znippy-plugin-git 0.1.6

Git object-store metadata plugin for znippy (native builtin — no WASM). Carries the reserved oid / commit-graph / reachability sub-indexes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
//! **`GitOps` — ours, typed, and base znippy never sees it.**
//!
//! §13.2: `ArchiveTypePlugin` is base znippy's contract and
//! [`crate::NativeGitPlugin`] implements it — base stores, the plugin annotates,
//! exactly as maven, python, rust-toolchain and media already work. `GitOps` is
//! the *other* trait: the one gunnar calls, with git's own vocabulary in it.
//!
//! §13.3: `ArchiveTypePlugin::run_command(cmd, args)` is **CLI-only string
//! dispatch** and delegates here. A server's hot path does not go through
//! stringly-typed dispatch, so nothing below takes a `&str` command or an
//! `args: &[String]`.
//!
//! ```text
//!   gunnar ──typed──► GitOps  (this file, twelve methods)
//!                       │
//!      ┌────────────────┼──────────────────┬─────────────┐
//!      ▼                ▼                  ▼             ▼
//!   ArchiveWrite    ObjectIndex          RefLog         Gc
//!   SafeWriter      ObjectReadStack      push log       NewGeneration
//!   (blob fsync,    (stree → Arrow       (Arrow IPC     (link, compact,
//!    journal row)    → redb tail)         frame = tx)    verify, rename)
//! ```
//!
//! Every arm under that diagram already existed and was already measured. This
//! file adds no storage, no index and no durability mechanism of its own — if a
//! method here looks like it is inventing one, that is a bug.
//!
//! # The one thing that is NOT here
//!
//! `run_command` still lives on the plugin in [`crate::lib`], and it now
//! delegates. Nothing git-shaped went into base znippy for any of this.

use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};

use anyhow::{anyhow, bail, Context, Result};
use znippy_common::ReservedSection;

use crate::arms::StoreConfig;
use crate::exploded::ExplodedStats;
use crate::exploded_cache::ExplodedCache;
use crate::gc::{Gc, GcReport};
use crate::graph::{assign_generations, CommitNode};
use crate::index_layout::{ObjectIndex, OneTableFourColumns};
use crate::indexer::{IndexJob, ObjectAbsorb, PushPath};
use crate::object::{GitHashKind, GitObjectKind};
use crate::pack_walk::PackWalk;
use crate::reach::ReachEntry;
use crate::read_stack::{ObjectReadStack, RebuildTriggers};
use crate::refs::{RefLog, RefUpdate};
use crate::resolve::BaseSource;

// ── the contract, now owned by `git-storage-trait` ────────────────────────────
//
// `GitOps` (the neutral ELEVEN) and its value types live in the
// `git-storage-trait` crate at this repo's root, so a gix backend
// (edda/storage-git-gix) can implement the same contract without linking Arrow
// or OpenZL. The twelfth method, `seal()`, returns `znippy_common::
// ReservedSection` (an Arrow type a gix backend has no analog for), so it is an
// **inherent** method on [`GitStore`] / [`SelectedStore`], not part of the
// trait. The re-exports below keep every existing path
// (`znippy_plugin_git::git_ops::{GitOps, Oid, …}`) alive.
pub use git_storage_trait::{Extent, GitOps, Oid, RefRow, Stored, TxId};


// ── the batch shape, which is measured and must not be papered over ───────────

/// Which path a lookup of `n` oids takes.
///
/// The number this dispatch was written for is `index_layout_bench`'s: on the bare
/// Arrow arms, `lookup_batch` with a **single** element costs 818 ns against
/// `lookup`'s 482 ns — 1.7x worse — because the batch path allocates a result
/// vector, a key vector and a second pass over them to serve one oid.
///
/// **RE-MEASURED against the shipping read stack, and the magnitude does not
/// carry over.** oden 2026-08-07, release, 1-min loadavg 4.94 (another tenant's
/// work — see LAW: never measure on a busy box, and read these as a ratio rather
/// than as absolutes), `ObjectReadStack<OneTableFourColumns>` over a real
/// repository's 2687-object pack, 20 000 iterations
/// ([`crate::store::tests::the_batch_of_one_really_is_slower_than_the_serial_path`]):
///
/// | call | per oid |
/// |---|---:|
/// | `lookup` | **628 ns** |
/// | `lookup_batch` with 1 oid | **639 ns** — 1.02x worse |
/// | `lookup_batch` with 100 oids | **161 ns** — 3.9x better |
///
/// So: the *direction* holds and the dispatch is right — a batch of one is never
/// faster — but on this stack at this size it costs 2%, not 70%. The real finding
/// is the third row: the batch path is worth **3.9x** at
/// [`BATCH_SATURATES_AT`], which is a much stronger reason to keep the two paths
/// apart than the batch-of-one penalty ever was. Both numbers are stated because
/// quoting only the 1.7x would be quoting a figure this stack does not reproduce.
///
/// The dispatch is a named function with its own guard precisely so it cannot
/// quietly become `lookup_batch` for every n.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LookupPath {
    /// One oid: `ObjectIndex::lookup`.
    Serial,
    /// Two or more: `ObjectIndex::lookup_batch`, one pass.
    Batch,
}

/// Oids at which the batch path stops getting faster. Reported, not enforced:
/// splitting a bigger batch would cost a pass and buy nothing.
pub const BATCH_SATURATES_AT: usize = 100;

/// The dispatch, in one place.
pub fn lookup_path(n: usize) -> LookupPath {
    if n == 1 {
        LookupPath::Serial
    } else {
        LookupPath::Batch
    }
}

// ── the store ─────────────────────────────────────────────────────────────────

/// A pack whose bytes are durable but whose objects the index has not absorbed.
///
/// §13.12's `indexed` bit, in the form this store needs it: membership in
/// [`PackState::pending`] *is* the bit being clear. A read that arrives while it
/// is non-empty falls back to absorbing it — slower, never wrong.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PendingPack {
    pack_id: u64,
    offset: u64,
    len: u64,
    /// The journal queued it on open (a restart), not a push in this process.
    /// What makes the progress row say `resumed 0%` after a reboot.
    resumed: bool,
}

impl PendingPack {
    fn from_job(j: IndexJob) -> Self {
        Self {
            pack_id: j.pack_id,
            offset: j.offset,
            len: j.len,
            resumed: false,
        }
    }
}

/// **§13.12's `indexed` bit — one bit per pack, indexed by pack ordinal.**
///
/// A plain bitset, and the two rejected alternatives say why:
///
/// * **not a hash set.** Pack ordinals are dense and small: they are assigned
///   `0..N` within **one repository** (§13.14 scopes a negotiation, and therefore
///   this store, to one repository — account-wide they would be sparse and the
///   array would grow with the account's total packs). Dense means the bit is one
///   shift and one AND with no hashing, and 10 000 packs is **1250 bytes** of
///   `words`, which lives in L1.
/// * **not a bloom filter.** A bloom's false positive would be *actively wrong*
///   here: it would report a pack absorbed when it is not, the read path would
///   stop falling back, and negotiation would be told `absent` about an object
///   whose bytes are durable — which makes a client withhold objects and lose
///   data. The bitset has no such mode. `1` means absorbed, `0` means fall back,
///   and both are exact.
///
/// **The bit is never stored.** It is derived on open by diffing two facts that
/// are already durable — the journal's extents against the index's rows — in
/// [`Absorber::adopt_journal`]. There is nothing for a derived bit to drift from.
///
/// **Why the extents sit beside it.** A `0` bit is only actionable with the
/// extent to absorb, so `extent[i]` carries it; `None` means "this store has not
/// been told about ordinal `i`", which is not the same as "not absorbed" and must
/// not be counted as work.
///
/// **Why `absorbed` is a separate fact from `extent`.** The ack path does two
/// things in this order: record the pack pending, then hand its extent to the
/// account's channel. The indexer's worker is a different thread and can reach
/// `absorb` *before* the first of those returns. With only a pending list, that
/// race ends in a bit that is set after the rows are already in and is never
/// cleared, so every later read pays a pointless fallback for the life of the
/// process. The bit is what the two writers agree on: [`PackState::note`] will
/// not queue a pack that is already done, and `absorb` will not do the work
/// twice.
///
/// Touched only under short critical sections — never across an absorb, which is
/// what the separate [`Absorber::gate`] is for. **The ack path must never block
/// behind index work.**
#[derive(Default)]
struct PackState {
    /// One bit per pack ordinal, 64 to a word. `1` = its rows are in the index.
    words: Vec<u64>,
    /// The extent of each known ordinal, so a `0` bit can be acted on.
    extent: Vec<Option<Extent>>,
    /// Known ordinals whose bit is `0` — what [`GitStore::unindexed_packs`]
    /// reports, kept as a count so the read path's check is a field load rather
    /// than a scan.
    unabsorbed: usize,
}

impl PackState {
    /// The bit.
    fn is_absorbed(&self, pack_id: u64) -> bool {
        let i = pack_id as usize;
        self.words
            .get(i / 64)
            .is_some_and(|w| w >> (i % 64) & 1 == 1)
    }

    /// Record a durable pack whose rows are not in yet. The bit **going clear**.
    ///
    /// **Idempotent, and the extent slot is the single thing that makes it so.**
    /// A second `note` for an ordinal that already has one — the ack path
    /// arriving after the drain has already absorbed the pack, or a re-queue on
    /// open racing the same pack's push — finds the slot filled and counts no new
    /// work. [`PackState::mark_absorbed`] fills that same slot, so a pack that is
    /// already done cannot be queued behind its own completion, and there is no
    /// second condition here that could disagree with the first.
    fn note(&mut self, pack_id: u64, extent: Extent) {
        let i = pack_id as usize;
        self.grow_to(i);
        if self.extent[i].is_none() {
            self.extent[i] = Some(extent);
            self.unabsorbed += 1;
        }
    }

    /// Room for ordinal `i` in both arrays. Dense ordinals are what makes this a
    /// `resize` and not an insert.
    fn grow_to(&mut self, i: usize) {
        if self.words.len() <= i / 64 {
            self.words.resize(i / 64 + 1, 0);
        }
        if self.extent.len() <= i {
            self.extent.resize(i + 1, None);
        }
    }

    /// The bit **going up**: this pack's rows are in the index.
    fn mark_absorbed(&mut self, pack_id: u64, extent: Extent) {
        let i = pack_id as usize;
        self.grow_to(i);
        if self.words[i / 64] >> (i % 64) & 1 == 0 {
            self.words[i / 64] |= 1 << (i % 64);
            if self.extent[i].is_some() {
                self.unabsorbed -= 1;
            }
        }
        self.extent[i] = Some(extent);
    }

    /// Every known pack whose bit is clear, in ordinal order.
    fn pending(&self) -> Vec<PendingPack> {
        self.extent
            .iter()
            .enumerate()
            .filter(|(i, e)| e.is_some() && !self.is_absorbed(*i as u64))
            .map(|(i, e)| {
                let (offset, len) = e.expect("filtered on Some");
                PendingPack {
                    pack_id: i as u64,
                    offset,
                    len,
                    resumed: true,
                }
            })
            .collect()
    }
}

/// The derived tables: the commit graph, the tree payloads the reachability
/// bitmaps are built from, and this store's own ordinal space.
///
/// **The ordinal space is this struct's, not the projection's.** An
/// [`crate::index_layout::IndexRow::ordinal`] is a row address inside one
/// projection generation and is re-derived by every rebuild, so a bitmap built
/// over projection ordinals would silently address different objects after any
/// rebuild. The bitmaps here are over `ordinal`, which is rebuilt in the same
/// fold that rebuilds them — the two cannot drift because one call produces both.
/// **Nothing in here is a source of truth.** Every field is folded from the
/// `objects` table and §14's exploded table by [`Absorber::refold`], and both of
/// those are on disk — which is what makes a clean reopen come back with the
/// same graph it shut down with. Before the exploded table existed, `graph` and
/// `trees` were *accumulated* here as packs were absorbed and stored nowhere, so
/// a clean shutdown lost them silently: MEASURED on oden 2026-08-08, a reopened
/// store over a fully absorbed 2687-object pack had all 2687 rows and **0 of 551
/// commits**, with `reachable()` returning a commit alone instead of its closure
/// and `gc` seeing an empty live set.
#[derive(Default)]
struct Derived {
    /// Parents-before-children, generations assigned. Folded from the exploded
    /// table's commit payloads.
    graph: Vec<CommitNode>,
    // **`trees` is GONE (lane Q, 2026-08-30).** It held every tree payload in
    // the repository, resident, keyed by a hex `String`, and was rebuilt from
    // the exploded table on every fold. MEASURED on the real `torvalds/linux`
    // mirror: 28.24 GB of tree payloads, 3.24× the 8.13 GiB pack, kept eagerly
    // on disk so this map could be rebuilt into a 50.9 GiB RSS — on a box that
    // ships with 16 GB. `crate::reach::TreeSource` replaced it with a lookup
    // ([`Absorber::tree_source`]), so a tree is read the way every other object
    // is: from the cache if it is there, from its own delta chain in the
    // mmapped pack if it is not.
    /// **The ordinal space, and the ONLY copy of it: every distinct oid in the
    /// store, raw, fixed-width, back to back, in oid-lexicographic order.**
    ///
    /// Ordinal `o` is the slice `oids_raw[o * oid_len .. (o + 1) * oid_len]`, and
    /// because the buffer is **sorted** the inverse (oid → ordinal) is a binary
    /// search over it — [`crate::reach::OrdinalSpace`] is that pair of lookups
    /// and owns nothing but a borrow of this field.
    ///
    /// # Why this is now the only representation
    ///
    /// It used to be one of THREE. `refold` also built `oids: Vec<String>` (the
    /// same list, hex) and `ordinal: HashMap<String, u32>` (the inverse, hex
    /// keys) — a 40-byte hex `String` per oid in the vector, a second as each
    /// map key, plus 20 raw bytes here. MEASURED, lane MEMORY, oden 2026-08-31
    /// (`examples/rss_per_open_store`): a cached open store cost **382 bytes of
    /// live RSS per indexed object** on a blob-only corpus and **744–966 B** on
    /// the two real repository packs — about half of it that pair. And it was
    /// paid twice at every fold: REFOLD measured the hex `Vec` at ~0.13 s and
    /// the `HashMap` at ~0.08 s of a 136k-object reopen, ~0.21 s spent turning
    /// bytes the tail already held into `String`-keyed tables.
    ///
    /// The flat buffer already answered both questions — a slice and a binary
    /// search — so the two `String`-per-oid tables were LAW 5's exact shape: a
    /// second and third spelling of one list that a comment had to *promise*
    /// agreed. They are gone; the serve path reads oid ⇄ ordinal straight off
    /// this buffer. See `gunnar/.nornir/stinky.md` S-082.
    ///
    /// # Why raw rather than hex
    ///
    /// Because every *serving* answer is built out of raw bytes.
    /// `reachable_raw` answers in oid bytes and each object is a
    /// `copy_from_slice` of a slice of this buffer — nothing is encoded,
    /// decoded or allocated per object. `reachable_oids` (the maintenance path)
    /// encodes on the way out, at one `String` per object, and nothing on the
    /// serve path calls it. The tail hands oids in oid order, which over
    /// fixed-width oids is byte order, so this is already the sorted
    /// concatenation with no sort of its own — see [`Absorber::refold`].
    oids_raw: Vec<u8>,
    /// The bitmaps, or empty if nothing has needed them since the last fold.
    ///
    /// **Behind an `Arc` since 2026-08-14, and that is a measurement and not a
    /// tidy-up.** [`Absorber::reach_bitmaps`] used to hand out `d.reach.clone()`
    /// — a deep copy of every commit's `RoaringBitmap` plus its oid `String` —
    /// and `crate::serve::GitServe::select` calls
    /// [`GitStore::reachable_oids`] **twice** per request (once for `want`, once
    /// to close over `have`). MEASURED on oden with `stage-probe`, the
    /// znippy-served `nornir` mirror (12 455 objects), a 4-object negotiated
    /// fetch: the `select.bitmap` stage was **75.2 % of the request's CPU** and
    /// **645 876 allocations**; at four requests sharing one warm store it was
    /// still 62 762 allocations *per request*. None of that copying is work the
    /// answer depends on — the table is immutable between folds — so the `Arc`
    /// removes it rather than dividing it across cores.
    reach: Arc<Vec<ReachEntry>>,
    /// Every commit's oid as **raw bytes**, the form
    /// [`crate::serve::GitServe::select`] tests a `want` against.
    ///
    /// `None` means a graph row's oid did not parse as hex, which `select`
    /// answers by declining the whole request. That check is why this is
    /// `Option` rather than a plain set: it used to run **per request** —
    /// `graph_snapshot()` cloned the whole `Vec<CommitNode>` and then
    /// `hex::decode`d every commit into a fresh `Vec<u8>` — and the answer
    /// cannot change between folds, so it is folded once here and borrowed
    /// after. The refusal is preserved exactly; only the arithmetic moved.
    commit_raw: Option<Arc<std::collections::HashSet<Vec<u8>>>>,
    /// **hex oid → index into [`Derived::graph`].** The graph-by-oid lookup
    /// [`crate::reach::accumulate`]'s walk needs, folded once by the same call
    /// that folds `graph` and `commit_raw` rather than rebuilt on every
    /// negotiation. `reachable` used to `d.graph.iter().map(...).collect()` a
    /// `HashMap<&str,&CommitNode>` per call — O(commits) per fetch, on every
    /// fetch and clone — for a table that cannot change between folds. MEASURED
    /// on oden 2026-09-01 (`bench_reachable_negotiation`, a 20 000-commit linear
    /// history): a negotiation over a one-object closure spent **895 µs**
    /// building this map and the reach one below, work the answer never used.
    /// It is keyed by hex, not raw, because the walk keys by hex — parents and
    /// tree oids in a [`CommitNode`] are hex — so a raw key would force a decode
    /// per walked edge to save the O(w+h) tip encode, a bad trade at any size.
    graph_index: HashMap<String, u32>,
    /// **hex commit oid → index into the [`Derived::reach`] table**, built by
    /// the same call that builds `reach` and cleared with it, so the pair is
    /// always in step. Replaces the per-call `HashMap<&str,&RoaringBitmap>`
    /// `reachable` rebuilt over every bitmap on every request. Behind an `Arc`
    /// for the same reason `reach` is: it is handed to the negotiation with a
    /// refcount bump, never a copy.
    reach_index: Arc<HashMap<String, u32>>,
    /// How many commits the graph held when [`Derived::reach`] was last built
    /// from scratch — the denominator of the carry rule in
    /// [`Absorber::refold`]. Bitmaps carried across a fold are exact for the
    /// commits they cover, but every commit added since is served by walking
    /// down to the nearest carried one, so once the additions outgrow
    /// [`REACH_CARRY_MAX`] of this the next reader rebuilds the table whole.
    reach_full_len: usize,
    /// Verbatim packs, so any absorbed object's content can be re-derived from
    /// the truth on demand. `(archive offset, len)`.
    packs: Vec<(u64, u64)>,
}

/// **The carry rule's ceiling**: a fold carries the reachability bitmaps
/// across when the graph has grown by at most this fraction of the commits the
/// last full build covered (and never fewer than 64 commits' worth). Beyond it
/// the table is rebuilt from scratch on the next read — which is what every
/// fold used to do, unconditionally.
///
/// MEASURED 2026-09-05 on oden (`gunnar serve`, a 10 000-commit / 51 023-object
/// repository over ssh): the FIRST clone after any push took 10.2 s and the next
/// 1.3 s, and after one more 4-object push the pattern repeated (10.9 s, then
/// 1.0 s). The fold had dropped `Derived::reach` and the next `reachable`
/// rebuilt every commit's tree closure — 0.2 ms per object of server CPU for a
/// push that changed nothing about any existing commit's reachability. A bitmap
/// is a fact about an immutable commit; only its ordinal numbering moves when
/// the sorted oid space grows, and a monotone remap costs one pass over the
/// bits. Sized at a tenth so the amortised rebuild stays bounded by the pushes
/// that earned it, like the persisted index's own fold threshold.
///
/// MEASURED AGAIN with the carry in place, same box, same repository, same
/// sequence (seed push, clone, clone, 4-object push, clone, clone): 10.5 s,
/// 1.15 s, then **1.12 s** and 1.15 s. The server logged the fold carrying all
/// 501 sampled entries, and the one 9.3 s build from scratch is the first
/// clone's, which no carry can serve. `reach_source_stats` is the same fact for
/// a test to assert.
pub(crate) const REACH_CARRY_MAX_FRACTION: usize = 10;
/// The floor under the rule, in commits: a repository small enough that a tenth
/// of it is a handful still carries across pushes of up to this many commits.
pub(crate) const REACH_CARRY_MIN_COMMITS: usize = 64;

/// **The object-level index, and the one thing that writes into it.**
///
/// Its own allocation rather than a field group inside [`GitStore`], and §13.9-12
/// is the only reason: the drain runs on the account indexer's worker thread, so
/// whatever it absorbs into cannot be reachable solely through a `&GitStore`.
/// Splitting it out is what lets the background worker and a falling-back read
/// call **the same** absorb instead of two copies of it (LAW 5) — the alternative
/// was a second implementation on the worker side, which is precisely the
/// twinning that law forbids.
///
/// It is a **leaf**: nothing in here points back at the store, so the worker's
/// `Arc` closes no cycle and the store still drops (and joins its worker)
/// normally.
/// Entries below which [`GitStore::resolve_emit_payloads`] does **not** fan out.
///
/// A `std::thread::scope` spawn is ~10–20 µs a worker and the per-entry work it
/// would divide is a bounds check plus a varint; a 100-object fetch would pay
/// four spawns to save four microseconds of parsing. The threshold is what keeps
/// `crate::serve`'s "one core's worth per transfer" true for every request that
/// is not a bulk clone — and a bulk clone is the only request the copy this
/// replaces was ever measured on.
const FAN_OUT_AT: usize = 4096;

/// The folded commit graph, cached beside the verbatim pack so a reopen *reads*
/// it instead of re-deriving it from every commit payload (S-065).
const GRAPH_CACHE_FILE: &str = "objects.graph";
/// `objects.graph` framing: 4-byte magic + 1-byte version + 32-byte token, then
/// the Arrow IPC commit graph.
const GRAPH_CACHE_MAGIC: &[u8; 4] = b"GRPH";
const GRAPH_CACHE_HEADER: usize = 4 + 1 + 32;

/// **`objects.ordinal` is no longer written, and an existing one is removed at
/// open.** It was S-082's memo of the ordinal space — every oid in sorted order,
/// with a `(epoch, count)` header validated against the redb tail — so that a
/// cold open could *read* the space instead of scanning the whole redb tail to
/// rebuild it. Since 2026-09-04 the read stack persists its projection
/// (`objects.index`) and the sorted oid list IS that index's oid column, mapped;
/// [`ObjectReadStack::oids_raw`] hands it back with a merge of the few redb rows
/// since the last fold. The scan the memo spared no longer exists, and a second
/// file carrying the same bytes under a bespoke header is exactly the kind of
/// file this store should not have. On the kernel mirror it was 278 964 902 B —
/// 20.0 B/object, the oid column to the byte. The name is kept only so the
/// stale file can be found and deleted.
const ORDINAL_CACHE_FILE: &str = "objects.ordinal";

/// The validity token for a persisted commit graph: blake3 over the sorted raw
/// oids of **every** object in the store.
///
/// It is both necessary and sufficient. The graph is a pure, deterministic
/// function of the commit payloads, which are content-addressed by their oids,
/// so an identical object set yields a byte-identical graph — and this hashes
/// the whole object set, in the one order `refold` already sorts it into, with
/// no read the fold did not already make. A mismatch (any push, any gc) forces a
/// recompute; a 256-bit blake3 makes an accidental match of two different object
/// sets not a case worth engineering against.
/// **`seen − live`: what a GC may drop.** `seen` is every oid the index held
/// when the GC started (`oids_in_order`), `live` the reachable set computed
/// after it. The difference is the dead set, and it is a POSITIVE set on
/// purpose: `retain(|o| live.contains(o))` would also drop every row that
/// arrived between the snapshot and the drop — a push in flight, whose refs
/// are not updated yet — because to `live` those are simply unknown. A row in
/// neither set is kept. `live` is hex, `seen` raw; the decode happens once
/// here rather than once per row in the retain predicate.
pub(crate) fn dead_oids(
    seen: Vec<Vec<u8>>,
    live: &std::collections::HashSet<String>,
) -> std::collections::HashSet<Vec<u8>> {
    let live_raw: std::collections::HashSet<Vec<u8>> =
        live.iter().filter_map(|h| hex::decode(h).ok()).collect();
    seen.into_iter().filter(|o| !live_raw.contains(o)).collect()
}

fn graph_token(oids_raw: &[u8]) -> [u8; 32] {
    let mut h = znippy_common::blake3::Hasher::new();
    h.update(oids_raw);
    *h.finalize().as_bytes()
}

/// Commits that get a reachability bitmap on the **live** selection path.
///
/// # It was `usize::MAX`, and that was the single most expensive line in a fetch
///
/// The comment that stood here said a sampled table *"is for the sealed archive
/// where the cost is disk"* and that every commit must be bitmapped on the live
/// path. That was not a preference, it was forced:
/// [`GitStore::reachable_oids`] had no walk, so a `want` with no bitmap could
/// only contribute itself — a silent under-send — and `crate::serve`'s `select`
/// therefore had to refuse unless *"in the graph"* and *"has a bitmap"* were the
/// same fact.
///
/// MEASURED on oden 2026-08-14, one 4-object negotiated fetch out of the
/// znippy-served `nornir` mirror (1 581 commits, 12 455 objects): the
/// `select.bitmap` stage was **75 % of the request's CPU**, and **530 218 of its
/// 575 349 allocations were this build** — which `refold` throws away again on
/// the next push. The gix arm answered the identical fetch in 6.8 ms because it
/// *reads* a `.bitmap` instead of building one.
///
/// [`crate::reach::accumulate`] is the walk that makes the cap legal, and 512 is
/// the number [`crate::reach::ReachPolicy::default`] already uses for the sealed
/// archive — the same figure git's own bitmap selection is of the order of, and
/// deliberately not a second, different constant to keep in step.
const LIVE_REACH_COMMITS: usize = 512;

/// [`LIVE_REACH_COMMITS`], or `ZNIPPY_GIT_REACH_COMMITS`.
///
/// **An operator knob, not an arm.** It selects no implementation and changes no
/// byte of any answer: the walk covers whatever the table does not, so the cap
/// trades build cost against walk cost and nothing else. That property is the
/// whole subject of
/// `the_bounded_walk_answers_exactly_what_a_full_bitmap_table_answers`, which
/// drives this very knob to its two extremes over one store.
///
/// Read **once per process** through [`crate::arms::read_env`], so it is
/// counted with every other environment read this crate makes, and so a
/// reachability request does not cost a `getenv` — until 2026-08-21 it did,
/// once per `reach_bitmaps`/`reachable_oids` call, uncounted.
fn live_reach_policy() -> crate::reach::ReachPolicy {
    static MAX: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    let max_commits = *MAX.get_or_init(|| {
        crate::arms::read_env(crate::arms::ENV_REACH_COMMITS)
            .and_then(|v| v.parse::<usize>().ok())
            .unwrap_or(LIVE_REACH_COMMITS)
    });
    crate::reach::ReachPolicy { max_commits }
}

/// Ceiling on phase-1 workers **per request**.
///
/// The serving tier admits ~32 concurrent transfers, and the fan-out primitive
/// has no reentrancy detection, so an uncapped `gatling_for_each` here is
/// 32 × ncores threads on a 128-core box. Four is a bound that leaves the
/// admission gate in charge of the machine.
const MAX_RESOLVE_WORKERS: usize = 4;

/// Workers for phase 1: [`MAX_RESOLVE_WORKERS`], or `ZNIPPY_GIT_EMIT_WORKERS`.
///
/// **An operator knob, not an arm.** It selects no implementation and changes no
/// byte of the emitted pack — a pack emitted at one worker and at sixteen is
/// byte-identical, because phase 1 only decides *where each entry's bytes are*
/// and phase 2 writes them in one serial order either way. `0` is read as "as
/// many as this box has cores", which is `gatling_for_each`'s own convention.
///
/// Read **once per process** through [`crate::arms::read_env`] — see
/// [`live_reach_policy`] for why; this one was a `getenv` per emitted request
/// until 2026-08-21.
fn emit_workers() -> usize {
    static WORKERS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *WORKERS.get_or_init(|| {
        crate::arms::read_env(crate::arms::ENV_EMIT_WORKERS)
            .and_then(|v| v.parse::<usize>().ok())
            .unwrap_or(MAX_RESOLVE_WORKERS)
    })
}

pub(crate) struct Absorber<S: ObjectIndex = OneTableFourColumns> {
    blobs: PathBuf,
    /// Read handle on the verbatim packs, for `pread` of an extent.
    ///
    /// The **fallback**, since 2026-08-14, not the ordinary path: `map` below
    /// answers every extent the mapping covers, and this reads the ones past its
    /// end (a push that landed after the snapshot was taken).
    ///
    /// **It is the writer's own open file description** (2026-08-30, lane AH),
    /// not a second `File::open`: this reads with `pread` at an explicit offset
    /// and shares no cursor with `append`, so a private descriptor bought a
    /// kernel object and a page-cache alias per open repository and no
    /// isolation. See [`crate::archive_write::open_blobs`] and
    /// `tests/fd_per_store.rs`.
    reader: Arc<File>,
    /// The same file, mapped read-only. See [`crate::archive_map`] for why an
    /// append-only file `gc` never rewrites is safe to map, and for the ~20 % of
    /// serve cycles the `pread`-per-object shape was spending on copies.
    map: crate::archive_map::ArchiveMap,
    hash: GitHashKind,
    /// The `objects` table: stree → Arrow → redb tail.
    ///
    /// `S` is the payload layout the projection is built in
    /// ([`crate::arms::IndexArm`]) and it is a **type parameter, not a field**:
    /// this is the hot path, every lookup goes through it, and the whole reason
    /// the arms exist is to measure the differences between them. A `dyn` here
    /// would put a virtual call on every single oid.
    objects: ObjectReadStack<S>,
    /// **§14's exploded objects table** — oid → resolved type and content, built
    /// eagerly by this absorb and by nothing else.
    ///
    /// Beside the `objects` table rather than inside it because the two have
    /// different lifetimes: `objects` is the index and losing it loses the
    /// repository's addressing, while this one is derived, verifiable against the
    /// verbatim bytes and deletable at any time. They are separate files so that
    /// "droppable" is a `rm`, not a schema migration.
    ///
    /// SWAPPED 2026-08-13 from the redb `ExplodedTable` to **one Arrow IPC
    /// table**, payload in the row. redb held 16.8 GB of kernel payload in a
    /// 204 GB file — 12× — and serialised the gatling fan-out behind its one
    /// writer at 96.8% of a single core. See [`crate::exploded_arrow`].
    ///
    /// **BUDGETED AND EVICTABLE since lane Q (2026-08-30)**: the two-pool
    /// [`ExplodedCache`] — the indexer's eager pool (commits and tags) beside a
    /// lazy pool the FIRST reader of a blob or tree fills and a byte budget
    /// empties. The unbounded eager tier it replaces MEASURED **141.7 GiB** for
    /// the 8.12 GiB `torvalds/linux` pack on the rig, 17× the pack, which is
    /// more than one appliance holds for all its repositories together.
    exploded: Arc<ExplodedCache>,
    derived: RwLock<Derived>,
    /// How many folds since open read the persisted commit graph off disk vs
    /// recomputed it from the exploded table. Counters, not clocks — the only
    /// thing that can say which path a fold took (LAW 2). See
    /// [`Absorber::graph_source_stats`].
    graph_read: std::sync::atomic::AtomicU64,
    graph_recomputed: std::sync::atomic::AtomicU64,
    /// **Is `objects.graph` read and written at all** ([`crate::arms::ENV_GRAPH_CACHE`],
    /// read once at open). `false` folds from the exploded table every time and
    /// leaves no file: a store that serves no reads holds no derived memo.
    graph_cache: std::sync::atomic::AtomicBool,
    /// How many folds CARRIED the reachability table across (renumbered, no
    /// tree opened) vs how many reads had to build it from scratch. The only
    /// witness that the carry ran — the bytes a carried and a rebuilt table
    /// answer with are identical by construction (LAW 2). See
    /// [`Absorber::reach_source_stats`].
    reach_carried: std::sync::atomic::AtomicU64,
    reach_rebuilt: std::sync::atomic::AtomicU64,
    /// Where the last fold's **ordinal space** came from: how many oids straight
    /// off the persisted index's column, how many off a scan of the redb tail.
    /// The same shape as [`Self::graph_read`]/[`Self::graph_recomputed`], and for
    /// the same reason: which source produced the space is not visible in the
    /// (identical) bytes, only in a counter (LAW 2). See
    /// [`Absorber::ordinal_source_stats`].
    ordinal_folded: std::sync::atomic::AtomicU64,
    ordinal_tail: std::sync::atomic::AtomicU64,
    packs: Mutex<PackState>,
    /// Serialises **absorption**, which is long. Held across a whole pack.
    ///
    /// Two absorbs of one pack are duplicated *work* and nothing worse: every
    /// writer under it is keyed by oid — [`ObjectReadStack::append`] swallows an
    /// identical second row, the exploded table overwrites its own key, and the
    /// commit graph is folded from that table rather than pushed at, so it cannot
    /// double. (It could before §14's table existed, when the graph was a `Vec`
    /// accumulated per absorb; that is why this paragraph used to say the gate
    /// was load-bearing for correctness and now does not.) The gate is still what
    /// makes the ordering below hold: **the rows go in, and only then is the bit
    /// cleared**, so a read either finds the bit still clear (and waits here) or
    /// finds the rows. Neither order can produce "absent".
    gate: Mutex<()>,
    /// **The progress counter** ([`crate::progress`]) a dashboard or a stats
    /// call reads. One per store, registered process-wide.
    progress: Arc<crate::progress::IndexProgress>,
    /// Set by [`GitStore::cancel_index`]: the repository is being deleted. The
    /// resolver checks it every few thousand objects and aborts the pack; the
    /// drain skips every pack still queued.
    cancel: std::sync::atomic::AtomicBool,
    /// Names the store in log lines: its root directory.
    label: String,
    /// The memory watchdog this store's worker pauses on. The process-wide one
    /// unless a test hands in a fake ([`GitStore::set_mem_watchdog`]).
    watchdog: RwLock<Arc<crate::memguard::MemWatchdog>>,
    /// **Pending packs a reader has already scanned**, keyed by pack offset:
    /// the walk and an oid-sorted row table, built by ONE read-only pass and
    /// kept until the pack is absorbed. Every later lookup into that pack is
    /// a binary search; a content read inflates one chain. Without this,
    /// every `has` during the index window re-resolved the whole pack —
    /// MEASURED on the rig 2026-08-30: a `push --mirror` of linux stalled
    /// pre-ack, ~800 ref updates × one 8 GiB resolve each.
    scanned: Mutex<HashMap<u64, Arc<ScannedPack>>>,
    /// One scan build at a time: a second reader waits for the first reader's
    /// pass rather than starting its own. That is waiting on a *reader*, not
    /// on the indexer.
    scan_build: Mutex<()>,
    /// **Packs this store has stopped trying to index**, by ordinal, with how
    /// many attempts it took to stop and the reason the last one gave.
    ///
    /// 🔴 The state this replaces was *no state*. A pack whose absorb failed
    /// stayed pending, every absorb loop hit it FIRST (they run in ordinal
    /// order) and aborted on it with `?`, so the packs behind it were never
    /// reached — and the next push, and the one after that, re-did the same
    /// doomed resolve and was refused for it. MEASURED on oden 2026-08-30
    /// (lane AI): one pack that could not be absorbed refused **every** push to
    /// that repository from then on, 21 of 140, and lane AD's standby re-asked
    /// for it every 300 s for 21 minutes. Work that cannot succeed has to stop
    /// and say why; see [`MAX_ABSORB_ATTEMPTS`] and [`Absorber::absorb_each`].
    unindexable: Mutex<HashMap<u64, Unindexable>>,
}

/// A pack this store will not try to index again, and why.
#[derive(Debug, Clone)]
pub struct Unindexable {
    /// The pack's ordinal.
    pub pack_id: u64,
    /// Its extent in the verbatim archive. The bytes are still there.
    pub extent: Extent,
    /// How many absorbs were spent before it stopped.
    pub attempts: u32,
    /// The last attempt's root cause — the backend's own sentence, which is
    /// what a client and an operator both get told.
    pub reason: String,
}

/// How many times one pack's absorb is attempted before the store stops.
///
/// Three, and the reason it is not one: an absorb can fail for a reason outside
/// the pack — the memory watchdog gave up, the repository was being deleted, a
/// transient read error — and a single bad moment must not condemn durable
/// bytes. It is not thirty either, because the resolve is deterministic in the
/// store's own state: a pack that failed three times with nothing else changing
/// fails the fourth time for the same reason, and every one of those attempts
/// is paid for by a client waiting on a push.
pub const MAX_ABSORB_ATTEMPTS: u32 = 3;

// **The pack this thread is inside an absorb of**, if any.
//
// `absorb_gated` holds `Absorber::gate` for the whole pack, and the resolver it
// runs asks this very store for delta bases through `BaseSource::content`. That
// re-entry must not take the gate again — a `std::sync::Mutex` is not
// reentrant, so it would not be a wait, it would be a deadlock — and it must
// not treat the pack it is halfway through as something it can absorb. One
// `Cell` answers both questions, and it is the same guard shape
// `scan_pending`'s `SCANNING` uses for the same reason.
thread_local! {
    static IN_ABSORB: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}

/// Sets [`IN_ABSORB`] for the duration of one absorb and restores whatever was
/// there before — absorbs nest (a pack whose base is in another pending pack).
struct InAbsorb(Option<u64>);

impl InAbsorb {
    fn enter(pack_id: u64) -> Self {
        InAbsorb(IN_ABSORB.with(|c| c.replace(Some(pack_id))))
    }
}

impl Drop for InAbsorb {
    fn drop(&mut self) {
        IN_ABSORB.with(|c| c.set(self.0));
    }
}

/// One pending pack, scanned read-only: what a lookup needs and nothing that
/// the index will hold. O(objects) memory — for linux ~56 B of walk + 32 B of
/// row per object, ~1.2 GB — and gone when the pack's bit goes up.
///
/// **Nothing on the production read path builds one of these any more.** A
/// reader that needs an un-indexed pack indexes it instead
/// ([`Absorber::index_pending_now`]); this remains for the one caller that
/// cannot — a resolver already inside `absorb_gated`, which may consult a scan
/// somebody else already built but must never start one.
struct ScannedPack {
    walk: crate::pack_walk::PackWalk,
    /// `(oid, entry index, resolved size)`, sorted by oid.
    rows: Vec<(Vec<u8>, u32, u64)>,
    archive_offset: u64,
}

impl ScannedPack {
    fn find(&self, oid: &[u8]) -> Option<(usize, u64)> {
        self.rows
            .binary_search_by(|(o, _, _)| o.as_slice().cmp(oid))
            .ok()
            .map(|i| (self.rows[i].1 as usize, self.rows[i].2))
    }

    fn row(&self, oid: &[u8]) -> Option<crate::index_layout::IndexRow> {
        let (entry, size) = self.find(oid)?;
        let e = &self.walk.entries[entry];
        Some(crate::index_layout::IndexRow {
            // Not ranked: the row is not in the index yet.
            ordinal: u32::MAX,
            offset: e.offset + self.archive_offset,
            len: e.len,
            obj_type: e.obj_type,
            uncompressed_size: size,
            delta_base: match &e.delta_base {
                crate::pack_walk::DeltaBase::Offset(o) => o + self.archive_offset,
                _ => 0,
            },
        })
    }
}

/// One repository's git store.
///
/// | on disk | what it is | who owns the format |
/// |---|---|---|
/// | `<root>/objects.pack` | the verbatim pack bytes, appended | [`SafeWriter`] |
/// | `<root>/objects.pack.journal` | the durable extent rows | [`SafeWriter`] |
/// | `<root>/objects.tail` | the un-sealed index tail | [`ObjectReadStack`] (redb) |
/// | `<root>/objects.exploded` | §14's resolved content, **droppable** | [`ExplodedArchive`] (one Arrow IPC table) |
/// | `<root>/refs.log` | the ref transaction log | [`RefLog`] (Arrow IPC frames) |
/// | `<root>/<name>.znippy` | the sealed archive GC compacts | base znippy |
///
/// Nothing in that table is new. The store is the composition, not a fifth
/// format.
/// # Which implementation of each trait, and how a caller picks
///
/// Three of the four boxes in the diagram at the top of this file have more than
/// one implementation. [`StoreConfig`] is the choice, [`crate::arms`] documents
/// what each arm promises, and the dispatch is split deliberately:
///
/// | trait | selected by | dispatch | cost |
/// |---|---|---|---|
/// | [`ObjectIndex`] | the type parameter `S` | **static** | none — the hot path is monomorphised |
/// | [`ArchiveWrite`](crate::archive_write::ArchiveWrite) | [`StoreConfig::writer`] | `dyn`, inside [`PushPath`] as it already was | one virtual call **per pack append**, not per object |
/// | [`Gc`] | [`StoreConfig::gc`] | `dyn` | one virtual call per `gc()` run |
///
/// `S` defaults to [`OneTableFourColumns`], so `GitStore` still names exactly
/// what it named before and every existing caller compiles unchanged.
pub struct GitStore<S: ObjectIndex = OneTableFourColumns> {
    root: PathBuf,
    /// The verbatim pack bytes. The **truth** (§14).
    blobs: PathBuf,
    /// The sealed znippy archive `gc` compacts. Only GC and `seal` touch it.
    archive: PathBuf,
    /// The selected [`ArchiveWrite`](crate::archive_write::ArchiveWrite) arm
    /// plus the per-account index channel. The ack path.
    push: PushPath,
    account: String,
    hash: GitHashKind,
    /// The object-level index and the absorb behind it — **shared with the
    /// account indexer's worker**, which is how a push ends in object rows
    /// without a read having to ask for them.
    absorber: Arc<Absorber<S>>,
    refs: RefLog,
    /// Serialises the ref log's read-compare-append. A CAS that read the
    /// namespace, then appended, without holding this could be overtaken between
    /// the two and would overwrite the update it did not see.
    ref_gate: Mutex<()>,
    /// The selected [`Gc`] arm. Built once, here, and run by
    /// [`GitOps::gc`] — a `Box<dyn>` because a GC is a whole-archive
    /// compaction that happens on a maintenance timer, so one virtual call
    /// against it is unmeasurable and a third type parameter on every signature
    /// in the crate is not free to read.
    gc: Box<dyn Gc + Send + Sync>,
    /// What this store was built with, for a bench row or a config dump. A
    /// description of the arms already constructed — **nothing consults it on a
    /// serving path**.
    arms: StoreConfig,
}

impl GitStore<OneTableFourColumns> {
    /// Open (creating) the store for one repository under `root`.
    ///
    /// **The default arms, and it reads no environment to get them.** An
    /// operator who exported `ZNIPPY_GIT_WRITER=fast` does not change what this
    /// builds — a caller that never asked for a selector must not have its
    /// durability contract moved out from under it. Use
    /// [`open_from_env`] when the selection is wanted.
    ///
    /// ⚠ One variable *is* read here, and it is not an arm:
    /// `ZNIPPY_GIT_REDB_CACHE_BYTES` (see
    /// [`crate::arms::redb_cache_bytes`]). It selects no implementation,
    /// changes no durability contract and leaves the bytes on disk identical —
    /// it caps redb's page cache, whose own default is 1 GiB *per database*, of
    /// which this store opens two. The sentence above is about arms, and a
    /// memory ceiling is not one.
    pub fn open(root: &Path, account: &str) -> Result<Self> {
        Self::open_with(root, account, GitHashKind::Sha1)
    }

    /// Same, with an explicit oid width. sha256 repositories exist and the store
    /// does not get to assume otherwise; every oid it stores is
    /// [`GitHashKind::oid_len`] bytes wide and the tail refuses a mixed batch.
    ///
    /// # What a reopen recovers, and why nothing had to be stored for it
    ///
    /// A store opened over an `objects.pack` some earlier process was still
    /// indexing has to end up in the same state that process would have reached.
    /// §13.12's `indexed` bit is what says so, and it is **derived here rather
    /// than persisted**: a pack is unabsorbed *iff* its extent is in the journal
    /// and its rows are not in the index, and both of those are already durable
    /// (see [`Absorber::adopt_journal`]). The packs that come back clear are put
    /// straight onto the account's channel, so the drain finishes the interrupted
    /// work with no read having to ask — and until it does, every read falls back
    /// exactly as it would have before the crash. **Slower, never wrong**, across
    /// a restart as well as within one.
    ///
    /// The bits are set **before** the channel is fed, which is the same ordering
    /// the ack path uses for the same reason: a read that arrives in between finds
    /// the bit clear and waits, never an index that does not mention the pack.
    ///
    /// # What a reopen recovers of the DERIVED tables, and how that was fixed
    ///
    /// [`Derived::graph`] and [`Derived::trees`] come back **in full**, for every
    /// pack, whether or not anything is re-queued. They are folded from §14's
    /// exploded table ([`Absorber::refold`]), which is on disk, so a clean
    /// shutdown carries them across.
    ///
    /// This was a live correctness hole until 2026-08-08 and it is recorded
    /// rather than quietly repaired. The graph was *accumulated in RAM* as packs
    /// were absorbed and stored nowhere; a store killed mid-absorb got it back
    /// because the interrupted pack was re-queued and re-resolved, but a store
    /// that shut down **cleanly** re-queued nothing and came back with an empty
    /// graph. MEASURED on oden 2026-08-08: 2687 rows and **0 of 551 commits**,
    /// `reachable` on a commit returning that commit alone instead of its
    /// closure — a *quiet* wrong answer — and `gc` seeing an empty live set. The
    /// fix is the table, because the payloads the graph is folded from had no
    /// home; [`tests::a_clean_shutdown_and_reopen_keeps_the_graph_and_reachable`]
    /// is what proves it, over a real process that exits normally.
    ///
    /// The exploded table is still **droppable**: if its row count is short of
    /// the `objects` table's, [`Absorber::adopt_journal`] declares no pack
    /// absorbed and every one of them is re-queued and re-exploded. Absent means
    /// rebuild, never wrong (§13.12, applied unchanged to a derived table).
    ///
    /// **Also the default arms, and also no environment read** — see
    /// [`open`](GitStore::open).
    pub fn open_with(root: &Path, account: &str, hash: GitHashKind) -> Result<Self> {
        // The default ARMS, and the environment's CEILING: the one variable
        // this constructor reads, because an operator capping a server's
        // footprint must not have to pick a different constructor to do it.
        // See [`crate::arms::redb_cache_bytes`].
        Self::open_with_arms(
            root,
            account,
            hash,
            StoreConfig::DEFAULT.with_redb_cache_bytes(crate::arms::redb_cache_bytes()?),
        )
    }
}

/// Where a stored entry's delta base sits, relative to the request being served.
///
/// The `Outside` arm carries the base in **both** namings because the two delta
/// forms know only one each — an `OFS_DELTA` its archive offset, a `REF_DELTA`
/// its oid — and [`GitStore::emit_set`]'s thin arm has to ask "does the client
/// hold this" in whichever one the entry speaks.
enum BaseOf {
    /// Not a delta at all. There is nothing to place it after and nothing to
    /// re-head; the stored entry is copied as it stands.
    Whole,
    /// A delta whose base **is** in the request, at this archive offset.
    ///
    /// The offset is carried rather than recomputed because a `REF_DELTA` does
    /// not know it — it names its base by oid, and its own `delta_base` column
    /// is `0` by construction — and the emitter needs it twice: as the
    /// `EmitEntry::delta_base` that [`crate::pack_walk::topological_order`]
    /// orders on, and as the base an in-pack ref-delta is re-headed to point at.
    Inside { at: u64 },
    /// A delta whose base the request does not carry.
    Outside {
        /// The base's archive offset, `0` when the entry named an oid instead.
        offset: u64,
        /// The base's oid, `None` when the entry named an offset instead — or
        /// when the entry is too short to read one out of.
        oid: Option<Vec<u8>>,
    },
}

/// The bases a **thin** pack may name without carrying them: what the receiver
/// already held before this transfer, keyed both ways.
///
/// Built by [`GitStore::client_bases`], which is where the argument for trusting
/// it is written down.
struct ExternalBases {
    /// The held object's oid, keyed by its archive offset — the coordinate an
    /// `OFS_DELTA` names its base in, and the only reason this map exists.
    by_offset: HashMap<u64, OidKey>,
    /// The same objects keyed the way a `REF_DELTA` names them.
    held: std::collections::HashSet<OidKey>,
}

/// **A raw oid as a fixed-size, `Copy` hash key — 20 bytes for SHA-1, 32 for
/// SHA-256, and no heap allocation either way.**
///
/// The two maps in [`ExternalBases`] are repository-sized: the client's `have`
/// closure on an incremental fetch is very nearly every object in the store.
/// Keying them by `Vec<u8>` is one heap allocation per entry per request —
/// 12 112 of them for a 69-object fetch, measured on oden 2026-08-15 — for a
/// question (*does the client hold this base?*) that never looks at more than
/// `oid_len` bytes.
///
/// Padded to the widest hash rather than parameterised by width: a store holds
/// exactly one hash kind, so every key in one set has the same real length and
/// two different oids can never collide through the padding. The length is
/// carried anyway, because a key that silently compared equal across widths is
/// the kind of wrong that only shows up in a mixed-hash mirror.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct OidKey {
    bytes: [u8; 32],
    len: u8,
}

impl OidKey {
    /// The key for `oid`, or a refusal for one wider than any git hash.
    fn new(oid: &[u8]) -> Result<Self> {
        let len = oid.len();
        if len == 0 || len > 32 {
            bail!("{len} is not the width of any git object id (1..=32 bytes)");
        }
        let mut bytes = [0u8; 32];
        bytes[..len].copy_from_slice(oid);
        Ok(OidKey {
            bytes,
            len: len as u8,
        })
    }

    /// The oid back, at its real width.
    fn as_slice(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }
}

impl<S: ObjectIndex + 'static> GitStore<S> {
    /// **The one constructor**, with every arm named.
    ///
    /// `S` picks the [`ObjectIndex`] layout at compile time; `arms` picks the
    /// [`ArchiveWrite`](crate::archive_write::ArchiveWrite) and [`Gc`]
    /// implementations at run time. [`open`](GitStore::open) and
    /// [`open_with`](GitStore::open_with) are this function with
    /// [`StoreConfig::DEFAULT`], which is why nothing about them moved.
    ///
    /// `arms.index` is **not** consulted here — `S` is the index arm, and a
    /// value that disagreed with the type would be a second source of truth.
    /// [`open_from_env`] is the one place the two are tied together, and it does
    /// it by choosing `S` from the value.
    ///
    /// ```no_run
    /// use znippy_plugin_git::arms::{GcArm, StoreConfig, WriterArm};
    /// use znippy_plugin_git::index_layout::PackedPayload;
    /// use znippy_plugin_git::{GitHashKind, GitStore};
    ///
    /// // A rebuildable import mirror: the ceiling writer, the packed payload
    /// // layout, and an in-place compaction.
    /// let arms = StoreConfig::DEFAULT
    ///     .with_writer(WriterArm::Fast)
    ///     .with_gc(GcArm::CompactInPlace);
    /// let store = GitStore::<PackedPayload>::open_with_arms(
    ///     std::path::Path::new("/srv/repo"),
    ///     "rickard",
    ///     GitHashKind::Sha1,
    ///     arms,
    /// )?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn open_with_arms(
        root: &Path,
        account: &str,
        hash: GitHashKind,
        arms: StoreConfig,
    ) -> Result<Self> {
        std::fs::create_dir_all(root)
            .with_context(|| format!("creating the store root {}", root.display()))?;
        let blobs = root.join("objects.pack");
        let writer = arms.writer.create(&blobs)?;
        // `None` for an arm that keeps no durable ack log — see
        // [`crate::arms::WriterArm::journal`]. Everything below that touches the
        // journal is written against that `Option` rather than assuming one.
        let journal = arms.writer.journal(&blobs);
        // **The redb ceiling**, carried in on the config rather
        // than read here: `StoreConfig::from_env` reads it with the arms, and
        // `open`/`open_with` put the environment's value on `DEFAULT` before
        // getting here, so every constructor still honours the variable and
        // `arms.to_string()` prints what was actually applied. Not an arm — see
        // [`crate::arms::redb_cache_bytes`] — redb's own default is 1 GiB *per
        // database*, and this store opens exactly ONE of them, the
        // `ObjectReadStack` below. The `let _ = cache_bytes` two lines down is
        // what is left of the second.
        let cache_bytes = arms.redb_cache_bytes;
        let objects = ObjectReadStack::<S>::open(
            &root.join("objects.tail"),
            RebuildTriggers::default(),
            cache_bytes,
        )?;
        let _ = cache_bytes; // no page cache to size: the blob is pread, the index is a slice
        // A store written before 2026-09-04 carries `objects.ordinal`, the memo
        // of the sorted oid list the read stack's persisted index now IS. Its
        // bytes are never read again, so it goes on the first open by this
        // build — 278 964 902 B on the kernel mirror. Absent is the normal case
        // and not an event; anything else that stops the delete is logged, not
        // fatal, because the store does not depend on the file being gone.
        match std::fs::remove_file(root.join(ORDINAL_CACHE_FILE)) {
            Ok(()) => tracing::info!(
                target: "znippy.git",
                path = %root.join(ORDINAL_CACHE_FILE).display(),
                "removed a stale objects.ordinal — the persisted index's oid column is the \
                 ordinal space now"
            ),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => tracing::warn!(
                target: "znippy.git",
                path = %root.join(ORDINAL_CACHE_FILE).display(),
                error = %e,
                "could not remove a stale objects.ordinal; it is dead weight, not a fault"
            ),
        }
        let exploded = Arc::new(ExplodedCache::open(
            &root.join("objects.exploded"),
            crate::exploded_arrow::ExplodePolicy::from_env()?,
            crate::exploded_cache::budget_from_env(root)?,
        )?)
        .registered();
        // **One descriptor on the blob file, not three.** The writer opened it
        // read/write and `flock`ed it; the absorber's `pread` fallback and the
        // index workers' `read_exact_at` both address it positionally, so they
        // take the same open file description rather than two more of their
        // own. 5 descriptors per open store → 3, which is the divisor of
        // gunnar's `open_repo_budget` (`tests/fd_per_store.rs`).
        let absorber = Arc::new(Absorber::<S>::open(
            &blobs,
            writer.blobs_shared(),
            hash,
            objects,
            exploded,
        )?);

        // **The `indexed` bit, derived.** Every extent this archive has ever
        // acked, diffed against the rows the index holds. `SafeWriter::create`
        // above appends to that journal and never truncates it, which is what
        // makes the older extents still be here to diff against.
        //
        // An arm with no journal has nothing to derive the bit from, and that is
        // the honest consequence of choosing it rather than a gap: a
        // `FastWriter` store has no durable record that a pack was acked, so a
        // reopen re-queues nothing and there is nothing for it to re-queue.
        let acked = match journal.as_deref() {
            Some(p) if p.exists() => crate::archive_write::read_journal(p).with_context(|| {
                format!(
                    "reading {} — it is the durable half of the indexed bit and a store \
                         cannot be opened without knowing which packs it owes index work for",
                    p.display()
                )
            })?,
            _ => Vec::new(),
        };
        let requeue = absorber.adopt_journal(&acked)?;

        // **The wiring.** The absorber goes into the push path, which hands it to
        // every account indexer it starts, so the drain behind `push_pack` ends
        // in object rows instead of one pack row. Nothing about the ack changes:
        // `append` still returns after the two fsyncs and this is all downstream
        // of that (§13.9).
        let push = PushPath::with_absorber(
            writer,
            &blobs,
            journal,
            absorber.clone() as Arc<dyn ObjectAbsorb>,
        )?;
        let refs = RefLog::new(root.join("refs.log"));
        let archive = root.join("repository.znippy");

        let store = Self {
            root: root.to_path_buf(),
            blobs,
            archive,
            push,
            account: account.to_string(),
            hash,
            absorber,
            refs,
            ref_gate: Mutex::new(()),
            gc: arms.gc.create(),
            arms,
        };
        // The interrupted work, back on the channel it fell off. Nothing reads
        // here and nothing blocks: this is the same 24-byte handoff a push makes,
        // and the drain picks it up on its own thread (§13.9-11).
        let indexer = store.push.indexer(&store.account);
        for p in &requeue {
            indexer.submit(IndexJob {
                pack_id: p.pack_id,
                offset: p.offset,
                len: p.len,
            })?;
        }
        // A store reopened over an existing tail already knows its objects; the
        // derived tables are rebuilt from them rather than from a side-car,
        // because a side-car is a second truth.
        store.refold()?;
        Ok(store)
    }

    /// The arms this store was built with. A description of what was
    /// constructed, not a switch — nothing on a serving path reads it.
    pub fn arms(&self) -> StoreConfig {
        self.arms
    }

    /// The selected writer's name, as it goes on a bench row.
    pub fn writer_name(&self) -> &'static str {
        self.push.name()
    }

    /// What the selected writer's `append` actually promises. Printed next to a
    /// throughput, because a throughput without it is not a comparison.
    pub fn writer_durability(&self) -> &'static str {
        self.push.durability()
    }

    /// The selected [`Gc`] arm.
    pub(crate) fn gc_arm(&self) -> &dyn Gc {
        self.gc.as_ref()
    }

    /// Where the verbatim packs are.
    pub fn blobs_path(&self) -> &Path {
        &self.blobs
    }

    /// The sealed archive GC operates on.
    pub fn archive_path(&self) -> &Path {
        &self.archive
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn hash_kind(&self) -> GitHashKind {
        self.hash
    }

    /// The `objects` table, for a caller that wants the index directly (the
    /// bench does).
    pub fn index(&self) -> &ObjectReadStack<S> {
        &self.absorber.objects
    }

    /// Objects in the `objects` table.
    pub fn object_count(&self) -> usize {
        self.absorber.objects.len()
    }

    /// Commits in the graph.
    pub fn commit_count(&self) -> usize {
        self.absorber
            .derived
            .read()
            .expect("derived lock")
            .graph
            .len()
    }

    /// `(graph_read_from_disk, graph_recomputed)` since this store was opened —
    /// how many folds read the persisted `objects.graph` vs re-derived it.
    pub fn graph_source_stats(&self) -> (u64, u64) {
        self.absorber.graph_source_stats()
    }

    /// `(reach_carried, reach_rebuilt)` since this store was opened — how many
    /// folds carried the reachability table across (renumbered, no tree
    /// opened) vs how many reads built it from scratch. The witness for the
    /// clone-after-push lever; see `REACH_CARRY_MAX_FRACTION`.
    pub fn reach_source_stats(&self) -> (u64, u64) {
        self.absorber.reach_source_stats()
    }

    /// `(folded_rows, tail_rows)` of the ordinal space the last fold built — how
    /// many oids came off the persisted index's oid column and how many off a
    /// scan of the redb tail. Replaces S-082's `(read, recomputed)`: there is no
    /// memo to read any more, the index IS the space.
    pub fn ordinal_source_stats(&self) -> (u64, u64) {
        self.absorber.ordinal_source_stats()
    }

    /// The folded ordinal space — every oid in ordinal order, hex. For the tests
    /// that assert a memo read reproduces the scanned space exactly (same oids,
    /// same order, same ordinals — the ordinal is the index into this vector).
    ///
    /// Formatted on demand from `oids_raw`: there is no resident hex `Vec` any
    /// more (S-082), and a test that wants hex encodes the flat buffer here
    /// rather than the store carrying a second copy for it.
    #[cfg(test)]
    pub(crate) fn ordinal_oids(&self) -> Vec<String> {
        let oid_len = self.hash.oid_len();
        self.absorber
            .derived
            .read()
            .expect("derived lock")
            .oids_raw
            .chunks_exact(oid_len)
            .map(hex::encode)
            .collect()
    }

    /// **One object's resolved content** — §14's exploded table, in one lookup.
    ///
    /// Not one of the twelve and deliberately not on [`GitOps`]: the twelve are
    /// the wire vocabulary and they hand back **stored** bytes ([`GitOps::get`]),
    /// which for a delta entry is a delta. This is the other question — *what
    /// does this object contain* — and it is the one §14's table exists to make
    /// a point lookup instead of a chain walk.
    ///
    /// It absorbs any pending pack first, for the same reason
    /// [`GitOps::has`] does: a store with durable bytes it has not indexed cannot
    /// answer "absent" without lying.
    pub fn content(&self, oid: Oid<'_>) -> Result<Option<(GitObjectKind, Vec<u8>)>> {
        // No absorb here any more: a pack the worker has not reached is read
        // for this one oid by `Absorber::resolved`'s third arm — on this thread,
        // from the mmapped pack, without waiting for the worker.
        self.absorber.resolved(oid)
    }

    /// **One object, with the bill for producing it.**
    ///
    /// [`Self::content`] plus what the read cost: `None` for a cost when the
    /// exploded pools answered (nothing was rebuilt), `Some(cost)` when the
    /// object was inflated out of the pack. What a measurement needs and a
    /// server does not — the cache admission decision is made inside, not by
    /// the caller.
    pub fn content_costed(
        &self,
        oid: Oid<'_>,
    ) -> Result<Option<(GitObjectKind, Vec<u8>, Option<crate::resolve::ReadCost>)>> {
        self.absorber.resolved_costed(oid)
    }

    /// §14's table, counted: rows, rows written, reads it served, reads that fell
    /// through to re-deriving from the verbatim truth.
    ///
    /// Applied output. Both content paths return identical bytes, so `served`
    /// against `rederived` is the only thing that can say which one ran.
    pub fn exploded_stats(&self) -> ExplodedStats {
        self.absorber.exploded.engine_stats()
    }

    /// **What the exploded tier is holding and what it is allowed to hold** —
    /// the row a dashboard prints (`explode 3.1G/8G`) and `Admin.StorageInfo`
    /// carries, per repository.
    pub fn explode_cache_use(&self) -> crate::exploded_cache::CacheUse {
        self.absorber.exploded.use_now()
    }

    /// Rows in the EAGER pool only — the graph the push wrote, with nothing a
    /// reader has since cached. What `adopt_journal` compares against the index
    /// and what a test asking "did the push explode the graph" must ask,
    /// because [`Self::exploded_stats`]'s `rows` counts both pools and a read
    /// moves it.
    pub fn exploded_eager_rows(&self) -> Result<u64> {
        self.absorber.exploded.eager_rows()
    }

    /// **Set this repository's explode budget** — what the control plane calls
    /// when an account's quota changes. Takes effect at the next rotation; it
    /// never refuses a read, never refuses a write and never deletes on the
    /// caller's thread. A bigger budget buys a bigger cache and therefore faster
    /// first reads; a smaller one costs re-inflation, never an error.
    pub fn set_explode_budget(&self, bytes: u64) {
        self.absorber.exploded.set_budget(bytes);
    }

    /// Flush the lazy pool, rotate it and evict it back under budget — on
    /// **this** thread. What a test and a `gc` call; a reader never does, it
    /// starts a write-back thread and walks away.
    pub fn explode_cache_maintain(&self) -> Result<u64> {
        self.absorber.exploded.maintain()
    }

    /// **`repo gc` reclaims the cache**: every lazy segment unlinked, the graph
    /// pool kept. Returns the bytes that left the filesystem.
    pub fn drop_explode_cache(&self) -> Result<u64> {
        self.absorber.exploded.drop_cache()
    }

    /// Where §14's table lives. Deleting this file while no store holds it is the
    /// sanctioned way to drop it; the next open re-explodes every pack.
    pub fn exploded_path(&self) -> &Path {
        self.absorber.exploded.path()
    }

    /// Every live row of one kind, with its payload — what the graph fold reads,
    /// exposed so a measurement can ask **the table** how many bytes it holds
    /// rather than dividing a file size by what the pack claimed.
    pub fn exploded_of_kind(&self, kind: GitObjectKind) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
        self.absorber.exploded.of_kind(kind)
    }

    /// The commit graph as it stands, generations included. A snapshot: the
    /// caller holds no lock and the next fold replaces it wholesale.
    pub fn graph_snapshot(&self) -> Vec<CommitNode> {
        self.absorber
            .derived
            .read()
            .expect("derived lock")
            .graph
            .clone()
    }

    /// Packs whose objects are not in the index yet — §13.12's bit, counted.
    pub fn unindexed_packs(&self) -> usize {
        self.absorber.unindexed_packs()
    }

    /// This account's indexer: the thread that drains the channel a push queues
    /// on. `is_indexed(pack_id)` on it is §13.12's bit at the pack level, and it
    /// is set only once that pack's **objects** are in the index.
    pub fn indexer(&self) -> std::sync::Arc<crate::indexer::AccountIndexer> {
        self.push.indexer(&self.account)
    }

    /// Block until the background drain has absorbed everything this store has
    /// pushed. What a maintenance tick, a seal or a test uses instead of racing
    /// it.
    pub fn wait_indexed(&self) {
        self.push.pool().wait_caught_up();
    }

    /// **Stop this store's index work — the repository is being deleted.**
    ///
    /// Sets the cancel flag the resolver polls every few thousand objects and
    /// the drain checks before every pack. The pack in flight is **aborted at
    /// its next checkpoint** (milliseconds), not finished: its rows are keyed
    /// by oid and the exploded tier is droppable, and the whole directory is
    /// about to be removed anyway. Every pack still queued is skipped. After
    /// this the store can be dropped without the drop joining a worker that is
    /// hours into a kernel pack — which is what `Drop for AccountIndexer` would
    /// otherwise do.
    pub fn cancel_index(&self) {
        self.absorber.cancel.store(true, std::sync::atomic::Ordering::SeqCst);
        self.push.pool().cancel_all();
    }

    /// Put a different memory watchdog under this store's worker — a test's
    /// fake `/proc/meminfo`. Takes effect from the next pack.
    pub fn set_mem_watchdog(&self, dog: Arc<crate::memguard::MemWatchdog>) {
        *self.absorber.watchdog.write().unwrap_or_else(|e| e.into_inner()) = dog;
    }

    /// Has [`cancel_index`](Self::cancel_index) been called?
    pub fn index_cancelled(&self) -> bool {
        self.absorber.cancel.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// This store's index progress counter, for a dashboard or a stats call.
    pub fn index_progress(&self) -> crate::progress::Snapshot {
        self.absorber.progress.snapshot()
    }

    /// **The indexer's half of the split**, and not one of the twelve.
    ///
    /// Runs on the account indexer's worker (§13.9), and on a read that arrives
    /// before that worker got there — the same function either way, which is why
    /// there is no such thing as a background index that behaves differently from
    /// the fallback one.
    pub fn absorb_pending(&self) -> Result<usize> {
        self.absorber.absorb_pending()
    }

    /// **Make every durable object addressable, on this thread, now** —
    /// [`git_storage_trait::GitServe::index_now`]'s implementation and the ack
    /// path's one call. See [`Absorber::index_pending_now`] for why the
    /// connectivity check is the only caller allowed to wait here.
    pub fn index_now(&self) -> Result<usize> {
        self.absorber.index_pending_now()
    }

    /// **The packs this store has stopped trying to index**, with the reason
    /// each one stopped for.
    ///
    /// Empty is the ordinary answer and the only good one. A non-empty list is
    /// a repository that is missing objects whose bytes are durable, and it is
    /// the fact an operator needs before wondering why a push was refused or a
    /// standby is behind — see [`MAX_ABSORB_ATTEMPTS`].
    pub fn unindexable_packs(&self) -> Vec<Unindexable> {
        self.absorber.unindexable_packs()
    }

    /// **The object ids a stored pack introduced**, and not one of the twelve.
    ///
    /// [`GitOps::put_pack`] cannot answer this and never will: the walk it does
    /// reads pack *entries*, and a pack entry does not carry its oid — that is
    /// why [`crate::pack_walk::Closure`] can only name the `REF_DELTA` bases and
    /// says so. The oids exist once the indexer has absorbed the pack, so this
    /// absorbs first rather than racing the drain, and is therefore the one
    /// caller that deliberately pays §13.9's deferral back.
    ///
    /// **Only call it when something needs the set.** A push whose policy has no
    /// gate over objects must not pay this, which is the whole reason it is a
    /// separate call and not a field on `TxId`.
    ///
    /// The extent *is* the identity: §14 stores a pack verbatim as one
    /// contiguous append, so "introduced by this pack" and "indexed at an offset
    /// inside this pack's extent" are the same set, with no pack column to keep
    /// in step. Bases the push deltas against live in *other* extents and are
    /// excluded by construction — which is what a thin push needs, and what
    /// reading a written `.idx` back could never do.
    ///
    /// Cost is one pass over the index, so it is O(objects in the repository),
    /// not O(objects pushed). Recorded rather than hidden: a per-pack ordinal
    /// range would make it O(pushed), and needs the indexer to keep one.
    pub fn oids_in_extent(&self, extent: Extent) -> Result<Vec<Vec<u8>>> {
        let (start, len) = extent;
        // **Never waits on the indexer.** If the gate is free this thread
        // absorbs the pending packs (the same work, done now, by the caller
        // that needs it); if the worker holds it, the extent is resolved
        // read-only on this thread and its oids are the answer — the same
        // resolver, no sink, no rows written.
        if self.try_absorb_pending()?.is_none() {
            let snap = self.archive_snapshot()?;
            let bytes = self.extent(&snap, start, len)?;
            let walked = crate::pack_walk::walk(&bytes, self.hash.oid_len())?;
            let mut oids: Vec<Vec<u8>> = Vec::with_capacity(walked.entries.len());
            let limits = crate::resolve::ResolveLimits {
                base_budget: (crate::resolve::base_budget_from_env() / 4).max(1),
                ..crate::resolve::ResolveLimits::none()
            };
            crate::resolve::resolve_streaming(
                &bytes,
                &walked,
                self.hash,
                start,
                &*self.absorber,
                &crate::exploded::NoSink,
                limits,
                &mut |rows| {
                    oids.extend(rows.drain(..).map(|r| r.oid));
                    Ok(())
                },
            )
            .context("resolving the pushed pack read-only to enumerate its objects")?;
            return Ok(oids);
        }
        let end = start.saturating_add(len);
        let all = self.index().oids_in_order()?;
        let refs: Vec<&[u8]> = all.iter().map(Vec::as_slice).collect();
        let extents = self.index().extents_batch(&refs);
        Ok(all
            .into_iter()
            .zip(extents)
            .filter_map(|(oid, at)| match at {
                Some((offset, _)) if offset >= start && offset < end => Some(oid),
                _ => None,
            })
            .collect())
    }

    /// **Everything needed to emit a pack for EXACTLY `oids`** — nothing added,
    /// nothing dropped.
    ///
    /// Not one of the twelve. It sits beside [`absorb_pending`](Self::absorb_pending)
    /// for the same reason those do: it is about how storage is *shaped*, not
    /// about what a caller stores or reads.
    ///
    /// # 🔴 It used to add the delta bases, and that shipped broken clones
    ///
    /// Until 2026-08-11 this closed the request over its delta bases: an
    /// `OFS_DELTA` names its base by position, so a base outside the set cannot
    /// be encoded, and *adding the base* looked like the answer that is always
    /// safe. It is not, and the failure is silent on the server:
    ///
    /// ```text
    /// git clone --bare --single-branch --branch base <url>
    ///     fatal: did not receive expected object 8601ec33920b7d701c9887fa04916501136d6e90
    ///     fatal: fetch-pack: invalid index-pack output
    /// event="git.upload_pack.served" objects=33773      ← the server said SUCCESS
    /// ```
    ///
    /// Measured on the `h2h-linear-sha1-2048c-1024f-16k` fixture: `base` reaches
    /// **31 805** objects, the delta-base closure added **1 968** more — 33 773,
    /// exactly the count the server logged — and 507 of those additions were
    /// **trees**. A tree that is not reachable from the wants drags its own
    /// children in as a *requirement*, because `git index-pack
    /// --check-self-contained-and-connected` (which is what a clone runs, and
    /// which sets `strict`) walks every received object's links and then demands
    /// each one exist. Those 507 trees named **204** objects the pack did not
    /// contain. `8601ec33…` is one of them.
    ///
    /// So a delta base pulled into a narrowed request is not free: it satisfies
    /// the *pack format* and violates *connectivity*. Closing over the added
    /// bases' children in turn does terminate — the same fixture reaches a fixed
    /// point at 34 534 objects — but it is an over-send by construction, and on
    /// a `--filter=blob:none` fetch it adds back exactly the blobs the filter
    /// excluded, which is the defect
    /// `emit_pack_emits_exactly_the_set_it_is_given_and_never_its_closure`
    /// exists to forbid.
    ///
    /// # What it does instead: the base decides how the entry is encoded
    ///
    /// The set is never widened. For each requested object:
    ///
    /// * **base inside the request** → the stored entry is copied byte for byte,
    ///   which is the whole point of this engine and is what a full clone does
    ///   for every single object;
    /// * **base outside the request** → the entry is **rebuilt** from §14's
    ///   resolved content and marked
    ///   [`EmitEntry::recompressed`](crate::pack_walk::EmitEntry::recompressed) —
    ///   as a computed delta against a base the request *does* carry where one
    ///   can be found (see [`Self::in_request_chain_ancestor`] and
    ///   [`crate::delta`]), and whole where it cannot.
    ///
    /// That is what stock `pack-objects` does — it reuses a stored delta only
    /// when the base is also being packed — and it keeps the receipt a fact:
    /// `copied` and `recompressed` add up to the objects written, and
    /// `recompressed` is **0 for a whole-repository clone** because such a
    /// selection contains every base. The cost lands on the boundary a narrowed
    /// request cuts through and nowhere else: 1 968 of 33 773 entries, 5.9 %, on
    /// the fixture above.
    ///
    /// `ofs_delta_ok` is the client's `ofs-delta` capability. An old client that
    /// cannot parse one is not refused any more: the entry is re-headed as a
    /// `REF_DELTA` naming its base by oid, **carrying the same compressed delta
    /// payload**, so that arm stays a copy too. Only a base outside the request
    /// costs a rebuild.
    ///
    /// # `thin_haves` — the boundary entry that does NOT have to be rebuilt
    ///
    /// `Some(tips)` says the client consented to a thin pack *and* the
    /// negotiation found common ground; [`crate::serve::GitStore::emit_oids`] is
    /// where the two halves are required together, because either alone is a
    /// failed fetch rather than a smaller one. Given it, a base outside the
    /// request is checked against [`the client's own objects`](GitStore::client_bases),
    /// and one the client already holds is named by oid in a `REF_DELTA` that
    /// carries the **stored delta stream unchanged**. That entry counts as
    /// `copied`, because it is: nothing was inflated and nothing was deflated.
    ///
    /// `None` — a clone, or a client that did not ask for a thin pack — behaves
    /// exactly as before, and a **full clone is byte-identical either way**,
    /// because a whole-repository request has no base outside itself for any of
    /// this to apply to.
    ///
    /// It does nothing for the *clone* half of the boundary cost, and cannot: a
    /// clone's receiver holds nothing, so there is no external base to name.
    /// That half is the arm below it — [`crate::delta`] computes a delta against
    /// something the pack **does** carry, which is the only move left when there
    /// is no receiver to lean on. The two do not overlap: `thin_haves` reaches a
    /// boundary entry first and costs nothing when it fires, so a fetch stays a
    /// pure copy and only a clone pays for a computed delta.
    ///
    /// # An oid this repository does not hold is REFUSED
    ///
    /// It used to be skipped, which is the same silent-under-send shape as the
    /// closure defect above wearing a different hat: N asked, N-1 emitted,
    /// `PackStats` reporting success, and the client the first to know. gunnar's
    /// in-memory arm has always refused it, so the skip also meant the two
    /// engines behind one contract disagreed about what a missing object means.
    /// A partial-clone filter does not depend on the skip and cannot: a filter
    /// *removes* oids from the selection, it never adds one the store lacks.
    ///
    /// # Cost
    ///
    /// O(objects requested). The previous shape read `oids_in_order()` and
    /// `lookup_batch` over the **whole repository** on every call, to build an
    /// offset→oid map it needed only for the closure; with no closure the
    /// selection's own offsets answer "is this base in the request", so that
    /// scan is gone and no reverse index has to exist.
    pub fn emit_set(
        &self,
        oids: &[Oid<'_>],
        ofs_delta_ok: bool,
        thin_haves: Option<&[Oid<'_>]>,
    ) -> Result<Vec<crate::pack_walk::EmitEntry>> {
        use crate::index_layout::ObjType;
        use std::collections::hash_map::Entry;

        // If the gate is free, absorb now; if the worker holds it, the rows
        // come from the index plus a read-only pass over the pending packs
        // (`lookup_batch_never_wait` below). Never a wait.
        let _ = self
            .try_absorb_pending()
            .context("absorbing pending index work before emitting a pack")?;

        // Deduplicate, preserving the caller's order. A repeated oid in the
        // request must not become a repeated entry in the pack.
        //
        // **A map and not a set**, keyed oid → position in `asked` (which is the
        // position in `rows`). The membership question is the one it always was;
        // what the position buys is the base's *archive offset* for a
        // `REF_DELTA`, which names its base by oid and can learn where that base
        // sits no other way. It is a `usize` per requested object on a vector
        // this function already builds — not a second pass and not a second
        // index lookup.
        let mut asked: Vec<&[u8]> = Vec::with_capacity(oids.len());
        let mut seen: HashMap<&[u8], usize> = HashMap::with_capacity(oids.len());
        for oid in oids {
            if let Entry::Vacant(slot) = seen.entry(*oid) {
                slot.insert(asked.len());
                asked.push(*oid);
            }
        }

        let rows = self.lookup_batch_never_wait(&asked)?;

        // **One mapping for the whole emit set.** Only the header probes below
        // read through it — the entries themselves are recorded as extents and
        // resolved by [`Self::resolve_emit_payloads`], which takes its own
        // snapshot of the same [`ArchiveMap`](crate::archive_map::ArchiveMap) and
        // therefore the same `Arc` unless a push landed in between.
        let snap = self.archive_snapshot()?;

        // The two questions "is this base in the request" are asked in the two
        // coordinate systems the two delta forms use, and both are answered off
        // the request itself rather than off the index.
        //
        // **Offset → position in the request**, not a bare set of offsets. The
        // membership question is the same one it always was; what the position
        // buys is the base's *oid*, which the re-delta arm below needs in order
        // to read the base's content. It is the same single pass over `rows`
        // that built the set, so it costs a `usize` per requested object and no
        // extra work — and it is emphatically not the whole-repository
        // offset→oid scan the old delta-base closure used to do.
        let in_set_offsets: HashMap<u64, usize> = rows
            .iter()
            .enumerate()
            .filter_map(|(i, r)| r.as_ref().map(|r| (r.offset, i)))
            .collect();
        let oid_len = self.hash_kind().oid_len();

        // The base of the last boundary entry that was re-deltified, kept so a
        // run of entries hanging off one ancestor inflates it once. One slot and
        // not an LRU: measured on `h2h-linear-sha1-2048c-1024f-16k`, 961
        // boundary entries name 855 distinct stored bases, so there is no reuse
        // worth a cache that could hold a repository's worth of objects — and
        // this crate is under a live RSS budget.
        let mut base_content: Option<(u64, Vec<u8>)> = None;

        // What the client already holds, built **lazily and at most once**. A
        // clone never asks for it (`thin_haves` is `None`), and a fetch every one
        // of whose bases is inside the request never reaches the line that builds
        // it either — only a request that actually cuts a delta chain pays, which
        // is the only request it can help.
        let mut client_bases: Option<ExternalBases> = None;

        let mut out = Vec::with_capacity(asked.len());
        for (oid, row) in asked.iter().zip(rows.iter()) {
            // **An oid this repository does not hold is REFUSED, not dropped.**
            //
            // This used to `continue`, and that is the same silent-under-send
            // shape as the closure defect above: the request asks for N objects,
            // the pack carries N-1, the receipt says success and the client is
            // the first to find out. It also made the two engines disagree about
            // what a missing object *means* — gunnar's in-memory arm has always
            // said *"emit_pack was asked for X, which this store does not hold;
            // a pack emitter that skipped it would send a pack no client can
            // close"* — so a benchmark across the two was comparing two
            // contracts.
            //
            // No legitimate caller relies on the skip. Every set that reaches
            // here is built out of this store's own index: `select` answers from
            // the reachability bitmaps, and gunnar's own walk resolves each id
            // against the store before it selects it. A partial-clone filter is
            // no exception and is the case worth naming, because it is the one
            // that *looks* like it might be: `--filter=blob:none` **removes**
            // oids from the selection, it never adds one the store lacks, so a
            // filtered request is a smaller set of objects that are all present
            // and this refusal never fires on it.
            let Some(row) = row.as_ref() else {
                bail!(
                    "this pack was asked for {}, which this repository does not hold; emitting \
                     the rest would be a short pack reported as a success, so this refuses \
                     instead",
                    hex::encode(oid)
                );
            };

            // Which base this entry names, if any, and whether the request holds
            // it. A `REF_DELTA`'s `delta_base` column is 0 by construction —
            // `DeltaBase::as_offset` reports 0 for a ref base and 0 is also the
            // no-base sentinel — so its base is read out of the entry's own
            // bytes, directly after the type/size varint.
            //
            // A base that is *outside* the request is carried in **both**
            // coordinate systems rather than as a bare `false`, because that is
            // what the thin arm below needs: an `OFS_DELTA` knows only where its
            // base sits, a `REF_DELTA` knows only what it is called, and
            // "does the client hold it" has to be asked in whichever one the
            // entry speaks.
            let base = match row.obj_type {
                ObjType::OfsDelta => match in_set_offsets.get(&row.delta_base) {
                    Some(_) => BaseOf::Inside {
                        at: row.delta_base,
                    },
                    None => BaseOf::Outside {
                        offset: row.delta_base,
                        oid: None,
                    },
                },
                ObjType::RefDelta => {
                    let head = self.extent(&snap, row.offset, row.len.min(64))?;
                    let (_, _, n) = crate::pack_walk::type_and_size_of(&head)?;
                    match head.get(n..n + oid_len) {
                        // In the request — **and where**. `rows[i]` is `None`
                        // only for an oid this store does not hold, which the
                        // refusal above turns into an error the moment the loop
                        // reaches it; until then the base is treated as outside,
                        // which is the answer that cannot be wrong.
                        Some(b) => match seen
                            .get(b)
                            .and_then(|i| rows[*i].as_ref())
                            .map(|r| r.offset)
                        {
                            Some(at) => BaseOf::Inside { at },
                            None => BaseOf::Outside {
                                offset: 0,
                                oid: Some(b.to_vec()),
                            },
                        },
                        // A truncated entry names no base this can read. It is
                        // not "inside", and it is not offered to the client
                        // either — it falls through to the whole rebuild, which
                        // is the answer that cannot be wrong.
                        None => BaseOf::Outside {
                            offset: 0,
                            oid: None,
                        },
                    }
                }
                _ => BaseOf::Whole,
            };

            if let BaseOf::Whole | BaseOf::Inside { .. } = base {
                let inside_at = match base {
                    BaseOf::Inside { at } => Some(at),
                    _ => None,
                };
                // **The whole-clone arm, and it reads not one byte here.** The
                // entry is recorded as its address in the archive; the bytes are
                // resolved against the mapping at emit time and go straight from
                // the page cache to the wire. This line used to be a `pread`
                // into a fresh `Vec` — 13.8 M of each on a `linux.git` clone, all
                // of them held at once, which is the 2314 MB peak RSS
                // [`crate::pack_walk::EntryBytes`] documents.
                let extent = crate::pack_walk::EntryBytes::Extent {
                    offset: row.offset,
                    len: row.len,
                };
                let (stored, obj_type, delta_base) = match (row.obj_type, inside_at) {
                    // An `OFS_DELTA` for a client that cannot read one: re-head it
                    // as a `REF_DELTA` naming the same base by oid. The compressed
                    // payload is the delta stream either way, so this is still a
                    // copy in the `recompressed` sense — nothing is inflated — but
                    // the concatenation of a new header and an old payload exists
                    // nowhere on disk, so it cannot be an extent and is `Owned`.
                    (ObjType::OfsDelta, Some(_)) if !ofs_delta_ok => {
                        let base_oid = self.oid_at_offset(row.delta_base, &asked, &rows)?;
                        let bytes = self.extent(&snap, row.offset, row.len)?;
                        (
                            crate::pack_walk::EntryBytes::Owned(Self::as_ref_delta(
                                &bytes, &base_oid,
                            )?),
                            ObjType::RefDelta,
                            0,
                        )
                    }
                    // 🚨 **A stored `REF_DELTA` whose base is IN THIS PACK is
                    // re-headed as an `OFS_DELTA`, and that is not an
                    // optimisation.**
                    //
                    // gitoxide — which is `gunnar_client`, `gunnar`'s own
                    // `receive-pack`, and every other gix-based receiver — reads
                    // every `OBJ_REF_DELTA` in an incoming pack as naming an
                    // object *the receiver already has*.
                    // `gix_pack::data::input::LookupRefDeltaObjectsIter` consults
                    // the local object database and the bases it has already
                    // spliced in, and **nowhere else**: never inside the pack it
                    // is reading. A base that is in the pack and not in the
                    // receiver's store is `input::Error::NotFound`, and the fetch
                    // dies with `The object <base> could not be decoded or wasn't
                    // found` — with the whole pack rejected, on a clone whose
                    // target is empty by definition, so *every* such entry is
                    // fatal. That is `S-003` / gitoxide#2882, and `gunnar-wire`'s
                    // `Selection::client_has` carries the same rule for gunnar's
                    // own emitter.
                    //
                    // Stock git resolves it happily, which is why this survived
                    // five green `git clone` runs against the store that could
                    // not serve one `gunnar_client` fetch (`gunnar.rewrite`
                    // round 0 and `gunnar.year` week 0, all four znippy columns,
                    // 2026-08-14 — the server logged the same request `served`).
                    //
                    // The entry keeps its compressed delta stream byte for byte;
                    // only the header changes, from "base named by oid" to "base
                    // named by distance", which is the naming every receiver in
                    // existence resolves inside the pack. This is where such an
                    // entry comes from in the first place: `git index-pack
                    // --fix-thin` appends the base into the pack and leaves the
                    // ref-delta naming it by oid, so any repository pushed to
                    // more than once holds them.
                    //
                    // # What it costs, stated rather than glossed
                    //
                    // `Owned`, so this is the one arm that gives up the zero-copy
                    // property for an entry it does **not** rebuild: the
                    // compressed delta stream is memcpy'd once, because a new
                    // header concatenated with an old payload exists nowhere on
                    // disk and no extent can address it. Bounded by the
                    // compressed size of the ref-deltas whose base is in the
                    // request — not by the repository, and not by the pack.
                    //
                    // It could be avoided: `emit_pack` re-encodes every header
                    // from `EmitEntry::obj_type` while `header_len` finds the
                    // payload from the STORED bytes' own type, so an `Extent`
                    // over the untouched ref-delta declared as an `OfsDelta`
                    // would emit the identical pack with no copy at all. That is
                    // deliberately not done: it makes an `EmitEntry` disagree
                    // with the bytes it points at, and the entry model being
                    // trustworthy is worth more than the memcpy. If the RSS
                    // budget ever says otherwise, the honest form is a third
                    // `EntryBytes` variant that carries the new header beside
                    // the extent, not a silent disagreement.
                    (ObjType::RefDelta, Some(at)) if ofs_delta_ok => {
                        let bytes = self.extent(&snap, row.offset, row.len)?;
                        (
                            crate::pack_walk::EntryBytes::Owned(Self::as_ofs_delta(
                                &bytes, oid_len, row.offset, at,
                            )?),
                            ObjType::OfsDelta,
                            at,
                        )
                    }
                    // Everything else copies. A `REF_DELTA` left as one here is
                    // the `!ofs_delta_ok` client, which cannot be handed a
                    // distance at all — and which is stock git older than 1.4.4,
                    // never a gix receiver, since gix has always advertised
                    // `ofs-delta`.
                    _ => (extent, row.obj_type, row.delta_base),
                };
                out.push(crate::pack_walk::EmitEntry {
                    oid: oid.to_vec(),
                    stored,
                    obj_type,
                    uncompressed_size: row.uncompressed_size,
                    delta_base,
                    offset: row.offset,
                    recompressed: false,
                    deltified: false,
                });
                continue;
            }

            // ── the base is outside the request ──────────────────────────────
            //
            // **Thin first.** If the client consented to a thin pack and the
            // negotiation vouches that it already holds this base, the entry
            // goes out as a `REF_DELTA` naming that base by oid, carrying the
            // **same compressed delta stream**. Nothing is inflated, nothing is
            // deflated, and the pack is smaller than the whole object by exactly
            // the margin the delta was worth. That is what `caps.thin` has always
            // been the allowance for.
            //
            // An `OFS_DELTA` cannot survive this: it names its base by a
            // backwards distance *within the pack*, and the base is not in the
            // pack. Re-heading it as a `REF_DELTA` is the same header swap the
            // no-`ofs-delta` client path does, over an unchanged payload.
            if let Some(haves) = thin_haves {
                if client_bases.is_none() {
                    client_bases = Some(self.client_bases(haves)?);
                }
                let ext = client_bases
                    .as_ref()
                    .expect("the client's bases were just built");
                let base_oid: Option<Vec<u8>> = match &base {
                    // Unreachable: the arm above `continue`s on both. Matched
                    // rather than `unreachable!()` so that a future arm falling
                    // through here declines the thin path instead of panicking
                    // inside a serving thread.
                    BaseOf::Whole | BaseOf::Inside { .. } => None,
                    BaseOf::Outside {
                        oid: Some(named), ..
                    } => ext
                        .held
                        .contains(&OidKey::new(named)?)
                        .then(|| named.clone()),
                    BaseOf::Outside {
                        offset,
                        oid: None,
                    } => ext.by_offset.get(offset).map(|k| k.as_slice().to_vec()),
                };
                if let Some(base_oid) = base_oid {
                    // A stored `REF_DELTA` already names its base by oid, so its
                    // bytes go out untouched and stay an extent. An `OFS_DELTA`
                    // has to be re-headed, and the result is new bytes.
                    let stored = if row.obj_type == ObjType::OfsDelta {
                        let bytes = self.extent(&snap, row.offset, row.len)?;
                        crate::pack_walk::EntryBytes::Owned(Self::as_ref_delta(&bytes, &base_oid)?)
                    } else {
                        crate::pack_walk::EntryBytes::Extent {
                            offset: row.offset,
                            len: row.len,
                        }
                    };
                    out.push(crate::pack_walk::EmitEntry {
                        oid: oid.to_vec(),
                        stored,
                        obj_type: ObjType::RefDelta,
                        uncompressed_size: row.uncompressed_size,
                        // The base is NOT in this pack, so nothing may be ordered
                        // after it: `topological_order` reads 0 as "names no base
                        // in here", which for an external base is the truth.
                        delta_base: 0,
                        offset: row.offset,
                        // Copied. The payload never left the archive's bytes.
                        recompressed: false,
                        deltified: false,
                    });
                    continue;
                }
            }

            // The base is not being sent and the client cannot supply it, so the
            // stored bytes cannot go out as they are. Two answers remain, and
            // the first is worth ~4× the second on the wire.
            let (kind, body) = self.content(oid)?.ok_or_else(|| {
                anyhow!(
                    "{} is a delta whose base is outside this request, so it must be sent whole, \
                     and this repository cannot produce its content — neither §14's exploded \
                     table nor a re-derivation from the verbatim packs answered",
                    hex::encode(oid)
                )
            })?;

            // ── re-delta against a base the request DOES carry ────────────────
            //
            // The candidate comes from the entry's own stored delta chain: the
            // nearest ancestor that is inside the request. That is the packer's
            // original similarity judgement, already made and already written
            // down — no window, no sort, no scan of the repository.
            let candidate = if crate::delta::enabled() {
                self.in_request_chain_ancestor(row.delta_base, row.offset, &in_set_offsets)?
            } else {
                None
            };
            if let Some(base_at) = candidate {
                let at = *in_set_offsets
                    .get(&base_at)
                    .expect("the ancestor was found by lookup in this very map");
                // Reuse the last base if this entry hangs off the same one.
                if base_content.as_ref().is_none_or(|(o, _)| *o != base_at) {
                    let base_oid = asked[at];
                    let (_, base_body) = self.content(base_oid)?.ok_or_else(|| {
                        anyhow!(
                            "{} is in this request and is the delta base chosen for {}, and this \
                             repository cannot produce its content",
                            hex::encode(base_oid),
                            hex::encode(oid)
                        )
                    })?;
                    base_content = Some((base_at, base_body));
                }
                let (_, base_body) = base_content.as_ref().expect("just filled");

                // `None` is the encoder declining — an unrelated base, or a
                // delta that came out no smaller than the object. Falling
                // through to the whole rebuild is then strictly right.
                if let Some(d) = crate::delta::delta(base_body, &body)? {
                    let stored = Self::ofs_delta_entry(&d, row.offset, base_at)?;
                    // A client with no `ofs-delta` is served the same computed
                    // delta under a `REF_DELTA` head naming the base by oid —
                    // the identical header swap the base-inside arm above does,
                    // over a payload that is already built.
                    // **The `Owned` exception, in its primary shape.** These
                    // bytes were computed here and exist on no disk, so no
                    // extent addresses them; carrying them on the entry is
                    // correct and is bounded by the boundary a narrowed request
                    // cuts through (961 of 33 773 entries on the fixture below),
                    // never by the repository.
                    let (stored, obj_type, delta_base) = if ofs_delta_ok {
                        (
                            crate::pack_walk::EntryBytes::Owned(stored),
                            ObjType::OfsDelta,
                            base_at,
                        )
                    } else {
                        (
                            crate::pack_walk::EntryBytes::Owned(Self::as_ref_delta(
                                &stored, asked[at],
                            )?),
                            ObjType::RefDelta,
                            0,
                        )
                    };
                    out.push(crate::pack_walk::EmitEntry {
                        oid: oid.to_vec(),
                        stored,
                        obj_type,
                        uncompressed_size: row.uncompressed_size,
                        delta_base,
                        offset: row.offset,
                        // Inflated and re-deflated, so NOT a copy — and the
                        // receipt says which of the two rebuilds ran.
                        recompressed: true,
                        deltified: true,
                    });
                    continue;
                }
            }

            // Ship the object whole rather than dragging an unreachable base —
            // and its children — into a clone.
            out.push(crate::pack_walk::EmitEntry {
                oid: oid.to_vec(),
                // Inflated and re-deflated from §14's resolved content: the
                // `Owned` exception again, and again bounded by the boundary.
                stored: crate::pack_walk::EntryBytes::Owned(Self::whole_entry(kind, &body)?),
                obj_type: crate::serve::resolved_type(kind),
                uncompressed_size: body.len() as u64,
                // Whole: it names no base, and nothing may order it after one.
                delta_base: 0,
                offset: row.offset,
                recompressed: true,
                deltified: false,
            });
        }
        Ok(out)
    }

    /// **PHASE 1 of emitting: resolve every entry's stored bytes, in parallel.**
    ///
    /// Emission splits in two, and the split is not a preference — it is where
    /// the ordering dependency actually is:
    ///
    /// | phase | what it does | why |
    /// |---|---|---|
    /// | 1, **here**, parallel | address → bytes for every entry | the archive is immutable, so N workers over disjoint (or shared) extents need **no lock at all** |
    /// | 2, [`crate::pack_walk::emit_pack`], serial | assign output offsets, encode `OFS_DELTA` distances, write, hash | an `OFS_DELTA` names its base by **distance back in the output pack**, so entry *n* cannot be encoded until every earlier entry's byte length is known |
    ///
    /// Phase 2 is not parallelisable and no attempt is made: the distance chain
    /// is a genuine serial dependency, and a running sha1 is another.
    ///
    /// # No lock, and why that is a fact rather than an intention
    ///
    /// [`Self::adopt_journal`] states the storage property this rests on — *"the
    /// blob file is append-only and `gc` truncates nothing, so a retired pack's
    /// bytes are still exactly where the journal says they are"*. Every byte a
    /// snapshot covers is therefore immutable for the life of the file, so the
    /// workers below share one `&Mapped` and read it concurrently with no
    /// synchronisation of any kind. There is no mutex here; if one were needed
    /// the data model would be wrong.
    ///
    /// # 🚨 This is a fan-out inside the serving tier, and `crate::serve`'s
    /// header says that tier is serial
    ///
    /// It did, and the reason it gave is still true and still respected: the
    /// constellation's fan-out primitive has no reentrancy detection, so an
    /// unbounded fan-out per request inside an admission gate that already runs
    /// 32 transfers spawns W² threads. That is why this is **bounded twice**:
    ///
    ///  * it does not fan out at all below [`FAN_OUT_AT`] entries, so every fetch
    ///    small enough for thread-spawn to dominate runs on the calling thread
    ///    exactly as before, and
    ///  * it never exceeds [`MAX_RESOLVE_WORKERS`] (override with
    ///    `ZNIPPY_GIT_EMIT_WORKERS`), so the worst case is 32 × 4 and not
    ///    32 × ncores.
    ///
    /// # What the fan-out is worth — stated honestly
    ///
    /// Resolving a mapped extent is a bounds check and a pointer, so the work
    /// this parallelises is **not** the resolve itself. It is the two things
    /// beside it: the first-touch **page fault** on each entry's header (the
    /// grammar is parsed here, which is what forces that fault, and it validates
    /// the entry before phase 2 commits a byte to the wire), and the `pread`
    /// fallback for any extent the mapping does not cover. On a warm page cache
    /// with the whole archive mapped, phase 1 is nearly free and the fan-out
    /// buys correspondingly little — the 20 % of cycles this change is aimed at
    /// is recovered by *not copying*, not by threads. I could not measure the
    /// fan-out's own contribution separately: oden was at loadavg 25.9 while
    /// this was written (2026-08-14), and a shared box cannot answer a question
    /// that fine.
    pub(crate) fn resolve_emit_payloads<'a>(
        &self,
        entries: &'a [crate::pack_walk::EmitEntry],
        snap: &'a crate::archive_map::Mapped,
    ) -> Result<Vec<std::borrow::Cow<'a, [u8]>>>
    where
        Self: Sync,
    {
        let workers = if entries.len() < FAN_OUT_AT {
            1
        } else {
            emit_workers()
        };
        self.resolve_with(entries, snap, workers)
    }

    /// [`Self::resolve_emit_payloads`] with the worker count named rather than
    /// decided — `1` runs inline on the calling thread.
    ///
    /// Split out so the fan-out is **testable at a size a test fixture can
    /// reach**. The production threshold is 4096 entries and the corpus these
    /// guards run on holds 2687, so a test that went through the front door
    /// would exercise the serial arm every time and the gatling arm never;
    /// `the_fan_out_resolves_the_identical_bytes_the_serial_pass_does` calls
    /// this with 1 and with 4 over the same set and requires the two to agree
    /// byte for byte.
    pub(crate) fn resolve_with<'a>(
        &self,
        entries: &'a [crate::pack_walk::EmitEntry],
        snap: &'a crate::archive_map::Mapped,
        workers: usize,
    ) -> Result<Vec<std::borrow::Cow<'a, [u8]>>>
    where
        Self: Sync,
    {
        use znippy_zoomies::gatling_forkjoin::gatling_for_each;

        let one = |i: usize| -> Result<std::borrow::Cow<'a, [u8]>> {
            let e = &entries[i];
            let bytes = match &e.stored {
                // The bytes live on the entry — the rebuilt-delta exception.
                // Borrowed, never cloned: `EntryBytes::Owned` is already the
                // only allocation this path makes and copying it would double it.
                crate::pack_walk::EntryBytes::Owned(v) => std::borrow::Cow::Borrowed(v.as_slice()),
                crate::pack_walk::EntryBytes::Extent { offset, len } => {
                    self.extent(snap, *offset, *len)?
                }
            };
            // Parse the entry's own header now. Two things fall out: a malformed
            // entry is refused **before** phase 2 has written any of the pack,
            // and the first cache line of every entry is touched here — on
            // whichever worker got it — rather than one at a time on the serial
            // writer.
            crate::pack_walk::type_and_size_of(&bytes).with_context(|| {
                format!(
                    "resolving the stored bytes of {} for emission",
                    hex::encode(&e.oid)
                )
            })?;
            Ok(bytes)
        };

        if workers <= 1 {
            return (0..entries.len()).map(one).collect();
        }
        gatling_for_each(entries.len(), workers, one)
            .into_iter()
            .collect()
    }

    /// **Both phases, one call** — the only way a caller in this crate turns an
    /// ordered emit set into pack bytes.
    ///
    /// It is three lines, and it is a function rather than three lines because
    /// LAW 5's *fix by construction* applies exactly here: the snapshot has to
    /// outlive the slices taken from it, and a caller that took its own snapshot
    /// per entry, or dropped it between the phases, would be writing a pack out
    /// of a mapping that no longer exists. Routing `emit_oids` and every test
    /// through one writer makes that impossible to get wrong twice.
    pub(crate) fn emit_ordered(
        &self,
        ordered: &[crate::pack_walk::EmitEntry],
        out: &mut dyn std::io::Write,
    ) -> Result<crate::pack_walk::EmitReport>
    where
        Self: Sync,
    {
        let snap = self
            .archive_snapshot()
            .context("mapping the archive to emit")?;
        let payloads = self
            .resolve_emit_payloads(ordered, &snap)
            .context("resolving the emit set's stored bytes")?;
        crate::pack_walk::emit_pack(
            ordered,
            self.hash_kind(),
            out,
            &|i| Ok(payloads[i].as_ref()),
        )
    }

    /// **The nearest ancestor of `from`'s stored delta chain that is inside the
    /// request**, or `None` when the chain leaves the request and never comes
    /// back.
    ///
    /// `from` is the archive offset of a base already known to be *outside* the
    /// request; `entry_at` is the offset of the entry that named it.
    ///
    /// # Why this cannot make a cycle, and why that is not a comment but an
    /// invariant
    ///
    /// The answer is required to satisfy `answer < entry_at`. In a well-formed
    /// pack a base always precedes the delta that names it, so every edge in the
    /// stored graph already points from a higher offset to a lower one; a new
    /// edge with the same property keeps the emitted graph a DAG **by
    /// construction**, whatever else the request contains. That matters because
    /// the obvious better candidate — the entry's own delta *children*, one
    /// revision away instead of two to nine — is exactly the set that would
    /// close a cycle: a child's stored base is this entry, so pointing this
    /// entry at the child makes `topological_order` unable to order either, and
    /// `emit_pack` refuses the set. Measured cost of the restriction on
    /// `h2h-linear-sha1-2048c-1024f-16k`: ~1 470 bytes per boundary entry
    /// against ~314 for the cyclic candidate, and 5 800 for shipping it whole.
    ///
    /// An `OFS_DELTA` decreases the offset every hop, so the bound is free
    /// there; a `REF_DELTA` names its base by oid and could point anywhere, so
    /// the comparison is made rather than assumed.
    ///
    /// # Cost
    ///
    /// One 64-byte `pread` per hop, no inflate, no allocation sized by an
    /// object — the same walk and the same ceiling as
    /// [`crate::serve::GitStore::resolved_type_at`], for the same reason: a
    /// pushed pack's back-references are not under this server's control, so a
    /// cycle must terminate rather than spin. Measured hop counts on the fixture
    /// above: 2 for 392 of the 859 that resolve, 3 for 260, and 9 at the worst.
    fn in_request_chain_ancestor(
        &self,
        from: u64,
        entry_at: u64,
        in_request: &HashMap<u64, usize>,
    ) -> Result<Option<u64>> {
        use crate::index_layout::{ObjType, ObjectIndex as _};

        /// git's own `pack.depth` ceiling, doubled — the same bound
        /// `resolved_type_at` carries and for the same reason.
        const MAX_LINKS: usize = 100;
        /// Enough of an entry to read its type/size varint plus either an
        /// `OFS_DELTA` distance or a `REF_DELTA` oid.
        const HEADER_PROBE: u64 = 64;

        let oid_len = self.hash_kind().oid_len();
        let mut at = from;
        for _ in 0..MAX_LINKS {
            if at != 0 && at < entry_at && in_request.contains_key(&at) {
                return Ok(Some(at));
            }
            if at == 0 {
                return Ok(None);
            }
            let head = self.read_extent(at, HEADER_PROBE)?;
            let (t, _, n) = crate::pack_walk::type_and_size_of(&head)?;
            at = match t {
                // A whole object with no base: the chain ends here, and it was
                // not in the request.
                ObjType::Commit | ObjType::Tree | ObjType::Blob | ObjType::Tag => {
                    return Ok(None)
                }
                ObjType::OfsDelta => {
                    let (distance, _) = crate::pack_walk::ofs_distance_of(&head[n..])?;
                    match at.checked_sub(distance) {
                        Some(next) if next != 0 => next,
                        // A base before the start of the archive is a corrupt
                        // back-reference. The whole rebuild is always a correct
                        // answer, so this declines rather than failing a clone
                        // over an entry it was only ever going to optimise.
                        _ => return Ok(None),
                    }
                }
                ObjType::RefDelta => {
                    let Some(base_oid) = head.get(n..n + oid_len) else {
                        return Ok(None);
                    };
                    match self.index().lookup(base_oid) {
                        Some(row) => row.offset,
                        None => return Ok(None),
                    }
                }
            };
        }
        Ok(None)
    }

    /// An `OFS_DELTA` pack entry carrying `d`, deflated.
    ///
    /// The distance written here is the **archive** distance, which is the same
    /// coordinate every stored entry's distance is in;
    /// [`crate::pack_walk::emit_pack`] rewrites it into output coordinates for
    /// every entry it emits, copied or not, so this only has to be well-formed
    /// and self-consistent — [`crate::pack_walk::header_len`] parses it back to
    /// find where the payload starts.
    ///
    /// `Compression::fast` for the same reason [`Self::whole_entry`] uses it,
    /// and the trade is far better here: the buffer being deflated is the delta,
    /// which on the measured fixture is ~1.4 KB against the object's 16 KiB, so
    /// this path deflates roughly a **tenth** of the bytes the whole rebuild it
    /// replaces does.
    fn ofs_delta_entry(d: &[u8], entry_at: u64, base_at: u64) -> Result<Vec<u8>> {
        use crate::index_layout::ObjType;
        use std::io::Write as _;

        let distance = entry_at.checked_sub(base_at).ok_or_else(|| {
            anyhow!(
                "a computed delta at archive offset {entry_at} names a base at {base_at}, which \
                 is after it — an ofs-delta distance is backwards and this would not encode"
            )
        })?;
        let mut out = Vec::with_capacity(d.len() / 2 + 32);
        crate::pack_walk::encode_type_and_size(&mut out, ObjType::OfsDelta, d.len() as u64);
        crate::pack_walk::encode_ofs_distance(&mut out, distance);
        let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::fast());
        z.write_all(d)?;
        Ok(z.finish()?)
    }

    /// **The objects the receiver already held before this transfer**, in both
    /// coordinate systems a delta can name a base in.
    ///
    /// `haves` is the negotiated common **tips**, exactly as
    /// [`git_storage_trait::GitServe::emit_pack`] defines them, and the closure
    /// over them is this store's own — the contract deliberately passes tips
    /// rather than the walk's exclusion set, because the closure is
    /// repository-sized and the engine can rebuild it from its own bitmaps.
    ///
    /// # This is a VOUCHER, and the caller has to be able to stand behind it
    ///
    /// Every object named here may be pointed at by a delta the pack does not
    /// carry. If the receiver turns out **not** to hold one, its
    /// `index-pack --fix-thin` dies with `pack has N unresolved deltas`, so a
    /// caller that cannot vouch must not pass `caps.thin`. The case that matters
    /// is a **partial clone**: a `blob:none` client's `have` tips reach blobs it
    /// was deliberately never sent, so the closure over-states what it holds and
    /// a filtered fetch must not be marked thin.
    ///
    /// # Cost
    ///
    /// One bitmap union plus one point lookup per held object, and it happens at
    /// most once per request — and only on a request that has a base outside
    /// itself to place. The `by_offset` map exists because an `OFS_DELTA` knows
    /// its base only as an archive offset; building it over what the *client*
    /// holds rather than over the repository is what keeps this off the
    /// whole-repository scan the closure used to do.
    ///
    /// **And it is spent in raw bytes now, end to end.** This used to ask
    /// [`GitOps::reachable`] — hex out of the ordinal space, `hex::decode`d
    /// straight back to bytes, then a third `to_vec` per object to key the
    /// offset map, three heap allocations per held object for a set the size of
    /// the client's history. It asks [`GitStore::reachable_raw`] instead: one
    /// buffer for the closure, one hash table of [`OidKey`]s over it, and
    /// nothing per object.
    fn client_bases(&self, haves: &[Oid<'_>]) -> Result<ExternalBases> {
        use crate::index_layout::ObjectIndex as _;

        let held = self.reachable_raw(haves, &[]).context(
            "closing over the negotiated common tips, to learn which bases the client can supply \
             for itself",
        )?;
        let refs: Vec<&[u8]> = held.iter().collect();
        let rows = self.index().lookup_batch(&refs);
        let mut by_offset = HashMap::with_capacity(refs.len());
        let mut keys = std::collections::HashSet::with_capacity(refs.len());
        for (oid, row) in refs.iter().zip(rows.iter()) {
            let key = OidKey::new(oid)?;
            if let Some(row) = row {
                by_offset.insert(row.offset, key);
            }
            keys.insert(key);
        }
        Ok(ExternalBases {
            by_offset,
            held: keys,
        })
    }

    /// The oid of the entry at `offset`, looked up **in the request** — which is
    /// the only place it can be, because this is called for a base the request
    /// was just shown to contain.
    ///
    /// Linear over the request rather than a map, because it runs only on the
    /// `ofs-delta`-less client path: a capability no git since 1.4.4 omits, and
    /// one that has to be *advertised absent* to reach here at all.
    fn oid_at_offset(
        &self,
        offset: u64,
        asked: &[&[u8]],
        rows: &[Option<crate::index_layout::IndexRow>],
    ) -> Result<Vec<u8>> {
        asked
            .iter()
            .zip(rows)
            .find(|(_, r)| r.as_ref().is_some_and(|r| r.offset == offset))
            .map(|(oid, _)| oid.to_vec())
            .ok_or_else(|| {
                anyhow!(
                    "the entry at archive offset {offset} was checked to be in this request and \
                     then could not be found in it"
                )
            })
    }

    /// Re-head a stored `OFS_DELTA` as a `REF_DELTA` naming `base_oid`.
    ///
    /// The compressed delta stream is copied unchanged; only the header differs,
    /// because the two forms differ in **how the base is named** and in nothing
    /// else. This is why a client without `ofs-delta` costs bytes and not CPU.
    fn as_ref_delta(stored: &[u8], base_oid: &[u8]) -> Result<Vec<u8>> {
        use crate::index_layout::ObjType;
        let (t, stated_size, n) = crate::pack_walk::type_and_size_of(stored)?;
        if t != ObjType::OfsDelta {
            bail!("only an ofs-delta can be re-headed as a ref-delta, this entry is {t:?}");
        }
        let (_, d) = crate::pack_walk::ofs_distance_of(stored.get(n..).unwrap_or(&[]))?;
        let mut out = Vec::with_capacity(stored.len() + base_oid.len());
        crate::pack_walk::encode_type_and_size(&mut out, ObjType::RefDelta, stated_size);
        out.extend_from_slice(base_oid);
        out.extend_from_slice(stored.get(n + d..).unwrap_or(&[]));
        Ok(out)
    }

    /// Re-head a stored `REF_DELTA` as an `OFS_DELTA` naming the base that sits
    /// at `base_at` — **the inverse of [`Self::as_ref_delta`]**, and the fix for
    /// the one pack shape gitoxide cannot read.
    ///
    /// The compressed delta stream is copied unchanged; only the header differs,
    /// because the two forms differ in how the base is *named* and in nothing
    /// else. The reason this has to exist is in the caller: a `REF_DELTA` whose
    /// base is inside the same pack is resolved by stock git and refused by
    /// every gix-based receiver.
    ///
    /// # The distance written here is a placeholder, and that is by design
    ///
    /// Exactly as [`Self::ofs_delta_entry`] documents: the distance an
    /// `OFS_DELTA` carries is relative to a position in the pack it is *in*, so
    /// [`crate::pack_walk::emit_pack`] re-encodes it for every entry from the
    /// output offsets it is assigning, and [`crate::pack_walk::header_len`]
    /// parses whatever is written here only to find where the payload starts. It
    /// therefore has to be well-formed and self-consistent, and nothing more.
    ///
    /// It cannot simply be `entry_at - base_at`: a `REF_DELTA` is allowed to
    /// name a base that comes **after** it in the pack, and `git index-pack
    /// --fix-thin` produces exactly that — it appends the base at the end. So a
    /// forward reference encodes as `1`, and `emit_pack` writes the real
    /// backwards distance once `topological_order` has put the base first.
    fn as_ofs_delta(
        stored: &[u8],
        oid_len: usize,
        entry_at: u64,
        base_at: u64,
    ) -> Result<Vec<u8>> {
        use crate::index_layout::ObjType;
        let (t, stated_size, n) = crate::pack_walk::type_and_size_of(stored)?;
        if t != ObjType::RefDelta {
            bail!("only a ref-delta can be re-headed as an ofs-delta, this entry is {t:?}");
        }
        let payload = stored.get(n + oid_len..).ok_or_else(|| {
            anyhow!(
                "a ref-delta entry at archive offset {entry_at} is {} bytes, which is not even its \
                 header plus a {oid_len}-byte base oid",
                stored.len()
            )
        })?;
        let mut out = Vec::with_capacity(payload.len() + 32);
        crate::pack_walk::encode_type_and_size(&mut out, ObjType::OfsDelta, stated_size);
        crate::pack_walk::encode_ofs_distance(
            &mut out,
            entry_at.checked_sub(base_at).filter(|d| *d > 0).unwrap_or(1),
        );
        out.extend_from_slice(payload);
        Ok(out)
    }

    /// A whole (non-delta) pack entry for `body`: type/size header, then the
    /// body deflated.
    ///
    /// The **only** place in this crate that deflates on a serving path, and the
    /// only reason it exists is a delta whose base the request does not contain.
    /// `Compression::fast` deliberately: these bytes are re-compressed because
    /// they *cannot* be copied, so the trade is wire size against a clone's
    /// latency, and the entries this runs on are a small boundary fraction of any
    /// real request.
    fn whole_entry(kind: crate::object::GitObjectKind, body: &[u8]) -> Result<Vec<u8>> {
        use std::io::Write as _;
        let mut out = Vec::with_capacity(body.len() / 2 + 32);
        crate::pack_walk::encode_type_and_size(
            &mut out,
            crate::serve::resolved_type(kind),
            body.len() as u64,
        );
        let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::fast());
        z.write_all(body)?;
        Ok(z.finish()?)
    }

    /// Take the absorb gate and hold it.
    ///
    /// The only way to observe "a read that arrived before the drain" as a
    /// **state** rather than as a race: with this held, the worker is parked at
    /// the top of its absorb, so the pack is provably durable, provably queued
    /// and provably not indexed. Its guard is in this module's tests, and nothing
    /// on a serving path takes it.
    #[cfg(test)]
    pub(crate) fn hold_absorb_gate(&self) -> std::sync::MutexGuard<'_, ()> {
        self.absorber.gate.lock().expect("absorb gate poisoned")
    }

    /// `pread` an extent out of the verbatim archive, into a fresh `Vec`.
    ///
    /// **The fallback and the owning path.** A caller that can hold a borrow
    /// wants [`Self::archive_snapshot`] plus [`Self::extent`] instead: this one
    /// costs a syscall, an allocation and a kernel→user copy, which is the shape
    /// [`crate::archive_map`] exists to get off the emit path.
    pub(crate) fn read_extent(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
        self.absorber.read_extent(offset, len)
    }

    /// One mapping of the verbatim archive, to be taken **once per operation**
    /// and sliced N times. See [`crate::archive_map::ArchiveMap::snapshot`].
    pub(crate) fn archive_snapshot(&self) -> Result<Arc<crate::archive_map::Mapped>> {
        self.absorber.map.snapshot()
    }

    /// **The one resolver**: an extent's bytes, borrowed from `snap` when it
    /// covers them and `pread` into a fresh buffer when it does not.
    ///
    /// `Cow::Borrowed` is the ordinary answer and the whole point — no syscall,
    /// no allocation, no copy, just a bounds-checked slice of the page cache.
    /// `Cow::Owned` happens for an extent past the mapped end, which means the
    /// blob file grew after the snapshot was taken (a push landed mid-clone).
    /// `Mapped::get` returning `None` is *"go and pread it"* and never *"there
    /// are no bytes"*, so the two arms return the **same bytes** and differ only
    /// in what they cost — which is the property
    /// `an_extent_past_the_mapping_falls_back_and_returns_the_same_bytes`
    /// asserts.
    pub(crate) fn extent<'m>(
        &self,
        snap: &'m crate::archive_map::Mapped,
        offset: u64,
        len: u64,
    ) -> Result<std::borrow::Cow<'m, [u8]>> {
        match snap.get(offset, len) {
            Some(b) => Ok(std::borrow::Cow::Borrowed(b)),
            None => Ok(std::borrow::Cow::Owned(self.read_extent(offset, len)?)),
        }
    }

    /// Record a durable pack as pending index work.
    ///
    /// The **bit going clear**, and the ack path's last act before it returns.
    pub(crate) fn queue(&self, pack_id: u64, extent: Extent) -> Result<()> {
        self.absorber.queue(pack_id, extent)
    }

    fn reach_bitmaps(&self) -> Result<Arc<Vec<ReachEntry>>> {
        self.absorber.reach_bitmaps()
    }

    /// [`Absorber::reach_bitmaps_with`], for the differential guard.
    pub(crate) fn reach_bitmaps_with(
        &self,
        policy: crate::reach::ReachPolicy,
        cache: bool,
    ) -> Result<Arc<Vec<ReachEntry>>> {
        self.absorber.reach_bitmaps_with(policy, cache)
    }

    /// [`Absorber::reach_tables_with`] — the reach table paired with its oid
    /// index, for the negotiation.
    pub(crate) fn reach_tables_with(
        &self,
        policy: crate::reach::ReachPolicy,
        cache: bool,
    ) -> Result<(Arc<Vec<ReachEntry>>, Arc<HashMap<String, u32>>)> {
        self.absorber.reach_tables_with(policy, cache)
    }

    /// The commit oid set, raw, shared. See [`Derived::commit_raw`].
    pub(crate) fn commit_oids_raw(
        &self,
    ) -> Result<Option<Arc<std::collections::HashSet<Vec<u8>>>>> {
        self.absorber.commit_oids_raw()
    }

    pub(crate) fn refold(&self) -> Result<()> {
        self.absorber.refold()
    }
}

impl<S: ObjectIndex> Absorber<S> {
    /// `shared` is the writer's descriptor on the same file
    /// ([`crate::archive_write::ArchiveWrite::blobs_shared`]); `None` opens one,
    /// which is what a caller with no writer does.
    fn open(
        blobs: &Path,
        shared: Option<Arc<File>>,
        hash: GitHashKind,
        objects: ObjectReadStack<S>,
        exploded: Arc<ExplodedCache>,
    ) -> Result<Self> {
        let reader = match shared {
            Some(f) => f,
            None => Arc::new(
                File::open(blobs)
                    .with_context(|| format!("opening {} for reads", blobs.display()))?,
            ),
        };
        let label = blobs
            .parent()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| blobs.display().to_string());
        let graph_cache = crate::arms::graph_cache_from_env()?;
        if !graph_cache {
            // A memo left by an earlier open with the cache on: this store keeps none.
            let stale = blobs.with_file_name(GRAPH_CACHE_FILE);
            match std::fs::remove_file(&stale) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => tracing::warn!(
                    target: "znippy.git",
                    path = %stale.display(),
                    error = %e,
                    "the graph cache is off but a stale objects.graph could not be removed"
                ),
            }
        }
        Ok(Self {
            blobs: blobs.to_path_buf(),
            reader,
            map: crate::archive_map::ArchiveMap::new(blobs),
            hash,
            objects,
            exploded,
            derived: RwLock::new(Derived::default()),
            graph_read: std::sync::atomic::AtomicU64::new(0),
            graph_recomputed: std::sync::atomic::AtomicU64::new(0),
            graph_cache: std::sync::atomic::AtomicBool::new(graph_cache),
            reach_carried: std::sync::atomic::AtomicU64::new(0),
            reach_rebuilt: std::sync::atomic::AtomicU64::new(0),
            ordinal_folded: std::sync::atomic::AtomicU64::new(0),
            ordinal_tail: std::sync::atomic::AtomicU64::new(0),
            packs: Mutex::new(PackState::default()),
            gate: Mutex::new(()),
            progress: crate::progress::IndexProgress::new(&label),
            cancel: std::sync::atomic::AtomicBool::new(false),
            label,
            watchdog: RwLock::new(crate::memguard::global()),
            scanned: Mutex::new(HashMap::new()),
            scan_build: Mutex::new(()),
            unindexable: Mutex::new(HashMap::new()),
        })
    }

    /// **Tree payloads, on demand** — [`crate::reach::TreeSource`] over this
    /// store.
    ///
    /// One lookup per tree the walk actually visits, instead of a resident map
    /// of every tree in the repository. Where the bytes come from is
    /// [`Absorber::resolved`]'s business and nobody else's: the exploded cache
    /// if the tree is in it, its own delta chain out of the mmapped pack if it
    /// is not — and the read then writes it back, so a second walk finds it
    /// warm.
    ///
    /// It must not take the `derived` lock, and it does not: `resolved` reads
    /// the exploded pools, the `objects` index and the pending packs, none of
    /// which is `derived`. Both callers build one of these **inside** their
    /// `derived.write()` section, and that is only sound because of this
    /// sentence.
    fn tree_source(&self) -> TreesFromStore<'_, S> {
        TreesFromStore { abs: self }
    }

    /// Packs whose objects are not in the index yet — §13.12's bit, counted.
    fn unindexed_packs(&self) -> usize {
        self.packs.lock().expect("pack state lock").unabsorbed
    }

    /// **Index everything durable, here, now — the ack path's half of §13.9.**
    ///
    /// # The two hours, in one function
    ///
    /// MEASURED by lane P2 on the oden rig 2026-08-30. `git.receive_pack.checking`
    /// fired at 07:43:49; its very first `peel` of a pushed tip missed the
    /// exploded table and missed the `objects` index (the worker was minutes
    /// into a 13 948 244-object pack), and fell into [`Self::scan_pending`],
    /// which ran **a second, read-only, throw-away resolve of the whole 8.12 GiB
    /// pack on the connection thread**:
    ///
    /// ```text
    /// 09:20:21  index.scanned  "a reader scanned a pending pack for itself:
    ///                           13948244 objects in 5792442 ms"
    /// ```
    ///
    /// 1h36m32s on the 16 GB box and 1h44m14s on the 8 GB one, for rows it then
    /// threw away with the comment *"keeping them would be the index, and the
    /// worker is building that"*. That sentence is the defect: two resolvers
    /// over the same bytes, each holding its own O(pack) `PackWalk::entries` and
    /// oid table, on four vCPUs — which is also **why the watchdog paused**. The
    /// reader's second copy is what ate the `MemAvailable` the indexer tripped
    /// over, and neither pass ever finished the check.
    ///
    /// # Who may call this
    ///
    /// **The ack path, and nothing else.** It takes [`Absorber::gate`], so it
    /// waits for whoever is absorbing — and *"nobody waits on the indexer"* is a
    /// law with its own red test
    /// (`a_read_before_the_drain_is_served_from_the_pack_and_never_waits`): a
    /// clone, an `ls-remote`, a `control status` must be answered while the
    /// drain is parked, and they still are, through [`Self::scan_pending`].
    ///
    /// The connectivity check is the one caller for which that is the wrong
    /// trade. It has to prove that every object reachable from 2874 new tips is
    /// present, which means reading them; an entry's oid exists only once its
    /// delta chain has been applied; so the pack must be resolved before the
    /// check can answer, and the only question is whether it is resolved **once
    /// or twice**. This makes it once. `git receive-pack` makes the same choice
    /// and calls it `index-pack`.
    ///
    /// If the account worker already holds the gate, this blocks on it and then
    /// finds `is_absorbed` set and returns: whoever got there first did the work.
    ///
    /// Returns how many packs this call absorbed; `0` means it could not (it is
    /// nested inside an absorb of the only pending pack, or there was nothing
    /// to do).
    fn index_pending_now(&self) -> Result<usize> {
        if self.unindexed_packs() == 0 {
            return Ok(0);
        }
        // **Nested**: this thread is already inside `absorb_gated` and holds the
        // gate, so taking it again is a deadlock, not a wait. The other pending
        // packs are still ours to absorb inline — that is lane U's case, a thin
        // push whose base sits in a pack pushed a moment earlier — and the one
        // we are in the middle of is not.
        if let Some(current) = IN_ABSORB.with(|c| c.get()) {
            let jobs: Vec<PendingPack> = {
                let s = self.packs.lock().map_err(|_| anyhow!("pack state poisoned"))?;
                s.pending()
            };
            return self.absorb_each(&jobs, Some(current));
        }
        let _gate = self.gate.lock().map_err(|_| anyhow!("absorb gate poisoned"))?;
        let jobs: Vec<PendingPack> = {
            let s = self.packs.lock().map_err(|_| anyhow!("pack state poisoned"))?;
            s.pending()
        };
        // `absorb_gated` is a no-op for a pack somebody absorbed while we were
        // queued on the gate, so the loser of the race pays nothing.
        self.absorb_each(&jobs, None)
    }

    /// **Absorb the pending packs only if nobody else is absorbing.**
    ///
    /// `Some(n)` = the gate was free and this caller did the work; `None` = the
    /// worker (or another reader) holds the gate — possibly paused by the
    /// memory watchdog for as long as the box is short — and this caller did
    /// **not** wait for it. Rickard's rule, 2026-08-30: *nobody waits on the
    /// indexer.* A read that needs the index now answers from the pack for
    /// itself ([`Self::scan_pending`]) and a read that needs the whole graph
    /// says so by name rather than blocking behind a kernel pack.
    fn try_absorb_pending(&self) -> Result<Option<usize>> {
        if self.unindexed_packs() == 0 {
            return Ok(Some(0));
        }
        let _gate = match self.gate.try_lock() {
            Ok(g) => g,
            Err(std::sync::TryLockError::WouldBlock) => return Ok(None),
            Err(std::sync::TryLockError::Poisoned(_)) => bail!("absorb gate poisoned"),
        };
        let jobs: Vec<PendingPack> = {
            let s = self
                .packs
                .lock()
                .map_err(|_| anyhow!("pack state poisoned"))?;
            s.pending()
        };
        self.absorb_each(&jobs, None).map(Some)
    }

    /// **A read served from the pack on the reader's own request, never by
    /// waiting for the worker.**
    ///
    /// Every oid in `wants` is looked up in the `objects` table first — the
    /// rows the worker has already landed, batch by batch, are visible there
    /// with no lock in common with it. The ones still missing, if any pack is
    /// still un-indexed, are found by **resolving the pending packs read-only
    /// on this thread**: the same resolver the worker runs
    /// ([`crate::resolve::resolve_streaming`]), over the same mmapped bytes,
    /// with a bounded base set, but with **no sink, no gate and no rows
    /// written** — it produces rows for the caller and nothing else. The pass
    /// stops the moment every wanted oid has been seen.
    ///
    /// `capture` names one oid whose **content** the caller wants as well (a
    /// [`GitStore::content`] read); it rides through a
    /// [`crate::exploded::CaptureOne`] sink and comes back in the second slot.
    ///
    /// # Cost, stated
    ///
    /// An oid that is in a pending pack costs one read-only pass up to where it
    /// sits; an oid that is **absent** costs a full pass over every pending
    /// pack — for a kernel pack, minutes of one core. That is the price of
    /// never answering "absent" for an object whose bytes are durable, paid by
    /// the reader that asked and by nobody else. The rows it computes are not
    /// kept: keeping them would be the index, and the worker is building that.
    fn scan_pending(
        &self,
        wants: &[&[u8]],
        capture: Option<&[u8]>,
    ) -> Result<(Vec<Option<crate::index_layout::IndexRow>>, Option<(GitObjectKind, Vec<u8>)>)> {
        use crate::index_layout::IndexRow;
        let mut out: Vec<Option<IndexRow>> = vec![None; wants.len()];
        let mut missing: HashMap<&[u8], Vec<usize>> = HashMap::with_capacity(wants.len());
        for (i, w) in wants.iter().enumerate() {
            missing.entry(*w).or_default().push(i);
        }
        if missing.is_empty() && capture.is_none() {
            return Ok((out, None));
        }
        // **No nested BUILD.** The resolver asks this absorber (as its
        // `BaseSource`) for a thin pack's external base, and that base may
        // itself be un-indexed — a second *scan build* started from inside the
        // first, and a third from inside that, without end.
        //
        // The guard used to answer `None` outright when re-entered, and that
        // was wider than the recursion it was written for: a base sitting in
        // **another pack that is already scanned** is one binary search away,
        // and refusing it made a thin push on top of a just-acked one fail
        // `[remote rejected] … missing necessary objects` — lane U's rig
        // finding, 2026-08-30. So a nested call now consults the scans that
        // exist and builds none: a lookup terminates, a build is what does not.
        thread_local! { static SCANNING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
        let nested = SCANNING.with(|s| s.get());
        struct Unset(bool);
        impl Drop for Unset {
            fn drop(&mut self) {
                if !self.0 {
                    SCANNING.with(|s| s.set(false));
                }
            }
        }
        SCANNING.with(|s| s.set(true));
        let _unset = Unset(nested);
        let pending: Vec<PendingPack> = {
            let s = self
                .packs
                .lock()
                .map_err(|_| anyhow!("pack state poisoned"))?;
            s.pending()
        };
        if pending.is_empty() {
            return Ok((out, None));
        }
        let snap = self.map.snapshot()?;
        let mut content: Option<(GitObjectKind, Vec<u8>)> = None;
        for job in &pending {
            if missing.is_empty() && (capture.is_none() || content.is_some()) {
                break;
            }
            let scanned = match self.cached_scan(job.offset) {
                Some(s) => s,
                // Inside another scan: no build, so the recursion the guard
                // exists for cannot happen, and a pack nobody has scanned yet
                // is simply not consulted for this base.
                None if nested => continue,
                None => self.scanned_pack(&snap, job)?,
            };
            missing.retain(|oid, slots| match scanned.row(oid) {
                Some(r) => {
                    for &i in slots.iter() {
                        out[i] = Some(r.clone());
                    }
                    false
                }
                None => true,
            });
            if let Some(want) = capture
                && content.is_none()
                && let Some((entry, _)) = scanned.find(want)
            {
                let bytes: std::borrow::Cow<'_, [u8]> = match snap.get(job.offset, job.len) {
                    Some(b) => std::borrow::Cow::Borrowed(b),
                    None => std::borrow::Cow::Owned(self.read_extent(job.offset, job.len)?),
                };
                let sp = scanned.clone();
                let offset_of = move |oid: &[u8]| sp.find(oid).map(|(e, _)| sp.walk.entries[e].offset);
                content = Some(crate::resolve::materialize_entry(
                    &bytes,
                    &scanned.walk,
                    entry,
                    self.hash.oid_len(),
                    &offset_of,
                    self,
                )?);
            }
        }
        Ok((out, content))
    }

    /// The scan of one pending pack **if it is already built** — a lookup, and
    /// nothing that could recurse. What a nested `scan_pending` is allowed.
    fn cached_scan(&self, offset: u64) -> Option<Arc<ScannedPack>> {
        self.scanned
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&offset)
            .cloned()
    }

    /// The scan of one pending pack: cached, or built now by one read-only
    /// pass (the same resolver, bounded bases, no sink, no rows written).
    fn scanned_pack(&self, snap: &crate::archive_map::Mapped, job: &PendingPack) -> Result<Arc<ScannedPack>> {
        if let Some(s) = self.scanned.lock().unwrap_or_else(|e| e.into_inner()).get(&job.offset) {
            return Ok(s.clone());
        }
        let _one_at_a_time = self.scan_build.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(s) = self.scanned.lock().unwrap_or_else(|e| e.into_inner()).get(&job.offset) {
            return Ok(s.clone());
        }
        let t0 = std::time::Instant::now();
        let bytes: std::borrow::Cow<'_, [u8]> = match snap.get(job.offset, job.len) {
            Some(b) => std::borrow::Cow::Borrowed(b),
            None => std::borrow::Cow::Owned(self.read_extent(job.offset, job.len)?),
        };
        let walk = crate::pack_walk::walk(&bytes, self.hash.oid_len())?;
        let mut rows: Vec<(Vec<u8>, u32, u64)> = Vec::with_capacity(walk.entries.len());
        // A reader's own budget: a quarter of the worker's, no watchdog —
        // the pause is the worker's and only the worker's.
        let limits = crate::resolve::ResolveLimits {
            base_budget: (crate::resolve::base_budget_from_env() / 4).max(1),
            cancel: Some(&self.cancel),
            label: &self.label,
            ..crate::resolve::ResolveLimits::none()
        };
        // Entry index = position in offset order; the rows come out in
        // resolution order, so map offset → index by binary search.
        let report = crate::resolve::resolve_streaming(
            &bytes,
            &walk,
            self.hash,
            job.offset,
            self,
            &crate::exploded::NoSink,
            limits,
            &mut |batch| {
                for r in batch.drain(..) {
                    let pack_off = r.offset - job.offset;
                    let idx = walk
                        .entries
                        .binary_search_by_key(&pack_off, |e| e.offset)
                        .map_err(|_| anyhow!("resolved row at {pack_off} has no walk entry"))?;
                    rows.push((r.oid, idx as u32, r.uncompressed_size));
                }
                Ok(())
            },
        )
        .context("resolving a pending pack read-only for lookups")?;
        rows.sort_unstable_by(|a, b| a.0.cmp(&b.0));
        let scanned = Arc::new(ScannedPack {
            walk,
            rows,
            archive_offset: job.offset,
        });
        tracing::info!(
            target: "gunnar::index",
            event = "index.scanned",
            repo = %self.label,
            pack_id = job.pack_id,
            objects = scanned.rows.len(),
            reinflations = report.reinflations,
            elapsed_ms = t0.elapsed().as_millis() as u64,
            "a reader scanned a pending pack for itself: {} objects in {} ms",
            scanned.rows.len(),
            t0.elapsed().as_millis()
        );
        self.scanned
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(job.offset, scanned.clone());
        Ok(scanned)
    }

    /// **Drop everything this store holds that can be rebuilt** — what the
    /// watchdog's flush reaches: the readers' scanned packs (`scanned`, ~1.2
    /// GB on linux, rebuilt by the next lookup's pass) and the exploded
    /// table's oid tree and batch cache. The rows on disk are untouched.
    ///
    /// **Returns the rows it actually dropped**, and that number is the point.
    /// Lane P2's rig logged this event 190 and 627 times with
    /// `scanned_rows_dropped=0` on every single one and kept waiting anyway,
    /// because the caller could not tell a spill that freed a gigabyte from one
    /// that freed nothing. Three zeros in a row now end the pause
    /// ([`crate::memguard::PauseEnd::NothingToGive`]).
    ///
    /// The exploded table's own caches are an mmap index and a small batch
    /// cache; they are dropped here too and deliberately not counted, because
    /// they are not where a kernel-sized pack's memory is.
    fn spill(&self) -> u64 {
        let dropped = {
            let mut s = self.scanned.lock().unwrap_or_else(|e| e.into_inner());
            let n: usize = s.values().map(|p| p.rows.len()).sum();
            s.clear();
            n
        };
        self.exploded.drop_caches();
        tracing::info!(
            target: "gunnar::index",
            event = "index.spilled",
            repo = %self.label,
            scanned_rows_dropped = dropped,
            "the store dropped its rebuildable caches for the memory watchdog"
        );
        dropped as u64
    }

    /// This store's watchdog (see the field).
    fn watchdog(&self) -> Arc<crate::memguard::MemWatchdog> {
        self.watchdog.read().unwrap_or_else(|e| e.into_inner()).clone()
    }

    /// One oid, never waiting: the index, then the pending packs.
    fn lookup_never_wait(&self, oid: &[u8]) -> Result<Option<crate::index_layout::IndexRow>> {
        if let Some(r) = self.objects.lookup(oid) {
            return Ok(Some(r));
        }
        // **Check-then-act, and the answer is to look again, not to wait.**
        // The index miss above and the bit read below are two reads with the
        // drain running between them: the pack's rows can land AND its bit
        // clear after the miss, and "no pending pack, so absent" was then a
        // lie about a durable object — the one answer §13.12 forbids
        // (`no_read_is_told_absent_while_the_drain_is_running` caught it,
        // 1 absent answer in 1352, 2 of 10 full-suite runs under load,
        // 2026-09-28). The bit clears only AFTER the rows go in, so once it
        // reads clear a second index read is authoritative.
        if self.unindexed_packs() == 0 {
            return Ok(self.objects.lookup(oid));
        }
        let (mut rows, _) = self.scan_pending(&[oid], None)?;
        if let Some(r) = rows.pop().flatten() {
            return Ok(Some(r));
        }
        // The same window one step later: the pack was absorbed and left the
        // pending list between the bit read and the scan.
        Ok(self.objects.lookup(oid))
    }

    /// Many oids, never waiting: one index pass, then one read-only pass over
    /// the pending packs for whatever the index did not have.
    fn lookup_batch_never_wait(&self, oids: &[&[u8]]) -> Result<Vec<Option<crate::index_layout::IndexRow>>> {
        let mut rows = self.objects.lookup_batch(oids);
        if rows.iter().all(Option::is_some) {
            return Ok(rows);
        }
        // See `lookup_never_wait`: a miss followed by a clear bit is re-read,
        // because the drain may have landed the rows between the two.
        if self.unindexed_packs() == 0 {
            return Ok(self.objects.lookup_batch(oids));
        }
        let missing: Vec<&[u8]> = oids
            .iter()
            .zip(&rows)
            .filter(|(_, r)| r.is_none())
            .map(|(o, _)| *o)
            .collect();
        let (found, _) = self.scan_pending(&missing, None)?;
        let mut by_oid: HashMap<&[u8], crate::index_layout::IndexRow> = HashMap::with_capacity(found.len());
        for (o, r) in missing.iter().zip(found) {
            if let Some(r) = r {
                by_oid.insert(*o, r);
            }
        }
        for (o, slot) in oids.iter().zip(rows.iter_mut()) {
            if slot.is_none()
                && let Some(r) = by_oid.get(*o)
            {
                *slot = Some(r.clone());
            }
        }
        // Absorbed between the bit read and the scan: whatever is still
        // missing gets one more index read.
        if rows.iter().any(Option::is_none) {
            for (o, slot) in oids.iter().zip(rows.iter_mut()) {
                if slot.is_none() {
                    *slot = self.objects.lookup(o);
                }
            }
        }
        Ok(rows)
    }

    /// The bit going clear: this pack is durable and its objects are not in.
    ///
    /// Skips a pack the drain already absorbed — the ack path queues *after* it
    /// has handed the extent to the channel, so the worker can legitimately be
    /// finished before this runs, and clearing a bit for a pack that is already
    /// indexed would leave it clear for ever.
    fn queue(&self, pack_id: u64, extent: Extent) -> Result<()> {
        let mut s = self
            .packs
            .lock()
            .map_err(|_| anyhow!("pack state poisoned"))?;
        s.note(pack_id, extent);
        Ok(())
    }

    /// **The bit, derived from the two durable facts, on open.**
    ///
    /// `journal` is every row this archive's journal holds, in append order.
    /// [`acked_packs`](crate::archive_write::acked_packs) is what turns that into
    /// the packs: its index *is* the pack ordinal — dense by construction, and
    /// re-derived the same way by every later open. For each one, the question is
    /// only *does this pack have any rows in the index*, which
    /// [`ObjectReadStack::extents_with_rows`] answers in one early-terminating
    /// scan rather than per pack.
    ///
    /// Returns the packs whose bit came up **clear**: durable bytes, no rows. The
    /// caller re-queues them on the account's channel, which is what makes a
    /// pack that was mid-absorb when the process died get absorbed by the next
    /// one instead of being durable-but-invisible for ever.
    ///
    /// The verbatim extents are also handed to [`Derived::packs`] — *all* of
    /// them, not only the unabsorbed ones. That is what lets [`BaseSource`]
    /// re-derive a delta base's content from the truth after a restart; without
    /// it a reopened store knows the rows of a pack it can no longer find the
    /// bytes of.
    ///
    /// # The one case where "no rows" does not mean "never absorbed" — and the
    /// third durable fact that now tells them apart
    ///
    /// [`GitOps::gc`] is the only thing that removes rows. A pack **all** of
    /// whose objects it finds dead therefore ends with a journal extent and no
    /// rows, which is byte for byte the state a pack that was in flight when the
    /// machine died leaves behind. This diff cannot tell them apart, and it must
    /// not guess: re-queueing the first resurrects every dead object, and *not*
    /// re-queueing the second loses a pack whose bytes were acked.
    ///
    /// So `gc` says which it is, durably, before it drops a row:
    /// [`retire_packs`](crate::archive_write::retire_packs) appends a tombstone
    /// naming the retired pack's offset, and a pack named by one is never
    /// re-queued here. The bit is still derived from durable facts only — there
    /// are now three of them (the journal's pack rows, the journal's tombstones,
    /// the index's rows) and none of them is a cache of another.
    ///
    /// A **partly** dead pack is not tombstoned and still has rows, so it takes
    /// the `absorbed` branch exactly as it always did.
    ///
    /// A tombstoned pack that *does* still have rows is a `gc` that was killed
    /// between the tombstone and the drop. It is treated as absorbed, which is
    /// what its rows say: nothing is lost, and the next `gc` finishes the job.
    ///
    /// Its extent still goes to [`Derived::packs`] either way. The blob file is
    /// append-only and `gc` truncates nothing, so a retired pack's bytes are
    /// still exactly where the journal says they are — and a live object may
    /// legitimately be a delta against a base that is itself unreachable, so
    /// dropping the extent from that list would break the resolve rather than
    /// tidy it.
    ///
    /// # The second durable fact: §14's exploded table
    ///
    /// A pack counts as absorbed only if the exploded table is **whole**, which
    /// is `exploded.rows() >= objects.len()` — one row per object, because §14's
    /// table is eager and skips nothing. If it is short, the table has been
    /// dropped (or a process died between the two commits) and **no** pack counts
    /// as absorbed: every one is re-queued and re-exploded from the verbatim
    /// truth. That is the whole of "droppable": deleting the file is a supported
    /// operation whose only cost is one re-ingest, and §13.12's rule holds
    /// unchanged over it — absent means fall back, never means wrong.
    ///
    /// `>=` and not `==` on purpose. A resolve that failed part way leaves rows
    /// for the objects it got to, and a `gc` retires both tables together, so the
    /// table can legitimately hold *more* than the index names; only being
    /// **short** is evidence of a gap.
    fn adopt_journal(&self, journal: &[Extent]) -> Result<Vec<PendingPack>> {
        if journal.is_empty() {
            return Ok(Vec::new());
        }
        // The packs, in ordinal order, and the offsets a `gc` retired. A
        // tombstone is a row and not a pack, so it holds no ordinal.
        let packs = crate::archive_write::acked_packs(journal);
        let retired = crate::archive_write::retired_offsets(journal);
        if packs.is_empty() {
            return Ok(Vec::new());
        }
        // Under `Graph` the table is short **by design** — commits and trees
        // only — so the row-count comparison would call every store dropped and
        // re-queue every pack on every open. It is weakened to "not empty",
        // which still catches the case this rule exists for (the file deleted),
        // and is stated rather than hidden: making it exact needs a durable
        // commit-and-tree count, which the index does not publish today.
        // Only `Full` explodes one row per object, so only `Full` can compare
        // counts. Under `Commits` (the shipped default) and `Graph` the eager
        // pool is short **by design**, and the comparison would call every store
        // dropped and re-queue every pack on every open — a Linux-sized re-index
        // per restart. The weakened test still catches what the rule exists for
        // (the file deleted) and is stated rather than hidden: making it exact
        // needs a durable per-kind count, which the index does not publish.
        //
        // The LAZY pool is deliberately not consulted. Its size is a function of
        // what has been READ, so it says nothing about whether a pack was
        // absorbed, and an eviction must never look like a lost index.
        let exploded_is_whole = match self.exploded.policy() {
            crate::exploded_arrow::ExplodePolicy::Full => {
                self.exploded.eager_rows()? >= self.objects.len() as u64
            }
            crate::exploded_arrow::ExplodePolicy::Off => true,
            _ => self.objects.len() == 0 || self.exploded.eager_rows()? > 0,
        };
        let has_rows = if exploded_is_whole {
            self.objects.extents_with_rows(&packs)?
        } else {
            vec![false; packs.len()]
        };
        {
            let mut d = self
                .derived
                .write()
                .map_err(|_| anyhow!("derived poisoned"))?;
            d.packs = packs.clone();
        }
        let mut s = self
            .packs
            .lock()
            .map_err(|_| anyhow!("pack state poisoned"))?;
        let mut requeue = Vec::new();
        for (i, (&extent, &absorbed)) in packs.iter().zip(&has_rows).enumerate() {
            let pack_id = i as u64;
            if absorbed {
                s.mark_absorbed(pack_id, extent);
            } else if retired.contains(&extent.0) {
                // A `gc` dropped every row this pack had and said so durably
                // *before* dropping them. There is no index work owed for it,
                // ever: re-queueing it is precisely how its dead objects would
                // come back. The bit goes **up** rather than being left clear,
                // because a clear bit is what makes a read fall back to
                // absorbing — which is the same resurrection by another door.
                s.mark_absorbed(pack_id, extent);
            } else {
                s.note(pack_id, extent);
                requeue.push(PendingPack {
                    pack_id,
                    offset: extent.0,
                    len: extent.1,
                    resumed: true,
                });
            }
        }
        Ok(requeue)
    }

    /// **The indexer's half of the split**, and not one of the twelve.
    ///
    /// Reads each pending pack's verbatim bytes back out of the archive,
    /// resolves them to oids ([`crate::resolve`]), appends the rows to the
    /// `objects` table and re-folds the derived tables. This is what §13.9-12
    /// puts behind the channel; it runs after the ack, never before one.
    ///
    /// Two callers, one function: the account indexer's worker (through
    /// [`ObjectAbsorb`]) and a read that arrived before that worker did. The
    /// second is §13.12's fallback in its literal form — *slower, never wrong*.
    fn absorb_pending(&self) -> Result<usize> {
        // Nothing to do, and — this is the point — **no gate taken**: the common
        // case is a store whose drain has kept up, and it must not queue behind
        // one that is running.
        if self.unindexed_packs() == 0 {
            return Ok(0);
        }
        let _gate = self
            .gate
            .lock()
            .map_err(|_| anyhow!("absorb gate poisoned"))?;
        let jobs: Vec<PendingPack> = {
            let s = self
                .packs
                .lock()
                .map_err(|_| anyhow!("pack state poisoned"))?;
            s.pending()
        };
        self.absorb_each(&jobs, None)
    }

    /// **Every pack it can, skipping the ones it has already given up on.**
    ///
    /// The one loop all four absorb entry points run (LAW 5): they were four
    /// copies of `for job in &jobs { self.absorb_gated(job)?; }`, and that `?`
    /// is the bug this function exists to remove. Two rules, and both are
    /// consequences of the same sentence — *work that can never succeed must
    /// stop and say why*:
    ///
    /// 1. **A failure does not abandon the packs behind it.** The loop runs to
    ///    the end and reports the FIRST failure afterwards, so a pack that
    ///    cannot be indexed no longer stops the push that arrived after it from
    ///    being indexed and acked.
    /// 2. **A pack that has been given up on is not attempted again.** After
    ///    [`MAX_ABSORB_ATTEMPTS`] it is recorded in
    ///    [`Absorber::unindexable`] with the reason, logged once as
    ///    `index.unindexable`, and skipped from then on. Its objects are then
    ///    genuinely absent from the index, which every read path already knows
    ///    how to say — a push that needs one is refused by name at
    ///    `external_bases_exist`, and a clone that needs one fails the
    ///    connectivity check. What no longer happens is the store re-resolving
    ///    it on every request for the rest of the process's life.
    ///
    /// `skip` is the pack this thread is standing inside an absorb of
    /// ([`IN_ABSORB`]).
    fn absorb_each(&self, jobs: &[PendingPack], skip: Option<u64>) -> Result<usize> {
        let mut absorbed = 0usize;
        let mut first: Option<anyhow::Error> = None;
        for job in jobs {
            if skip == Some(job.pack_id) || self.given_up_on(job.pack_id) {
                continue;
            }
            match self.absorb_gated(job) {
                Ok(()) => absorbed += 1,
                Err(e) => {
                    // Cancellation is the repository being deleted: there is no
                    // queue left worth draining and nothing to record.
                    if self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
                        return Err(e);
                    }
                    self.note_absorb_failure(job, &e);
                    if first.is_none() {
                        first = Some(e);
                    }
                }
            }
        }
        match first {
            None => Ok(absorbed),
            Some(e) => Err(e),
        }
    }

    /// Every pack this store has given up on, ordinal order.
    fn unindexable_packs(&self) -> Vec<Unindexable> {
        let mut v: Vec<Unindexable> = self
            .unindexable
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .values()
            .cloned()
            .collect();
        v.sort_by_key(|u| u.pack_id);
        v
    }

    /// Has this store stopped trying to index that pack?
    fn given_up_on(&self, pack_id: u64) -> bool {
        self.unindexable
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .contains_key(&pack_id)
    }

    /// Count one failed absorb, and stop at [`MAX_ABSORB_ATTEMPTS`].
    ///
    /// The reason recorded is `root_cause`, not the outermost wrapper: that is
    /// the sentence the backend actually has to offer, and lane Z's rule is that
    /// the client gets it verbatim rather than a layer's paraphrase of it.
    fn note_absorb_failure(&self, job: &PendingPack, err: &anyhow::Error) {
        let giving_up;
        {
            let mut map = self.unindexable.lock().unwrap_or_else(|e| e.into_inner());
            // A pack already given up on is not attempted, so an entry here is
            // always a fresh count.
            let e = map.entry(job.pack_id).or_insert_with(|| Unindexable {
                pack_id: job.pack_id,
                extent: (job.offset, job.len),
                attempts: 0,
                reason: String::new(),
            });
            e.attempts += 1;
            e.reason = format!("{}", err.root_cause());
            if e.attempts < MAX_ABSORB_ATTEMPTS {
                let attempts = e.attempts;
                map.remove(&job.pack_id);
                tracing::warn!(
                    target: "znippy.git",
                    store = %self.label,
                    pack = job.pack_id,
                    attempts,
                    max = MAX_ABSORB_ATTEMPTS,
                    error = %err.root_cause(),
                    "a pack could not be indexed; it stays pending and will be tried again"
                );
                return;
            }
            giving_up = Some(e.clone());
        }
        if let Some(u) = giving_up {
            tracing::error!(
                target: "znippy.git",
                store = %self.label,
                event = "index.unindexable",
                pack = u.pack_id,
                offset = u.extent.0,
                len = u.extent.1,
                attempts = u.attempts,
                error = %u.reason,
                "this store has STOPPED trying to index this pack after {} attempts. Its bytes \
                 are durable and untouched, and every object it introduced is absent from the \
                 index — a push that deltas against one is refused by name and a clone that \
                 needs one fails its connectivity check, both immediately. Nothing will retry \
                 it: re-push the pack, or delete and re-create the repository.",
                u.attempts
            );
        }
    }

    /// One pack, **with [`Absorber::gate`] already held**.
    ///
    /// The order at the end is the correctness argument: the rows are in the
    /// index *before* the bit is cleared. A read that finds the bit still clear
    /// blocks on the gate and then finds the rows; a read that finds it set finds
    /// the rows too. There is no interleaving in which a durable object answers
    /// "absent" — which during negotiation would make a client withhold objects
    /// and lose data.
    fn absorb_gated(&self, job: &PendingPack) -> Result<()> {
        if self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
            // The repository is being deleted: no pack still queued is worth a
            // byte of work, and the drain must get through its queue fast so
            // the store can be dropped and the directory removed.
            return Err(crate::resolve::ResolveError::cancelled());
        }
        {
            let s = self
                .packs
                .lock()
                .map_err(|_| anyhow!("pack state poisoned"))?;
            if s.is_absorbed(job.pack_id) {
                // Already in, by whoever reached it first. Re-resolving is now
                // *correct* — the exploded table is keyed by oid and the graph is
                // folded from it rather than pushed at, so a second absorb of one
                // pack changes nothing (that idempotence is what makes dropping
                // the table and re-queueing every pack a safe operation). It is
                // still a whole pack re-read, re-inflated and re-hashed for
                // nothing, so it is skipped.
                return Ok(());
            }
        }
        // From here to the end of `absorb_one` this thread holds the gate, and
        // the resolver is about to ask this same store for delta bases. See
        // [`IN_ABSORB`]: the re-entry must not take the gate again and must not
        // try to absorb the pack it is standing in.
        let _in = InAbsorb::enter(job.pack_id);
        self.absorb_one(job).map_err(|e| {
            // The entry stays pending by construction — it was never removed —
            // so the bytes are durable, the pack is still un-indexed, and reads
            // keep falling back rather than answering absent.
            e.context(format!(
                "absorbing pack {} at ({}, {}) — its bytes are durable and it stays \
                 un-indexed; reads will keep falling back rather than answer absent",
                job.pack_id, job.offset, job.len
            ))
        })?;
        let mut s = self
            .packs
            .lock()
            .map_err(|_| anyhow!("pack state poisoned"))?;
        s.mark_absorbed(job.pack_id, (job.offset, job.len));
        drop(s);
        // The index answers for it now; the reader's scan is dead weight.
        self.scanned.lock().unwrap_or_else(|e| e.into_inner()).remove(&job.offset);
        Ok(())
    }

    /// One pack: verbatim bytes in, `objects` rows **and** §14's exploded rows
    /// out, from **one** walk and **one** resolve.
    ///
    /// The exploded rows are not a second pass and not a second resolver (LAW 5):
    /// [`crate::resolve::resolve_walked`] hands every object it produces to the
    /// sink as it produces it, including the blob payloads it is about to drop,
    /// so the side table falls out of the pass that was already being made.
    ///
    /// Ordering is the correctness argument, and it is the same one the drain
    /// makes one level up: **the exploded rows are committed before the fold that
    /// reads them**, and the fold runs before this returns, so there is no
    /// interleaving in which the graph is folded over a table that does not yet
    /// hold this pack's commits.
    fn absorb_one(&self, job: &PendingPack) -> Result<()> {
        let t0 = std::time::Instant::now();
        self.progress.begin(job.pack_id, job.len, job.resumed);
        // **A live row every 10 s for as long as this pack takes**, carrying
        // `peak_rss` and the re-inflation count. Those two rode only on
        // `index.finished`, so lane P2's two rig boxes — which ran for 2h14m
        // and 2h12m and never finished a pack — produced neither, in exactly
        // the failure they were built for. The ticker is a thread and not a
        // hook inside the resolve loop on purpose: it prints while the resolver
        // is PAUSED too, which is when an operator most needs it.
        let _tick = crate::progress::ProgressTicker::start(self.progress.clone());
        let result = self.absorb_one_inner(job, t0);
        self.progress.sample_memory();
        self.progress.finish();
        result
    }

    /// The body of [`absorb_one`](Self::absorb_one), so `finish` runs on every
    /// exit and the progress row never sticks at 99 %.
    fn absorb_one_inner(&self, job: &PendingPack, t0: std::time::Instant) -> Result<()> {
        use crate::progress::Phase;
        let progress = &self.progress;
        // **The pack is read where it already is.** `read_extent` was a
        // `pread` of the whole extent into a fresh `Vec` — 8.12 GiB of
        // anonymous heap for torvalds/linux, before one byte was inflated, on a
        // 16 GB box. The mapping costs nothing the kernel cannot reclaim
        // ([`crate::archive_map`]), and `MemAvailable` — what the watchdog
        // reads — knows that.
        let snap = self.map.snapshot()?;
        let bytes: std::borrow::Cow<'_, [u8]> = match snap.get(job.offset, job.len) {
            Some(b) => std::borrow::Cow::Borrowed(b),
            // Past the mapping: the file grew after the snapshot. Same bytes,
            // one `pread` — the exception, not the shape.
            None => std::borrow::Cow::Owned(self.read_extent(job.offset, job.len)?),
        };
        progress.set_phase(Phase::Walk);
        let walked = crate::pack_walk::walk(&bytes, self.hash.oid_len())?;
        let t_walk = t0.elapsed();
        let dog = self.watchdog();
        let spill = || self.spill();
        let limits = crate::resolve::ResolveLimits::for_indexer(
            &self.label,
            &self.cancel,
            progress,
            dog,
            &spill,
        );
        let mut batches = 0u64;
        let mut appended = 0u64;
        let mut entries: Vec<crate::index_layout::IndexEntry> = Vec::with_capacity(limits.row_batch);
        let report = crate::resolve::resolve_streaming(
            &bytes,
            &walked,
            self.hash,
            job.offset,
            self,
            &*self.exploded,
            limits,
            &mut |rows| {
                // **One batch of rows lands, then the next.** The exploded
                // tier already flushed itself every 64 MiB; the index rows
                // used to wait for the whole pack. Now the batch is the unit:
                // rows go to the `objects` table as they are produced, and the
                // pack's own "indexed" bit still goes up only after the LAST
                // batch — `mark_absorbed` is the caller's, after this returns.
                entries.clear();
                entries.extend(rows.iter().map(|r| r.index_entry()));
                rows.clear();
                self.objects.append(&entries)?;
                appended += entries.len() as u64;
                batches += 1;
                Ok(())
            },
        )?;
        drop(entries);
        let t_resolve = t0.elapsed() - t_walk;
        progress.set_phase(Phase::Flush);
        // Down before anything folds over it.
        self.exploded.flush()?;
        // A push is what fills the disk, so the push is what asks the cache to
        // give space back (the disk line, `exploded_cache::DISK_LINE_PERCENT`).
        // Until 2026-09-28 only a reader's write-back started the maintenance
        // thread, so a store nobody read never looked at the disk. `kick`
        // spawns and returns: the indexer does not wait for an unlink.
        self.exploded.kick();

        {
            let mut d = self
                .derived
                .write()
                .map_err(|_| anyhow!("derived poisoned"))?;
            // A reopen already listed every acked extent (`adopt_journal`), so
            // this is the first absorb of a pack pushed in *this* process — or a
            // re-queued one that is already listed. `find` is what reads this
            // list, so a duplicate would not be wrong, only unbounded.
            if !d.packs.contains(&(job.offset, job.len)) {
                d.packs.push((job.offset, job.len));
            }
        }
        progress.set_phase(Phase::Fold);
        let t_fold0 = std::time::Instant::now();
        // The graph and the tree payloads are folded from the exploded table, not
        // pushed at from here. That is what makes a re-absorb idempotent — which
        // it has to be, because dropping the table re-queues every pack.
        self.refold()?;
        let _ = self.objects.maybe_rebuild()?;
        let t_fold = t_fold0.elapsed();
        // **The audit line**: every number is applied output of this absorb.
        // `peak_rss` is the process's VmHWM off /proc/self/status — the high
        // water mark of the whole server, which on the appliance is the box.
        tracing::info!(
            target: "gunnar::index",
            event = "index.finished",
            repo = %self.label,
            pack_id = job.pack_id,
            pack_bytes = job.len,
            peak_rss = crate::memguard::peak_rss_bytes(),
            mem_available = self.watchdog().available().unwrap_or(0),
            objects = report.rows,
            batches = batches,
            rows_appended = appended,
            reinflations = report.reinflations,
            evictions = report.evictions,
            watchdog_drops = report.watchdog_drops,
            peak_base_bytes = report.peak_base_bytes,
            pauses = report.pauses,
            paused_ms = report.paused_ms,
            walk_ms = t_walk.as_millis() as u64,
            resolve_ms = t_resolve.as_millis() as u64,
            fold_ms = t_fold.as_millis() as u64,
            total_ms = t0.elapsed().as_millis() as u64,
            resumed = job.resumed,
            "indexed {} objects in {} batches: walk {} ms, resolve {} ms, fold {} ms; peak bases {}, {} evictions, {} re-inflations, {} pauses ({} ms); peak rss {}",
            report.rows,
            batches,
            t_walk.as_millis(),
            t_resolve.as_millis(),
            t_fold.as_millis(),
            crate::memguard::fmt_bytes(report.peak_base_bytes),
            report.evictions,
            report.reinflations,
            report.pauses,
            report.paused_ms,
            crate::memguard::fmt_bytes(crate::memguard::peak_rss_bytes())
        );
        Ok(())
    }

    /// Recompute everything derived from the object set: the commit graph, the
    /// tree payloads, the ordinal space, the generation numbers, and (lazily) the
    /// bitmaps.
    ///
    /// **The graph is folded from §14's exploded table, not accumulated.** That
    /// is the whole fix for the clean-reopen hole: commit and tree payloads are
    /// on disk, so this call produces the same graph after a restart as before
    /// one, and it is called at the end of [`GitStore::open_with_arms`] for
    /// exactly that reason. It also makes a re-absorb idempotent — the old
    /// accumulate-into-a-`Vec` shape doubled every commit if a pack was absorbed
    /// twice, which is why dropping the table and re-queueing everything was not
    /// a safe operation before this.
    ///
    /// **Generations are stored and must be recomputed in any fold** (§13,
    /// decided). A generation number is `1 + max(parents)`, so it is invalidated
    /// the moment history's shape changes — which is exactly what absorbing a
    /// pack does. [`assign_generations`] is the one writer of that number and it
    /// is called here, over the whole graph, rather than incrementally: an
    /// incremental update would have to know which descendants moved, and being
    /// wrong about that produces an ancestry cutoff that skips real ancestors.
    ///
    /// # Cost
    ///
    /// One range scan of the exploded table's commits and one of its trees, per
    /// absorbed pack. It is the same order as the `tail_oids` scan below, which
    /// this function already made on every absorb, and it reads **no blob
    /// payload** — that is what the kind index in
    /// [`crate::exploded`] is for.
    ///
    /// ## And that order is the whole repository, on every push
    ///
    /// Said plainly, because "the same order as the scan below" reads like a
    /// reassurance and is not one: **nothing here is proportional to the push.**
    /// Every call rebuilds every tree payload, every commit node, every
    /// generation number, a `HashMap<String, u32>` over every oid in the
    /// repository and a sorted `Vec<String>` of the same — for a push of one
    /// commit exactly as for a push of ten thousand.
    ///
    /// MEASURED on oden 2026-08-11, release, quiet box (`some avg10` 0.00). The
    /// **same** 100-commit increment, pushed onto the same history seeded to
    /// four different depths, server CPU for the push:
    ///
    /// | objects already in the repository | CPU |
    /// |---:|---:|
    /// | 9 614 | 0.12 s |
    /// | 35 350 | 0.23 s |
    /// | 103 988 | 0.45 s |
    /// | 206 925 | 0.77 s |
    ///
    /// That is a straight line: **≈88 ms fixed, plus ≈3.3 µs per object already
    /// stored**, and the fit predicts the four points to within 20 ms. It is
    /// also why a push is slower than the ack path suggests — §13.9 puts the
    /// index behind a channel, but `put_refs` checks every ref target with
    /// `has`, `has` calls `lookup_one`, and `lookup_one` absorbs pending packs
    /// first. The drain is off the *ack* and squarely on the *push*.
    ///
    /// This is not fixed here and the numbers are recorded so the next attempt
    /// starts from them rather than from a guess. The obvious lever — fold
    /// incrementally — is the one the paragraph above rules out for
    /// generations, so it needs its own argument and its own gate.
    fn refold(&self) -> Result<()> {
        // Everything derived is computed **before** the write lock, which is then
        // held only for the swap: the fold is the long part and nothing that
        // reads `derived` should queue behind it.
        //
        // Ordinals first — **read, not re-scanned, when the tail has not moved.**
        // S-082's fix, mirroring the commit-graph memo one paragraph down:
        // `objects.ordinal` beside the pack holds `oids_raw` (every oid in the
        // store, in ordinal = sorted-raw order), and a cold open reads its couple
        // of megabytes back sequentially in milliseconds instead of walking the
        // whole redb B-tree — REFOLD measured that scan at ~65% (0.45 s) of a
        // 136k-object reopen, and proved a flat buffer measured the same, so the
        // cost is the SCAN, not the allocation. It is a memo, not a second truth:
        // the redb tail stays authoritative and the file is discarded unless its
        // (epoch, count) both match the live tail, so a push, a gc or a torn
        // write all fall back to the scan and re-persist.
        //
        // The raw concatenation is BOTH the ordinal space and the validity token
        // for the commit graph below, so the graph is read whenever the object
        // set is unchanged; the hex form and the ordinal map fold out of the same
        // bytes, so ordinal `o` names the same object in every representation by
        // construction rather than by agreeing computations (LAW 5). The tail
        // hands oids in oid order, which is byte order over fixed-width oids and
        // therefore already the sorted concatenation the memo stores.
        //
        // **2026-09-04: the memo is gone, because the scan it spared is gone.**
        // The read stack persists its projection now (`objects.index`), and the
        // sorted oid list IS that index's oid column — one contiguous copy out
        // of a mapped buffer, plus a merge of the few rows redb still holds
        // since the last fold. No file of its own, no header, no epoch to
        // validate: the projection is current by construction. What is kept is
        // the provenance — how many oids came off the index and how many off
        // the tail — because that is the only thing that can prove the space
        // was not a scan (both paths yield identical bytes).
        let space = self.objects.oids_raw()?;
        self.ordinal_folded
            .store(space.folded_rows, std::sync::atomic::Ordering::Relaxed);
        self.ordinal_tail
            .store(space.tail_rows, std::sync::atomic::Ordering::Relaxed);
        let oids_raw = space.raw;
        let token = graph_token(&oids_raw);

        // The commit graph — **read, not recomputed, when the object set has not
        // moved.** S-065's fix: `objects.graph` beside the pack holds the folded
        // graph with generations, written by this same call at derive time and
        // read here. It is not a second truth — it is a memoized projection
        // validated on every read against the authoritative object set (the
        // token is a blake3 over every oid in the store), and an absent file, a
        // stale token or a decode failure all fall back to the fold and
        // re-persist. Same shape as lane REFCAS persisting a tag's peeled target.
        //
        // On a fold, commit payloads are read out of §14's exploded table (no
        // tree payload — that was lane Q's 28.24 GB and most of the 50.9 GiB RSS
        // on `torvalds/linux`), parsed, and generation-numbered. That is the
        // whole of the O(commits) open cost this persistence removes.
        let cached = if self.graph_cache.load(std::sync::atomic::Ordering::Relaxed) {
            self.load_persisted_graph()?
        } else {
            None
        };
        let graph: Vec<CommitNode> = match cached {
            Some((tok, g)) if tok == token => {
                self.graph_read.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                g
            }
            _ => {
                self.graph_recomputed
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let commits = self.exploded.of_kind(GitObjectKind::Commit)?;
                let g: Vec<CommitNode> = commits
                    .iter()
                    .map(|(oid, payload)| {
                        let h = crate::object::parse_commit(payload);
                        CommitNode {
                            oid: hex::encode(oid),
                            parents: h.parents,
                            tree: h.tree,
                            committer_time: h.committer_time,
                            generation: 0,
                        }
                    })
                    .collect();
                let g = assign_generations(g);
                // Persist for the next open. A write failure is not fatal to the
                // fold — the graph is correct in memory and the next open simply
                // recomputes — so it is logged, not propagated.
                if !self.graph_cache.load(std::sync::atomic::Ordering::Relaxed) {
                    // Switched off: no memo on this disk.
                } else if let Err(e) = self.persist_graph(&token, &g) {
                    tracing::warn!(store = %self.label, "could not persist objects.graph: {e:#}");
                }
                g
            }
        };

        // The same commit set `select` refuses a `want` against, in the raw form
        // it tests. Folded once here instead of once per request; see the field.
        // A row that does not decode makes the whole set `None`, which is the
        // decline `select` used to reach by returning early out of its own loop.
        let commit_raw = graph
            .iter()
            .map(|n| hex::decode(&n.oid).ok())
            .collect::<Option<std::collections::HashSet<Vec<u8>>>>()
            .map(Arc::new);
        // No hex `Vec<String>` and no `HashMap<String, u32>` are folded here any
        // more (S-082): `oids_raw` is the whole ordinal space, and oid ⇄ ordinal
        // is served off it by [`crate::reach::OrdinalSpace`] — a slice one way, a
        // binary search the other. That removed the ~0.13 s + ~0.08 s this fold
        // spent building those two per-oid `String` tables, and their resident
        // cost with them.
        // The graph-by-oid lookup, folded here so `reachable` borrows it instead
        // of rebuilding it per negotiation. Keyed by hex, the form the walk
        // keys by. Same lifecycle as `commit_raw`: rebuilt on every fold, so it
        // cannot outlive the graph it indexes.
        let graph_index: HashMap<String, u32> = graph
            .iter()
            .enumerate()
            .map(|(i, n)| (n.oid.clone(), i as u32))
            .collect();

        let mut d = self
            .derived
            .write()
            .map_err(|_| anyhow!("derived poisoned"))?;
        // ── carry the reachability table across the fold ──────────────────
        //
        // The table describes immutable commits; the fold only renumbers the
        // ordinal space. Carry it (renumbered) while the graph has not outgrown
        // the last full build by more than the carry rule allows — else drop it
        // and let the next reader rebuild, which is what every fold used to do.
        // See `REACH_CARRY_MAX_FRACTION` for the measurement behind this.
        let carried: Option<Vec<ReachEntry>> = if d.reach.is_empty() {
            None
        } else {
            let grown = graph.len().saturating_sub(d.reach_full_len);
            let allowed = (d.reach_full_len / REACH_CARRY_MAX_FRACTION).max(REACH_CARRY_MIN_COMMITS);
            if grown > allowed {
                None
            } else {
                let oid_len = self.hash.oid_len();
                let old_space = crate::reach::OrdinalSpace::new(&d.oids_raw, oid_len);
                let new_space = crate::reach::OrdinalSpace::new(&oids_raw, oid_len);
                crate::reach::carry_reach(&d.reach, &old_space, &new_space, |c| graph_index.contains_key(c))
            }
        };
        tracing::info!(
            store = %self.label,
            reach_len = d.reach.len(),
            reach_full_len = d.reach_full_len,
            graph_len = graph.len(),
            carried = carried.as_ref().map(Vec::len),
            "fold: reachability table carry decision"
        );
        d.graph = graph;
        d.graph_index = graph_index;
        d.commit_raw = commit_raw;
        d.oids_raw = oids_raw;
        match carried {
            Some(entries) => {
                let index: HashMap<String, u32> = entries
                    .iter()
                    .enumerate()
                    .map(|(i, e)| (e.commit.clone(), i as u32))
                    .collect();
                d.reach = Arc::new(entries);
                d.reach_index = Arc::new(index);
                self.reach_carried
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
            None => {
                // Over the ordinal space that just changed and not carriable;
                // both are rebuilt lazily by `reach_bitmaps_with`.
                d.reach = Arc::default();
                d.reach_index = Arc::default();
            }
        }
        Ok(())
    }

    /// `(reach_carried, reach_rebuilt)` — how many folds since open carried the
    /// reachability table across (renumbered) vs how many reads built it from
    /// scratch. See [`tests::a_push_carries_the_reach_table_across_the_fold`].
    fn reach_source_stats(&self) -> (u64, u64) {
        (
            self.reach_carried.load(std::sync::atomic::Ordering::Relaxed),
            self.reach_rebuilt.load(std::sync::atomic::Ordering::Relaxed),
        )
    }

    /// Where the folded commit graph is cached, beside the verbatim pack:
    /// `<root>/objects.graph`.
    fn graph_cache_path(&self) -> PathBuf {
        self.blobs.with_file_name(GRAPH_CACHE_FILE)
    }

    /// The persisted graph and the token it was written under, or `None` when
    /// the cache is absent, truncated, an unknown version, or fails to decode —
    /// every one of which is a signal to recompute and re-persist rather than an
    /// error, because the cache is a memo and the exploded table is the truth.
    fn load_persisted_graph(&self) -> Result<Option<([u8; 32], Vec<CommitNode>)>> {
        let bytes = match std::fs::read(self.graph_cache_path()) {
            Ok(b) => b,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(e).with_context(|| {
                    format!("reading {}", self.graph_cache_path().display())
                });
            }
        };
        // Frame: b"GRPH" (4) + version (1) + token (32) + Arrow IPC graph.
        if bytes.len() < GRAPH_CACHE_HEADER || &bytes[..4] != GRAPH_CACHE_MAGIC || bytes[4] != 1 {
            return Ok(None);
        }
        let mut token = [0u8; 32];
        token.copy_from_slice(&bytes[5..GRAPH_CACHE_HEADER]);
        match crate::graph::decode_graph(&bytes[GRAPH_CACHE_HEADER..]) {
            Ok(g) => Ok(Some((token, g))),
            Err(_) => Ok(None),
        }
    }

    /// Write the folded graph and its token durably: encode, write a temp file,
    /// fsync it, then rename over the cache — the rename is the atomic publish,
    /// so a reader never sees a half-written graph.
    fn persist_graph(&self, token: &[u8; 32], nodes: &[CommitNode]) -> Result<()> {
        use std::io::Write as _;
        let ipc = crate::graph::encode_graph(nodes)?;
        let mut out = Vec::with_capacity(GRAPH_CACHE_HEADER + ipc.len());
        out.extend_from_slice(GRAPH_CACHE_MAGIC);
        out.push(1);
        out.extend_from_slice(token);
        out.extend_from_slice(&ipc);

        let path = self.graph_cache_path();
        let tmp = path.with_extension("graph.tmp");
        {
            let mut f = File::create(&tmp)
                .with_context(|| format!("creating {}", tmp.display()))?;
            f.write_all(&out)
                .with_context(|| format!("writing {}", tmp.display()))?;
            f.sync_all()
                .with_context(|| format!("fsync {}", tmp.display()))?;
        }
        std::fs::rename(&tmp, &path)
            .with_context(|| format!("publishing {}", path.display()))?;
        Ok(())
    }

    /// `(graph_read_from_disk, graph_recomputed)` — how many folds since open
    /// read the persisted graph vs recomputed it. The only thing that can prove
    /// the persisted path ran; see
    /// [`tests::a_reopen_reads_the_persisted_graph_it_does_not_recompute`].
    fn graph_source_stats(&self) -> (u64, u64) {
        (
            self.graph_read.load(std::sync::atomic::Ordering::Relaxed),
            self.graph_recomputed
                .load(std::sync::atomic::Ordering::Relaxed),
        )
    }

    /// `(folded_rows, tail_rows)` of the ordinal space the last fold built — how
    /// many oids came straight off the persisted index's oid column and how many
    /// off a scan of the redb tail. The only thing that can prove the space was
    /// not a scan (LAW 2), because both sources yield identical bytes; see
    /// [`tests::the_ordinal_space_comes_off_the_index_not_a_scan`].
    fn ordinal_source_stats(&self) -> (u64, u64) {
        (
            self.ordinal_folded.load(std::sync::atomic::Ordering::Relaxed),
            self.ordinal_tail.load(std::sync::atomic::Ordering::Relaxed),
        )
    }

    /// The bitmaps, built on first use after a fold and cached until the next.
    fn reach_bitmaps(&self) -> Result<Arc<Vec<ReachEntry>>> {
        self.reach_bitmaps_with(live_reach_policy(), true)
    }

    /// [`Absorber::reach_bitmaps`] with the policy **named** and the cache
    /// optional. The bitmaps alone; [`Absorber::reach_tables_with`] is the one
    /// builder and this drops the index it also returns, for callers that seal
    /// the table or compare two of them and never key into one by oid.
    fn reach_bitmaps_with(
        &self,
        policy: crate::reach::ReachPolicy,
        cache: bool,
    ) -> Result<Arc<Vec<ReachEntry>>> {
        Ok(self.reach_tables_with(policy, cache)?.0)
    }

    /// **The reach table and its oid index, as one pair that is always in
    /// step.** [`crate::reach::accumulate`] keys the table by commit oid, and
    /// building that index per negotiation is exactly the O(commits) waste this
    /// lane removes — so it is built once, here, beside the table, and handed
    /// back with it. The two travel together (both cached, both returned) so a
    /// caller can never pair a fresh index against a stale table or the reverse.
    ///
    /// `cache` is false for the differential guard, which builds the table at two
    /// very different caps over one store and requires the two to answer
    /// identically; letting either poison `d.reach` would make the second arm
    /// read the first one's table and the comparison would be of a thing against
    /// itself.
    fn reach_tables_with(
        &self,
        policy: crate::reach::ReachPolicy,
        cache: bool,
    ) -> Result<(Arc<Vec<ReachEntry>>, Arc<HashMap<String, u32>>)> {
        {
            let d = self
                .derived
                .read()
                .map_err(|_| anyhow!("derived poisoned"))?;
            if cache && !d.reach.is_empty() {
                // Two refcount bumps. This was `d.reach.clone()` — one deep copy
                // of every commit's roaring bitmap, per call, twice per request
                // — plus, before this lane, a whole `HashMap<&str,_>` rebuilt
                // from the table on every call at the negotiation site.
                return Ok((Arc::clone(&d.reach), Arc::clone(&d.reach_index)));
            }
            if d.graph.is_empty() {
                return Ok((Arc::default(), Arc::default()));
            }
        }
        let mut d = self
            .derived
            .write()
            .map_err(|_| anyhow!("derived poisoned"))?;
        // Built before the facts so it outlives them, and deliberately NOT
        // holding the `derived` guard: `Absorber::resolved` does not take that
        // lock, which is what makes a live tree lookup legal from inside this
        // write section at all.
        let trees = self.tree_source();
        let oid_len = self.hash.oid_len();
        let facts = crate::reach::ObjectFacts {
            ordinal: crate::reach::OrdinalSpace::new(&d.oids_raw, oid_len),
            trees: &trees,
            oid_len,
        };
        let started = std::time::Instant::now();
        let built = Arc::new(crate::reach::build_reach(&d.graph, &facts, policy));
        self.reach_rebuilt
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        tracing::info!(
            store = %self.label,
            entries = built.len(),
            commits = d.graph.len(),
            elapsed_ms = started.elapsed().as_millis() as u64,
            cache,
            "built the reachability table from scratch"
        );
        // The commit count this build covered — the denominator the next fold's
        // carry rule divides by (`REACH_CARRY_MAX_FRACTION`).
        d.reach_full_len = d.graph.len();
        // The index over the table just built — commit oid → row — so the
        // negotiation looks a bitmap up by a hash rather than by rebuilding this
        // map first.
        let index: Arc<HashMap<String, u32>> = Arc::new(
            built
                .iter()
                .enumerate()
                .map(|(i, e)| (e.commit.clone(), i as u32))
                .collect(),
        );
        if cache {
            // `Arc::new` once each, then a refcount bump into the cache — the
            // second full copy the table line used to make
            // (`d.reach = built.clone()`) is gone, and the index is cached in
            // lockstep so the read arm above can hand out both.
            d.reach = Arc::clone(&built);
            d.reach_index = Arc::clone(&index);
        }
        Ok((built, index))
    }

    /// The commit oid set, raw, as folded. See [`Derived::commit_raw`].
    fn commit_oids_raw(&self) -> Result<Option<Arc<std::collections::HashSet<Vec<u8>>>>> {
        Ok(self
            .derived
            .read()
            .map_err(|_| anyhow!("derived poisoned"))?
            .commit_raw
            .clone())
    }

    // `ordinal_space()` lived here: `d.oids.clone()`, a fresh `Vec<String>` of
    // every oid in the store, handed to `reachable_oids` twice per request. It
    // is gone, and so is `d.oids` itself (S-082): the serve path borrows
    // `d.oids_raw` as an `OrdinalSpace` under the read guard it was already
    // going to take, and reads oid ⇄ ordinal straight off it.

    /// `pread` an extent out of the verbatim archive, **into uninitialised
    /// capacity** — no zero-fill before the read.
    ///
    /// This used to be `vec![0u8; len]` + `read_exact_at`, and under emit
    /// concurrency the zeroing was not a detail: profiled on oden 2026-08-12
    /// (gunnar serving 32 concurrent clones, perf on the server pid), ~44 % of
    /// serve CPU was memory zeroing/copying — `memset` 18.1 % plus kernel
    /// page-zeroing 7.8 % — against ~12 % for one clone, because 32 threads
    /// churning pack-scale buffers recycle mimalloc freelist blocks that must
    /// each be memset before `pread` immediately overwrites every byte.
    ///
    /// Soundness: no reference to uninitialised memory is ever formed. The
    /// bytes are written through a raw pointer into the `Vec`'s spare
    /// capacity, `EINTR` retries, a short read refuses, and `set_len` runs
    /// only after every one of `len` bytes has been written.
    fn read_extent(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
        use std::os::fd::AsRawFd;
        let want = usize::try_from(len).context("extent length overflows usize")?;
        let mut buf: Vec<u8> = Vec::with_capacity(want);
        let fd = self.reader.as_raw_fd();
        let mut filled = 0usize;
        while filled < want {
            let n = unsafe {
                libc::pread(
                    fd,
                    buf.as_mut_ptr().add(filled).cast(),
                    want - filled,
                    i64::try_from(offset + filled as u64).context("extent offset overflows off_t")?,
                )
            };
            if n < 0 {
                let err = std::io::Error::last_os_error();
                if err.kind() == std::io::ErrorKind::Interrupted {
                    continue;
                }
                return Err(err).with_context(|| {
                    format!("reading ({offset}, {len}) out of {}", self.blobs.display())
                });
            }
            if n == 0 {
                bail!(
                    "short read at ({offset}, {len}) out of {}: {filled} of {want} bytes before \
                     EOF — the archive is truncated relative to its index",
                    self.blobs.display()
                );
            }
            filled += n as usize;
        }
        // Every byte of `want` is now initialised.
        unsafe { buf.set_len(want) };
        Ok(buf)
    }
}

/// **The drain's object-level ingress**, and the reason a push ends in object
/// rows without anybody reading first.
///
/// The account indexer holds this as an `Arc<dyn ObjectAbsorb>` and calls it once
/// per drained job, on its own thread, after the ack. It is the *same* absorb a
/// falling-back read takes, gate and all (LAW 5): there is no background copy of
/// this logic to drift.
impl<S: ObjectIndex> ObjectAbsorb for Absorber<S> {
    fn absorb(&self, job: IndexJob) -> Result<()> {
        // **The memory watchdog, BEFORE the pack and BEFORE the gate**
        // ([`crate::memguard`]). Inside the pack the resolver checks again
        // every few thousand objects; this is the check that keeps a burst of
        // packs from starting one more absorb on a box that is already short.
        // Taken before the gate on purpose: a paused worker holds nothing —
        // not the gate, not a row, not a base — so a reader that wants to
        // absorb for itself can, and every other reader scans the pack.
        if self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
            return Err(crate::resolve::ResolveError::cancelled());
        }
        let dog = self.watchdog();
        if dog.breached().is_some() {
            self.progress.begin(job.pack_id, job.len, false);
            self.progress.set_phase(crate::progress::Phase::Paused);
            self.progress.add_pause();
            let r = dog.pause_until_ok(&self.label, Some(&self.cancel), &mut || Ok(self.spill()));
            self.progress.finish();
            let paused = r?;
            // The pause before the pack has the same rule as the one inside it:
            // a give-up is not a resume. Starting an 8 GiB pack on a box that
            // just told us it has nothing left is how the parked hours began.
            if paused.end.gave_up() {
                return Err(crate::resolve::ResolveError::out_of_memory(
                    paused.end.as_str(),
                    paused.available,
                    paused.budget,
                    0,
                    0,
                ));
            }
        }
        let _gate = self
            .gate
            .lock()
            .map_err(|_| anyhow!("absorb gate poisoned"))?;
        self.absorb_gated(&PendingPack::from_job(job))
    }
}

impl<S: ObjectIndex + 'static> GitStore<S> {
    /// The push path, for the two `put` halves.
    pub(crate) fn push_path(&self) -> &PushPath {
        &self.push
    }

    pub(crate) fn account(&self) -> &str {
        &self.account
    }

    pub(crate) fn ref_log(&self) -> &RefLog {
        &self.refs
    }

    pub(crate) fn ref_gate(&self) -> &Mutex<()> {
        &self.ref_gate
    }

    /// The closure check's index half: a `REF_DELTA`'s base has to exist —
    /// **in the store, or in this very pack**.
    ///
    /// This is the one part of receive-pack that reads `objects.oid` (§13's
    /// table), and on the path a real push takes it reads nothing else.
    ///
    /// # The second half of that sentence used to be missing, and it refused
    /// packs git itself writes
    ///
    /// [`crate::pack_walk::PackWalk::closure`] cannot do better on its own:
    /// a walk reports what the bytes say, and the bytes of a `REF_DELTA` name a
    /// base by **oid**, which is a fact about resolved content that no walk can
    /// know. So every ref base came back on `external_refs` and every one of
    /// them was required to be in the store already.
    ///
    /// A `REF_DELTA` naming a base *inside the same pack* is ordinary and git
    /// writes it constantly: `git index-pack --fix-thin` completes a pushed thin
    /// pack by **appending the base object to the pack** and leaving the delta
    /// naming it by oid. Every such pack was refused with *"this pack deltas
    /// against X, which this repository does not have"*, on a store that was
    /// being handed a perfectly ordinary, self-contained packfile — the base was
    /// entry 1 of 25 in the pack's own `.idx` (`gunnar.multi_pack_serve`,
    /// 2026-08-14). The same missing check is `S-003` / gitoxide#2882 in
    /// `LookupRefDeltaObjectsIter`; it is the same defect wearing the receiving
    /// hat instead of the sending one.
    ///
    /// # What it costs, and where
    ///
    /// **Nothing on any push that was going to succeed before.** Every base
    /// found in the store short-circuits exactly as it did, and a pack with no
    /// ref-delta at all never gets past the first loop.
    ///
    /// The pack is resolved only when the alternative is *refusing it*, and then
    /// the resolve is the cheapest honest answer available: an entry's oid is
    /// knowable only by applying its delta chain, which is precisely what
    /// [`crate::resolve::resolve_walked`] does — the same resolver the absorb is
    /// about to run over the same pack anyway, reused rather than twinned
    /// (LAW 5). A push that is genuinely thin against a base nobody has still
    /// fails, one resolve later, and still names the oid.
    pub(crate) fn external_bases_exist(&self, bytes: &[u8], w: &PackWalk) -> Result<()> {
        let c = w.closure();
        if !c.broken_offsets.is_empty() {
            bail!(
                "this pack is corrupt: {} delta base offset(s) do not land on an entry — first {}",
                c.broken_offsets.len(),
                c.broken_offsets[0]
            );
        }
        // The fast path, unchanged: a base the store already holds is settled
        // without reading one byte of the pack.
        let mut unheld: Vec<&[u8]> = Vec::new();
        for oid in &c.external_refs {
            if self.lookup_one(oid)?.is_none() {
                unheld.push(oid.as_slice());
            }
        }
        if unheld.is_empty() {
            return Ok(());
        }

        // Only now, and only because the alternative is refusing the push: does
        // the pack supply these itself? `resolve_walked` answers with the
        // store behind it, so a base that really is external is still found the
        // cheap way and only a genuinely absent one fails.
        let resolved = crate::resolve::resolve_walked(
            bytes,
            w,
            self.hash_kind(),
            0,
            &*self.absorber,
            &crate::exploded::NoSink,
        )
        .with_context(|| {
            format!(
                "this pack deltas against {} object(s) this repository does not have, so it was \
                 resolved to find out whether the pack carries them itself — first {}",
                unheld.len(),
                hex::encode(unheld[0])
            )
        })?;
        let in_pack: std::collections::HashSet<&[u8]> =
            resolved.iter().map(|r| r.oid.as_slice()).collect();
        for oid in unheld {
            if !in_pack.contains(oid) {
                bail!(
                    "this pack deltas against {}, which this repository does not have and which \
                     the pack does not carry either — the push is refused rather than stored with \
                     a dangling base",
                    hex::encode(oid)
                );
            }
        }
        Ok(())
    }

    /// One oid, on the **serial** path. See [`lookup_path`].
    pub(crate) fn lookup_one(&self, oid: Oid<'_>) -> Result<Option<crate::index_layout::IndexRow>> {
        // **Never waits on the indexer.** The rows the worker has landed so far
        // are in the index; an oid it has not reached is resolved from the
        // pending pack on this thread (`Absorber::scan_pending`).
        self.absorber.lookup_never_wait(oid)
    }

    /// Many oids, on the **batch** path, never waiting on the indexer.
    pub(crate) fn lookup_batch_never_wait(
        &self,
        oids: &[Oid<'_>],
    ) -> Result<Vec<Option<crate::index_layout::IndexRow>>> {
        self.absorber.lookup_batch_never_wait(oids)
    }

    /// Absorb the pending packs on this thread **if the gate is free**;
    /// `None` = the worker holds it and this caller did not wait. See
    /// `Absorber::try_absorb_pending`.
    pub fn try_absorb_pending(&self) -> Result<Option<usize>> {
        self.absorber.try_absorb_pending()
    }

    /// The named refusal for a request that needs the whole derived graph
    /// while a pack is still being indexed: `reachable` cannot be answered
    /// from a graph that does not hold the pack's commits yet, and waiting for
    /// the worker is forbidden. The message carries the progress row's
    /// numbers so the client knows when to come back.
    fn index_in_progress(&self) -> anyhow::Error {
        let p = self.index_progress();
        anyhow!(
            "index in progress for this repository: pack {} {}% ({}/{} objects, {}) — reachability \
             needs the whole graph; retry when the index row reaches 100 %",
            p.pack_id,
            p.percent(),
            p.objects_done,
            p.objects_total,
            p.phase.as_str()
        )
    }

    /// The current ref namespace, as the log folds to it. The whole-snapshot
    /// accessor; [`ref_get`](Self::ref_get) is the keyed one.
    pub(crate) fn ref_state(&self) -> Result<BTreeMap<String, crate::refs::RefState>> {
        self.refs.current()
    }

    /// One ref by name, O(log r), without cloning the namespace — for `head`
    /// and a single-ref CAS. See [`crate::refs::RefLog::get`].
    pub(crate) fn ref_get(&self, name: &str) -> Result<Option<crate::refs::RefState>> {
        self.refs.get(name)
    }

    /// Reachability over the graph, as roaring bitmaps, in **this store's**
    /// ordinal space.
    ///
    /// Returns `(want ∪ closure) − (have ∪ closure)` as oid hex. Every object —
    /// commit, tree and blob — is in the bitmaps, because
    /// [`crate::reach::build_reach`] walks the trees; that is why this can answer
    /// with objects rather than only with commits.
    ///
    /// **Hex is for the maintenance path, not the serving one.** The answer is
    /// computed in raw bytes by [`GitStore::reachable_raw_with`] and encoded
    /// here, at one `String` per object; every caller that serves a request asks
    /// for the raw form instead. See [`Derived::oids_raw`] for what that cost.
    pub(crate) fn reachable_oids(&self, want: &[Oid<'_>], have: &[Oid<'_>]) -> Result<Vec<String>> {
        Ok(self
            .reachable_raw_with(want, have, live_reach_policy(), true)?
            .iter()
            .map(hex::encode)
            .collect())
    }

    /// [`GitStore::reachable_oids`] with the bitmap policy **named** and the
    /// cache optional.
    ///
    /// One body, not two (LAW 5): both are [`GitStore::reachable_raw_with`], so
    /// the guarded path and the shipped path are the same code.
    #[cfg(test)]
    pub(crate) fn reachable_oids_with(
        &self,
        want: &[Oid<'_>],
        have: &[Oid<'_>],
        policy: crate::reach::ReachPolicy,
        cache: bool,
    ) -> Result<Vec<String>> {
        Ok(self
            .reachable_raw_with(want, have, policy, cache)?
            .iter()
            .map(hex::encode)
            .collect())
    }

    /// `(want ∪ closure) − (have ∪ closure)`, in **raw oid bytes**, in one
    /// allocation.
    ///
    /// The answer every serving caller wants and the one the bitmaps naturally
    /// produce: an ordinal indexes straight into [`Derived::oids_raw`], so
    /// nothing is encoded, decoded or allocated per object on the way out.
    pub(crate) fn reachable_raw(
        &self,
        want: &[Oid<'_>],
        have: &[Oid<'_>],
    ) -> Result<git_storage_trait::OidList> {
        self.reachable_raw_with(want, have, live_reach_policy(), true)
    }

    /// [`GitStore::reachable_raw`] with the bitmap policy **named** and the
    /// cache optional.
    ///
    /// It exists because the answer is defined to be **independent of the
    /// policy** — [`crate::reach::accumulate`] covers whatever the table does
    /// not — and a property like that can only be tested by driving the policy.
    /// A test that could not reach it would be asserting that one code path
    /// equals itself. `cache: false` keeps one arm's table from being read by
    /// the next, which is the same trap in a different hat.
    pub(crate) fn reachable_raw_with(
        &self,
        want: &[Oid<'_>],
        have: &[Oid<'_>],
        policy: crate::reach::ReachPolicy,
        cache: bool,
    ) -> Result<git_storage_trait::OidList> {
        // The graph is folded by the absorb, so a pending pack has to be
        // absorbed before reachability can be right. If the gate is free this
        // thread does it; if the worker holds it — hours into a kernel pack,
        // or paused by the watchdog — this is refused by name, not waited on.
        if self.try_absorb_pending()?.is_none() {
            return Err(self.index_in_progress());
        }
        // `reach_bitmaps` may take the derived WRITE lock to build, so it runs
        // to completion before the read guard below is taken. Getting that order
        // wrong is a self-deadlock, not a slow path.
        // The reach table AND its oid index, one pair from the same fold. Both
        // used to be rebuilt at this site on every call: the bitmap map
        // (`e.commit → &bitmap`) here, and the graph map below — O(commits)
        // apiece, per request, for tables that cannot change between folds. They
        // are folded once now and borrowed through a [`crate::reach::ReachView`].
        let (bitmaps, reach_index) = self.reach_tables_with(policy, cache)?;
        // **One read guard, held across the whole answer, and nothing cloned out
        // of it.** This used to be `ordinal_space()?` (a `Vec<String>` of every
        // oid in the store) plus `.ordinal.clone()` (a `HashMap<String, u32>` of
        // the same, again) — ~2 × 12 455 `String` allocations per call and two
        // calls per request, for two tables that cannot change between folds.
        // Borrowing them is not a lock held longer than the work: the guard is a
        // reader, folds take the writer, and a fold that lands mid-answer would
        // invalidate the ordinals this loop is translating.
        let d = self
            .absorber
            .derived
            .read()
            .map_err(|_| anyhow!("derived poisoned"))?;
        let space = &d.oids_raw;
        let oid_len = self.hash.oid_len();
        // oid ⇄ ordinal off the flat buffer — a binary search, no map to clone
        // out of the guard. `want`/`have` arrive as raw bytes, so those lookups
        // take the raw form directly (`ordinal.ordinal_of_raw`) and never encode.
        let ordinal = crate::reach::OrdinalSpace::new(space, oid_len);

        // The graph-by-oid lookup for [`crate::reach::accumulate`]'s commit walk
        // is `d.graph_index`, folded beside `d.graph` and borrowed here — not
        // rebuilt per call. The reach table's index (`reach_index`) is paired
        // with `bitmaps` above by the same fold, so this view never mixes a
        // table with an index from a different one.
        let view = crate::reach::ReachView {
            reach: &bitmaps,
            reach_index: &reach_index,
            graph: &d.graph,
            graph_index: &d.graph_index,
        };
        let trees = self.absorber.tree_source();
        let facts = crate::reach::ObjectFacts {
            ordinal,
            trees: &trees,
            oid_len,
        };

        let mut union = roaring::RoaringBitmap::new();
        for oid in want {
            let hex = hex::encode(oid);
            match view.bitmap(hex.as_str()) {
                // A commit with a bitmap: its whole closure, in one OR.
                Some(bm) => union |= bm,
                // **No bitmap. This is the case that used to be a wrong answer.**
                //
                // It contributed the object itself and nothing else — see
                // `crate::reach::accumulate`'s header for what that cost. Now a
                // commit the graph holds is WALKED, bounded by the first
                // bitmapped commit behind it, and only a `want` the store does
                // not hold at all is still refused.
                None => {
                    if view.is_commit(hex.as_str()) {
                        crate::reach::accumulate(hex.as_str(), &view, &facts, &mut union);
                    } else if let Some(o) = ordinal.ordinal_of_raw(oid) {
                        // Not a commit at all — a TAG or a blob asked for
                        // directly.
                        union.insert(o);
                        // **A tag contributes what it points AT, and until
                        // 2026-08-31 it did not.**
                        //
                        // The bitmaps are built over the commit graph and no
                        // tree points at a tag, so a tag is in nobody's closure
                        // and this arm was the only place its target could
                        // enter. It did not, so an annotated tag shipped as one
                        // object with its commit missing, and the far end said
                        // `missing necessary objects … (peeling a tag)`. That
                        // is exactly what gunnar's replication hit on six
                        // repositories: 25 tags on one commit no branch carried.
                        //
                        // gunnar's own serve paths never had the bug because
                        // they peel BEFORE they ask a store
                        // (`gunnar-wire`'s `select_objects`, step 1). A store
                        // that answers `reachable` has to peel here, because
                        // its caller cannot know which oids are tags.
                        //
                        // A tag object is only ever reachable as a REF TIP —
                        // nothing inside a commit or a tree points at one — so
                        // peeling in the `want` loop is complete, not partial.
                        peel_tag_into(
                            self.absorber.as_ref(),
                            &hex,
                            &view,
                            &facts,
                            &mut union,
                        );
                    } else {
                        bail!(
                            "want {hex} is not in this repository — a negotiation must not be \
                             answered from a partial set"
                        );
                    }
                }
            }
        }
        let mut had = roaring::RoaringBitmap::new();
        for oid in have {
            let hex = hex::encode(oid);
            if let Some(bm) = view.bitmap(hex.as_str()) {
                had |= bm;
            } else if view.is_commit(hex.as_str()) {
                // The same walk on the exclude side, and it must be the same
                // walk: an under-counted `have` over-sends (harmless, wasteful)
                // but an under-counted `want` under-sends, and answering the two
                // sides by different rules is how a `want − have` stops being a
                // subtraction of like for like.
                crate::reach::accumulate(hex.as_str(), &view, &facts, &mut had);
            } else if let Some(o) = ordinal.ordinal_of_raw(oid) {
                had.insert(o);
            }
            // An unknown `have` is normal: the client may have objects we do not.
            // It contributes nothing, which is the safe direction — we send more,
            // never less.
        }

        let delta = union - had;
        // One allocation for the whole answer, sized before the loop. The
        // ordinal space is a flat buffer, so each object is a `copy_from_slice`
        // of `oid_len` bytes into it and nothing else.
        let mut out = git_storage_trait::OidList::with_capacity(delta.len() as usize, oid_len);
        for o in delta {
            let at = o as usize * oid_len;
            let raw = space
                .get(at..at + oid_len)
                .ok_or_else(|| anyhow!("ordinal {o} is outside this store's ordinal space"))?;
            out.push(raw)?;
        }
        Ok(out)
    }

    /// Every object reachable from every ref: what a GC must keep.
    pub(crate) fn live_set(&self) -> Result<std::collections::HashSet<String>> {
        let refs = self.ref_state()?;
        let tips: Vec<Vec<u8>> = refs
            .values()
            .filter_map(|s| s.target.as_deref())
            .filter_map(|t| hex::decode(t).ok())
            .collect();
        if tips.is_empty() {
            bail!(
                "this repository has no ref pointing at an object, so every object in it would be \
                 dead. A GC that would delete everything is refused: name a ref first"
            );
        }
        let borrowed: Vec<Oid<'_>> = tips.iter().map(|t| t.as_slice()).collect();
        let mut live: std::collections::HashSet<String> =
            self.reachable_oids(&borrowed, &[])?.into_iter().collect();
        // The peeled targets of annotated tags are reachable too, and a tag
        // object is not a commit so it has no bitmap of its own.
        for s in refs.values() {
            if let Some(p) = &s.peeled {
                live.insert(p.clone());
            }
            if let Some(t) = &s.target {
                live.insert(t.clone());
            }
        }
        Ok(live)
    }

    /// Drop every row the live set does not name. The index is append-only for
    /// everything except this.
    ///
    /// **Both tables, in one call.** §14's exploded table is retired with the
    /// `objects` table because its row count against that one's is what says
    /// whether it is whole ([`Absorber::adopt_journal`]): dropping from one and
    /// not the other would leave every later open re-exploding the entire
    /// repository. The count returned is still the index's — that is what a
    /// [`GcReport`] means by a dropped row.
    /// Drop exactly the rows in `dead` — a set the GC computed as "seen at its
    /// start and not reachable", never "not in `live`". The distinction is a
    /// row that arrived after the GC took its snapshot: it is in neither set,
    /// and the predicate below keeps it. See [`dead_oids`].
    pub(crate) fn drop_dead_rows(&self, dead: &std::collections::HashSet<Vec<u8>>) -> Result<u64> {
        let dropped = self
            .absorber
            .objects
            .retain(&|oid: &[u8]| !dead.contains(oid))?;
        self.absorber
            .exploded
            .retain(&|oid: &[u8]| !dead.contains(oid))?;
        // **Everything folded from those two tables, refolded.** The commit
        // graph, the tree payloads, the ordinal space and the bitmaps are all
        // derivations of the rows that just went, and a derivation that still
        // names a dropped oid is *wrong* rather than merely stale — a `reachable`
        // over a graph holding dead commits selects objects the index can no
        // longer serve. This is the same [`Absorber::refold`] every absorb and
        // every open already calls, over the table this call just changed;
        // nothing about how the graph is rebuilt is touched here.
        //
        // The bitmaps go with it: they address **ordinals**, and dropping rows
        // renumbers the ordinal space, so `refold` clears them and the next
        // `reach_bitmaps()` builds them over the new numbering. Carrying them
        // across would be carrying an index into a different array.
        self.absorber.refold()?;
        Ok(dropped)
    }

    /// **The journal's half of a GC: retire every pack whose objects are now all
    /// dead, before a single row is dropped.**
    ///
    /// Returns the offsets retired.
    ///
    /// # Why this exists
    ///
    /// §13.12's `indexed` bit is derived on open as *extent in the journal, rows
    /// not in the index* ([`Absorber::adopt_journal`]). Dropping every row of a
    /// pack produces that state exactly, so without this call the next open
    /// re-queues the pack and re-absorbs the objects a GC just decided were dead.
    /// A **partly** dead pack keeps rows and was never affected; this is only
    /// about the all-dead case.
    ///
    /// # What it does not do
    ///
    /// It does not truncate `objects.pack`. The blob file is append-only and a
    /// pack in the middle of it cannot be cut out without moving every extent
    /// after it — which would invalidate every index row in the archive. The dead
    /// pack's bytes stay; what changes is that nothing will ever index them
    /// again. Reclaiming those bytes is a rewrite of the blob file, and it is not
    /// this function.
    ///
    /// An arm with no journal ([`FastWriter`](crate::archive_write::FastWriter))
    /// has nothing to retire and nothing that re-queues, so it returns empty.
    ///
    /// # Cost
    ///
    /// One [`ObjectReadStack::extents_with_rows`] scan plus one batch lookup of
    /// the live set. Both are already the shape a GC pays elsewhere, and both run
    /// once per `gc()`, not per pack.
    /// Where the journal's acked extents end right now — the GC's snapshot of
    /// "packs that existed when I started". A pack acked past this point during
    /// the GC belongs to a push in flight and is not the GC's to judge.
    pub(crate) fn acked_end(&self) -> Result<u64> {
        let Some(journal) = self.arms.writer.journal(&self.blobs) else {
            return Ok(u64::MAX);
        };
        if !journal.exists() {
            return Ok(0);
        }
        let rows = crate::archive_write::read_journal(&journal)?;
        Ok(crate::archive_write::acked_packs(&rows)
            .iter()
            .map(|(o, l)| o + l)
            .max()
            .unwrap_or(0))
    }

    /// Tombstone every acked pack that holds no live object — among the packs
    /// whose extent ends at or before `acked_end`, the GC's snapshot from
    /// [`acked_end`](Self::acked_end). A pack pushed after that snapshot has
    /// objects `live` never saw, and without the bound it would be retired for
    /// being unknown, which is how a GC would delete a push in flight.
    pub(crate) fn retire_dead_packs(
        &self,
        live: &std::collections::HashSet<String>,
        acked_end: u64,
    ) -> Result<Vec<u64>> {
        let Some(journal) = self.arms.writer.journal(&self.blobs) else {
            return Ok(Vec::new());
        };
        if !journal.exists() {
            return Ok(Vec::new());
        }
        let rows = crate::archive_write::read_journal(&journal)?;
        let packs: Vec<(u64, u64)> = crate::archive_write::acked_packs(&rows)
            .into_iter()
            .filter(|(o, l)| o + l <= acked_end)
            .collect();
        let already = crate::archive_write::retired_offsets(&rows);
        if packs.is_empty() {
            return Ok(Vec::new());
        }

        // Which packs hold any row at all right now. A pack with none is either
        // already retired or was never absorbed — neither is this call's
        // business, and calling the second one dead would lose it.
        let occupied = self.absorber.objects.extents_with_rows(&packs)?;

        // Which packs hold a row that survives. Placed by binary search over the
        // pack starts, the same way the scan above places a row.
        let mut order: Vec<usize> = (0..packs.len()).filter(|&i| packs[i].1 > 0).collect();
        order.sort_unstable_by_key(|&i| packs[i].0);
        let starts: Vec<u64> = order.iter().map(|&i| packs[i].0).collect();
        let live_oids: Vec<Vec<u8>> = live.iter().filter_map(|h| hex::decode(h).ok()).collect();
        let borrowed: Vec<&[u8]> = live_oids.iter().map(|o| o.as_slice()).collect();
        let mut has_live = vec![false; packs.len()];
        for (offset, _) in self
            .absorber
            .objects
            .extents_batch(&borrowed)
            .into_iter()
            .flatten()
        {
            let p = starts.partition_point(|&s| s <= offset);
            if p == 0 {
                continue;
            }
            let i = order[p - 1];
            if offset < packs[i].0 + packs[i].1 {
                has_live[i] = true;
            }
        }

        let dead: Vec<u64> = (0..packs.len())
            .filter(|&i| occupied[i] && !has_live[i] && !already.contains(&packs[i].0))
            .map(|i| packs[i].0)
            .collect();
        // Durable before the rows go. The one ordering this function has.
        crate::archive_write::retire_packs(&journal, &dead)?;
        Ok(dead)
    }

    /// **Write generation 0** at [`archive_path`](Self::archive_path), carrying
    /// the verbatim packs this store has acked plus `reserved`.
    ///
    /// The whole of the decision-making lives in
    /// [`seal_generation_zero`](crate::archive_write::seal_generation_zero); this
    /// is the three paths it needs, taken off the same fields the push path and
    /// the GC read, so a seal cannot address a different blob file or a different
    /// journal from the one that acked the packs.
    pub(crate) fn seal_archive(
        &self,
        reserved: Vec<ReservedSection>,
    ) -> Result<crate::archive_write::SealReport> {
        crate::archive_write::seal_generation_zero(
            &self.blobs,
            self.arms.writer.journal(&self.blobs).as_deref(),
            &self.archive,
            reserved,
        )
    }

    /// The sections a sealed archive carries: the ref log, the commit graph and
    /// the bitmaps.
    pub(crate) fn reserved_sections(&self) -> Result<Vec<ReservedSection>> {
        use znippy_common::{GUNNAR_GRAPH_MODULE, GUNNAR_REACH_MODULE};
        let mut out = vec![self.refs.seal_section()?];
        let d = self
            .absorber
            .derived
            .read()
            .map_err(|_| anyhow!("derived poisoned"))?;
        if !d.graph.is_empty() {
            out.push(ReservedSection::arrow(
                GUNNAR_GRAPH_MODULE,
                crate::graph::graph_schema(),
                vec![crate::graph::build_graph_batch(&d.graph)?],
            ));
        }
        drop(d);
        let reach = self.reach_bitmaps()?;
        if !reach.is_empty() {
            out.push(ReservedSection::arrow(
                GUNNAR_REACH_MODULE,
                crate::reach::reach_schema(),
                vec![crate::reach::build_reach_batch(&reach)?],
            ));
        }
        Ok(out)
    }
}

// ── the runtime selector ──────────────────────────────────────────────────────

/// **A [`GitStore`] whose index arm was chosen at run time.**
///
/// The [`ObjectIndex`] arm is a *type*, so a value can only choose it by naming
/// every monomorphisation. This enum is that list, and it is an enum rather than
/// a `Box<dyn GitOps>` for two reasons:
///
/// * a boxed trait object can only offer the twelve, and the arms differ in
///   things the twelve deliberately do not expose — how many Arrow bytes the
///   projection actually materialised, which writer is on the ack path. A bench
///   or an operator dump needs those, and a guard needs them to assert that the
///   selector selected **on applied output** rather than on a label;
/// * there is no allocation and no vtable: the `match` is one predictable branch
///   at the top of a call, and everything under it — the `stree` probe, the
///   Arrow gather, the redb tail — is the same fully static code
///   [`GitStore::<S>::open_with_arms`](GitStore::open_with_arms) produces,
///   because `S` is known inside each arm.
///
/// # What it costs, stated rather than hidden
///
/// One branch per [`GitOps`] call — **not per object**. `extents(&[1000 oids])`
/// is one branch and a thousand monomorphised lookups behind it. The binary
/// carries three copies of the store, which is the price of picking a type at
/// run time and there is no version of this that does not pay it.
///
/// A caller that knows its arm at compile time should **not** come through here:
/// [`GitStore::open`] and [`GitStore::open_with_arms`] hand back a concrete
/// store with no branch at all, and that includes every caller that wants the
/// default.
pub enum SelectedStore {
    OneTableFourColumns(GitStore<OneTableFourColumns>),
    FourTables(GitStore<crate::index_layout::FourTables>),
    PackedPayload(GitStore<crate::index_layout::PackedPayload>),
}

/// One expression, evaluated against whichever concrete store this is. The
/// delegation below is generated from it so there is no second copy of any
/// method body (LAW 5).
macro_rules! on_arm {
    ($self:ident, $s:ident => $body:expr) => {
        match $self {
            SelectedStore::OneTableFourColumns($s) => $body,
            SelectedStore::FourTables($s) => $body,
            SelectedStore::PackedPayload($s) => $body,
        }
    };
}

impl SelectedStore {
    /// The arms this store was built with.
    pub fn arms(&self) -> StoreConfig {
        on_arm!(self, s => s.arms())
    }

    /// **The explode band** — bytes held in each pool, the budget, and what has
    /// been evicted since this store was opened. `Admin.StorageInfo` and the
    /// dashboard's `explode 3.1G/8G` cell.
    pub fn explode_cache_use(&self) -> crate::exploded_cache::CacheUse {
        on_arm!(self, s => s.explode_cache_use())
    }

    /// **This repository's explode quota, set live.** What the control plane
    /// calls when an account's plan changes. It never refuses a read and never
    /// deletes on the caller's thread: over budget evicts at the next rotation,
    /// and an account at its limit still serves every object — from the pack,
    /// which is slower and never wrong.
    pub fn set_explode_budget(&self, bytes: u64) {
        on_arm!(self, s => s.set_explode_budget(bytes))
    }

    /// **`repo gc` reclaims the cache**: every lazy segment unlinked, the graph
    /// pool kept. Returns the bytes that left the filesystem.
    pub fn drop_explode_cache(&self) -> anyhow::Result<u64> {
        on_arm!(self, s => s.drop_explode_cache())
    }

    /// The selected writer's name, as it goes on a bench row.
    pub fn writer_name(&self) -> &'static str {
        on_arm!(self, s => s.writer_name())
    }

    /// What the selected writer's `append` promises.
    pub fn writer_durability(&self) -> &'static str {
        on_arm!(self, s => s.writer_durability())
    }

    /// **Arrow IPC bytes the selected index arm actually materialised.**
    ///
    /// The applied output that distinguishes one layout from another: a packed
    /// 25-byte column, four columns in one section and four independent
    /// sections are three different numbers for the same objects. This is what
    /// a guard reads to prove the selector selected, because a *name* would
    /// prove only that a name was copied.
    pub fn index_ipc_bytes(&self) -> usize {
        on_arm!(self, s => s.index().ipc_bytes())
    }

    /// **The name the built projection reports about itself** —
    /// `OneTableFourColumns`, `FourTables` or `PackedPayload`.
    ///
    /// The other half of the applied-output pair [`index_ipc_bytes`] starts:
    /// the byte count separates the arms once objects are in the store, and
    /// this separates them from the instant it is built, including on an empty
    /// store where all three materialise nothing. It is the value
    /// [`crate::arms::IndexArm::projection_name`] exists to be compared with —
    /// what the layout calls itself, never what the selector asked for — so a
    /// server logging it is stating what it built rather than repeating its own
    /// environment back.
    ///
    /// [`index_ipc_bytes`]: SelectedStore::index_ipc_bytes
    pub fn index_name(&self) -> &'static str {
        on_arm!(self, s => s.index().projection_name())
    }

    /// The oids a pushed extent introduced — [`GitStore::oids_in_extent`],
    /// delegated.
    ///
    /// Not one of the twelve (a pack's extent is a znippy concept), so it does
    /// not arrive with the [`GitOps`] impl below and has to be forwarded by
    /// hand. A server that reports the objects a push introduced needs it, and
    /// a server that picked its index arm at run time still needs it.
    pub fn oids_in_extent(&self, extent: Extent) -> Result<Vec<Vec<u8>>> {
        on_arm!(self, s => s.oids_in_extent(extent))
    }

    /// Objects in the `objects` table.
    pub fn object_count(&self) -> usize {
        on_arm!(self, s => s.object_count())
    }

    /// Block until the background drain has absorbed everything pushed.
    pub fn wait_indexed(&self) {
        on_arm!(self, s => s.wait_indexed())
    }

    /// Stop this store's index work; see [`GitStore::cancel_index`].
    pub fn cancel_index(&self) {
        on_arm!(self, s => s.cancel_index())
    }

    /// This store's index progress; see [`GitStore::index_progress`].
    pub fn index_progress(&self) -> crate::progress::Snapshot {
        on_arm!(self, s => s.index_progress())
    }

    /// Rebuild the projection, so the layout under test is what answers rather
    /// than the redb tail.
    pub fn rebuild_projection(&self) -> Result<()> {
        on_arm!(self, s => s.index().rebuild())
    }

    /// The twelfth method — inherent, not on [`GitOps`], because it returns
    /// Arrow `ReservedSection`s a gix backend has no analog for.
    pub fn seal(&self) -> Result<Vec<ReservedSection>> {
        on_arm!(self, s => s.seal())
    }
}

impl GitOps for SelectedStore {
    fn put(&self, pack: &[u8], refs: &[RefUpdate]) -> Result<TxId> {
        on_arm!(self, s => s.put(pack, refs))
    }
    fn put_pack(&self, bytes: &[u8]) -> Result<TxId> {
        on_arm!(self, s => s.put_pack(bytes))
    }
    // Delegated like every other method, and that is the point: without these
    // two lines a `SelectedStore` would silently inherit the trait's *default*
    // `put_pack_observed` — the one that publishes nothing — and every store
    // gunnar actually opens goes through this enum. The count would have been
    // implemented in `store.rs` and unreachable in production.
    fn put_pack_observed(
        &self,
        bytes: &[u8],
        progress: &dyn git_storage_trait::PackProgress,
    ) -> Result<TxId> {
        on_arm!(self, s => s.put_pack_observed(bytes, progress))
    }
    fn publishes_pack_progress(&self) -> bool {
        on_arm!(self, s => s.publishes_pack_progress())
    }
    fn put_refs(&self, updates: &[RefUpdate]) -> Result<TxId> {
        on_arm!(self, s => s.put_refs(updates))
    }
    fn get(&self, oid: Oid<'_>) -> Result<Option<Stored>> {
        on_arm!(self, s => s.get(oid))
    }
    fn has(&self, oid: Oid<'_>) -> Result<bool> {
        on_arm!(self, s => s.has(oid))
    }
    fn size(&self, oid: Oid<'_>) -> Result<Option<u64>> {
        on_arm!(self, s => s.size(oid))
    }
    fn extents(&self, oids: &[Oid<'_>]) -> Result<Vec<Option<Extent>>> {
        on_arm!(self, s => s.extents(oids))
    }
    fn refs(&self) -> Result<Vec<RefRow>> {
        on_arm!(self, s => s.refs())
    }
    fn update_ref(&self, name: &str, old: Option<Oid<'_>>, new: Option<Oid<'_>>) -> Result<TxId> {
        on_arm!(self, s => s.update_ref(name, old, new))
    }
    fn put_refs_cas(&self, edits: &[git_storage_trait::RefCas<'_>]) -> Result<TxId> {
        on_arm!(self, s => s.put_refs_cas(edits))
    }
    fn reachable(&self, want: &[Oid<'_>], have: &[Oid<'_>]) -> Result<Vec<Vec<u8>>> {
        on_arm!(self, s => s.reachable(want, have))
    }
    fn gc(&self) -> Result<GcReport> {
        on_arm!(self, s => s.gc())
    }
}

/// The reading contract, delegated the same way [`GitOps`] is.
///
/// Every method is one predictable branch over a monomorphised body — the same
/// arrangement, and the same cost argument, [`SelectedStore`] makes for the
/// eleven. It is here rather than in [`crate::serve`] only because the macro
/// that generates it lives in this module.
impl crate::serve::GitServe for SelectedStore {
    fn read(&self, oid: Oid<'_>) -> Result<Option<(crate::index_layout::ObjType, Vec<u8>)>> {
        on_arm!(self, s => crate::serve::GitServe::read(s, oid))
    }
    fn header(&self, oid: Oid<'_>) -> Result<Option<(crate::index_layout::ObjType, u64)>> {
        on_arm!(self, s => crate::serve::GitServe::header(s, oid))
    }
    fn sizes(&self, oids: &[Oid<'_>]) -> Result<Vec<Option<u64>>> {
        on_arm!(self, s => crate::serve::GitServe::sizes(s, oids))
    }
    fn index_now(&self) -> Result<usize> {
        on_arm!(self, s => crate::serve::GitServe::index_now(s))
    }
    fn head(&self) -> Result<Option<RefRow>> {
        on_arm!(self, s => crate::serve::GitServe::head(s))
    }
    fn set_head(&self, target: &str) -> Result<TxId> {
        on_arm!(self, s => crate::serve::GitServe::set_head(s, target))
    }
    /// `objects` is the **exact set to emit**, not tips to close over — the
    /// contract's word, and this forwarder uses it so that the name cannot drift
    /// back into `want` one arm at a time. See [`crate::serve::GitServe::emit_pack`].
    fn emit_pack(
        &self,
        objects: &[Oid<'_>],
        have: &[Oid<'_>],
        caps: &git_storage_trait::Caps,
        out: &mut dyn std::io::Write,
    ) -> Result<git_storage_trait::PackStats> {
        on_arm!(self, s => crate::serve::GitServe::emit_pack(s, objects, have, caps, out))
    }
    fn select(
        &self,
        want: &[Oid<'_>],
        have: &[Oid<'_>],
    ) -> Result<Option<git_storage_trait::ReachSet>> {
        on_arm!(self, s => crate::serve::GitServe::select(s, want, have))
    }
}

/// **Open a store with all three arms chosen at run time.**
///
/// The one place [`crate::arms::IndexArm`] — a value — is turned into `S` — a
/// type. See [`SelectedStore`] for what the resulting handle costs.
pub fn open_selected(
    root: &Path,
    account: &str,
    hash: GitHashKind,
    arms: StoreConfig,
) -> Result<SelectedStore> {
    use crate::arms::IndexArm;
    use crate::index_layout::{FourTables, PackedPayload};
    Ok(match arms.index {
        IndexArm::OneTableFourColumns => {
            SelectedStore::OneTableFourColumns(GitStore::<OneTableFourColumns>::open_with_arms(
                root, account, hash, arms,
            )?)
        }
        IndexArm::FourTables => SelectedStore::FourTables(GitStore::<FourTables>::open_with_arms(
            root, account, hash, arms,
        )?),
        IndexArm::PackedPayload => SelectedStore::PackedPayload(
            GitStore::<PackedPayload>::open_with_arms(root, account, hash, arms)?,
        ),
    })
}

/// **The env-driven front door**: read the three variables **once**, here, and
/// build the store they name.
///
/// This is the whole runtime selector a server or a bench needs — one call, one
/// triple of `getenv`s, and from then on the store holds built objects and reads
/// nothing. There is deliberately no per-operation lookup of any kind: a
/// `std::env::var` inside a serving loop would be one syscall per object served,
/// which is a real defect that was found and fixed in gunnar the day before this
/// was written. [`crate::arms::env_reads`] counts every read this crate makes so
/// that "once, at construction" is an assertion rather than a claim.
///
/// An unset variable takes the shipping default, so a process with a clean
/// environment gets exactly [`GitStore::open`]'s combination.
pub fn open_from_env(root: &Path, account: &str, hash: GitHashKind) -> Result<SelectedStore> {
    let arms = StoreConfig::from_env()?;
    open_selected(root, account, hash, arms)
}

impl<S: ObjectIndex> Absorber<S> {
    /// **One object's resolved content, and §14's table is what answers.**
    ///
    /// Two paths, and they are not interchangeable even though they return
    /// identical bytes:
    ///
    /// 1. **the exploded table** — one point lookup, no inflate, no delta chain;
    /// 2. **re-derived from the verbatim truth** — find which pack holds the
    ///    object, read the whole pack back, resolve it. Correct and slow, and it
    ///    exists because the table is droppable: a store whose table has been
    ///    deleted, or whose re-explosion has not caught up, must still answer.
    ///
    /// The counters are the only way to tell them apart. Identical bytes come
    /// back either way, so a byte comparison proves nothing about which path ran
    /// — that is the identity-value trap in its exact form, and it is why
    /// [`crate::exploded::ExplodedStats::rederived`] is bumped here rather than
    /// inferred.
    ///
    /// On the [`Absorber`] rather than on [`GitStore`] because that is where the
    /// absorb runs: the background worker has no store handle, and a base lookup
    /// that needed one would put the whole store behind the drain.
    fn resolved(&self, oid: &[u8]) -> Result<Option<(GitObjectKind, Vec<u8>)>> {
        Ok(self
            .resolved_costed(oid)?
            .map(|(kind, payload, _)| (kind, payload)))
    }

    /// [`Self::resolved`] and the bill. `None` for the cost means a pool
    /// answered and nothing was rebuilt.
    #[allow(clippy::type_complexity)]
    fn resolved_costed(
        &self,
        oid: &[u8],
    ) -> Result<Option<(GitObjectKind, Vec<u8>, Option<crate::resolve::ReadCost>)>> {
        // (1) §14's table.
        if let Some((kind, payload)) = self.exploded.content(oid)? {
            return Ok(Some((kind, payload, None)));
        }
        // (2) the verbatim truth, re-derived.
        let Some(row) = self.objects.lookup(oid) else {
            // (3) not indexed yet: the pending packs, read-only, on this
            // reader's own thread — never by waiting for the worker.
            //
            // **This arm is the ack path's trap and it is not the ack path's
            // fix.** `a_read_before_the_drain_is_served_from_the_pack_and_never_waits`
            // is the law here: a clone must be answered while the drain is
            // parked, so a read may not take the absorb gate. What must not
            // happen is the ACK arriving here, and it no longer does —
            // `GitServe::index_now` runs before the connectivity check, so by
            // the time the check reads there is nothing pending to scan. See
            // [`Absorber::index_pending_now`].
            if self.unindexed_packs() == 0 {
                return Ok(None);
            }
            self.exploded.note_rederived();
            let (_, content) = self.scan_pending(&[], Some(oid))?;
            // The pending scan resolves through a `PackWalk` rather than a
            // chain walk, so it does not produce a bill. `None` is honest here
            // and is not "it was free".
            return Ok(content.map(|(k, p)| (k, p, None)));
        };
        // ── ONE CHAIN, not one pack ─────────────────────────────────────
        //
        // The row's `offset` addresses the entry in the archive directly, so the
        // object is materialised by following its own delta chain out of the
        // mapping — `d` inflates and `d − 1` delta applications, nothing else
        // touched. This used to `read_extent` the WHOLE containing pack and
        // re-resolve it: for `torvalds/linux` an 8.12 GiB read and a 13.9 M
        // object resolve **per object served**, which is the cost that forced
        // the exploded tier to be built eagerly at push time — and that tier
        // MEASURED 141.7 GiB for an 8.12 GiB pack (17×). Lazy explode is only
        // affordable because of this function
        // (`ideas/lazy-explode-index-only-at-push.md`).
        //
        // It also does not care whether the containing pack has been ABSORBED:
        // the bytes were fsynced before the ack, so an object whose row is in
        // the index is readable the instant the row is. The pending-pack scan
        // below is for the window before the row exists at all.
        self.exploded.note_rederived();
        let snap = self.map.snapshot()?;
        let src = ArchiveWindow { abs: self, snap: &snap };
        let offset_of = |base: &[u8]| self.objects.lookup(base).map(|r| r.offset);
        match crate::resolve::materialize_at(
            &src,
            row.offset,
            self.hash.oid_len(),
            &offset_of,
            self,
        ) {
            Ok((kind, payload, cost)) => {
                self.keep_for_the_next_reader(oid, kind, &payload, cost);
                Ok(Some((kind, payload, Some(cost))))
            }
            Err(e) => {
                // A chain that cannot be followed out of the mapping is not a
                // wrong answer to hand back: fall through to the pending scan,
                // which re-derives from the pack the row came in on.
                //
                // **And if that finds nothing either, the ORIGINAL error is
                // what comes back — never `Ok(None)`.** The row says this store
                // holds the object; a failed read of an object we hold is a
                // store defect, and answering "absent" for it turned that defect
                // into a refusal of somebody else's push (lane AI, 2026-08-30 —
                // see `crate::resolve::MAX_DELTA_LINKS`). Absence is a fact the
                // index states, not a shape an error decays into.
                if self.unindexed_packs() == 0 {
                    return Err(e);
                }
                match self.scan_pending(&[], Some(oid))? {
                    (_, Some((k, p))) => Ok(Some((k, p, None))),
                    (_, None) => Err(e),
                }
            }
        }
    }
}

impl<S: ObjectIndex> Absorber<S> {
    /// **The write-back, and it is off the reader's path.**
    ///
    /// The reader has its bytes already — this buffers a copy into the lazy
    /// pool's newest segment (a `memcpy` under one lock, no I/O, no fsync, no
    /// eviction) and, once 4 MiB have accumulated, starts a thread to do the
    /// writing. That is Rickard's law from the design note in one function:
    /// *nobody waits*. A failure here is not the read's failure — the bytes
    /// were correct before the cache was consulted and are correct after it
    /// refuses — so it is counted and swallowed rather than propagated.
    ///
    /// **It does not always write.** A shallow, small object is cheaper to
    /// inflate again than to keep — a whole object is one `inflate` of one zlib
    /// stream at one offset — so the cache declines it and counts the read as
    /// `direct_reads` (`exploded_cache::worth_caching`). That is Rickard's
    /// refinement, 2026-08-30: *do not explode uniformly*. The reader that just
    /// paid the bill is the only thing that knows what it was, which is why the
    /// cost comes back out of [`crate::resolve::materialize_at`] rather than
    /// being predicted from an index column.
    ///
    /// Two readers racing on one oid is benign: identical bytes, and the table
    /// keeps the first row it filed under that key.
    fn keep_for_the_next_reader(
        &self,
        oid: &[u8],
        kind: GitObjectKind,
        payload: &[u8],
        cost: crate::resolve::ReadCost,
    ) {
        match self.exploded.write_back(oid, kind, payload, cost) {
            Ok(true) => self.exploded.kick(),
            Ok(false) => {}
            Err(e) => {
                tracing::debug!(
                    target: "znippy.git",
                    store = %self.label,
                    error = %e,
                    "the exploded cache would not take a write-back; the read is unaffected"
                );
            }
        }
    }
}

/// [`crate::reach::TreeSource`] over a live store — see
/// [`Absorber::tree_source`].
/// The oid a tag object points at, out of its header.
///
/// A tag object's payload begins `object <hex>\n` — that is the format, not a
/// heuristic, and it is the whole parse. Deliberately NOT reached for with a
/// git object library: this crate is a shipped archiver and `gix-object` is a
/// dev-dependency here, so pulling it into the read path to read one line would
/// put the pack pipeline back in an archive-only build (S-071).
fn tag_target_hex(payload: &[u8], oid_len: usize) -> Option<String> {
    let line = payload.split(|b| *b == b'\n').next()?;
    let rest = line.strip_prefix(b"object ")?;
    // Exactly the hash width this store uses, and hex. A shorter or longer
    // field is a malformed tag, and guessing at one would put a wrong oid into
    // a reachability answer — the one place a wrong answer is silent.
    if rest.len() != oid_len * 2 || !rest.iter().all(u8::is_ascii_hexdigit) {
        return None;
    }
    std::str::from_utf8(rest).ok().map(str::to_owned)
}

/// Add what a tag points at — and what THAT reaches — to a reachability union.
///
/// See the call site in `reachable_raw_with` for why this exists and why doing
/// it in the `want` loop is complete rather than partial.
///
/// A tag of a tag is legal git, so this follows the chain; `MAX_TAG_HOPS`
/// bounds it because a corrupt archive could point one at itself and a
/// reachability walk must terminate on bad data, not hang on it.
fn peel_tag_into<S: ObjectIndex>(
    abs: &Absorber<S>,
    tag_hex: &str,
    view: &crate::reach::ReachView<'_>,
    facts: &crate::reach::ObjectFacts<'_>,
    union: &mut roaring::RoaringBitmap,
) {
    const MAX_TAG_HOPS: usize = 8;
    let mut cursor = tag_hex.to_owned();
    for _ in 0..MAX_TAG_HOPS {
        let Ok(raw) = hex::decode(&cursor) else { return };
        // Not a tag, unreadable, or absent: nothing to peel. An unreadable
        // object makes the closure SHORT, and a short closure is refused
        // downstream by name (`missing necessary objects`) rather than served
        // as though it were complete — the same contract `TreesFromStore::tree`
        // documents.
        let Ok(Some((GitObjectKind::Tag, payload))) = abs.resolved(&raw) else { return };
        let Some(target) = tag_target_hex(&payload, facts.oid_len) else { return };
        if let Some(bm) = view.bitmap(target.as_str()) {
            *union |= bm;
            return;
        }
        if view.is_commit(target.as_str()) {
            crate::reach::accumulate(target.as_str(), view, facts, union);
            return;
        }
        let Some(o) = facts.ordinal.ordinal_of_hex(target.as_str()) else { return };
        union.insert(o);
        // A tag may point at a TREE, whose subtrees and blobs are then just as
        // necessary as a commit's would be. Inserting the tree alone would be
        // the same bug one level down.
        match abs.resolved(&hex::decode(&target).unwrap_or_default()) {
            Ok(Some((GitObjectKind::Tree, _))) => {
                crate::reach::accumulate_tree(target.as_str(), facts, union);
                return;
            }
            Ok(Some((GitObjectKind::Tag, _))) => cursor = target,
            // A blob, or unreadable: it is in, and it has no closure.
            _ => return,
        }
    }
}

struct TreesFromStore<'a, S: ObjectIndex> {
    abs: &'a Absorber<S>,
}

impl<S: ObjectIndex> crate::reach::TreeSource for TreesFromStore<'_, S> {
    fn tree(&self, oid_hex: &str) -> Option<std::borrow::Cow<'_, [u8]>> {
        let raw = hex::decode(oid_hex).ok()?;
        // A read that fails is `None`, which is what an object this archive
        // does not hold has always answered here — the walk stops at it. It is
        // NOT silently dropping an error that matters: an unreadable tree makes
        // the closure short, and a short closure is refused downstream by name
        // (`missing necessary objects`) rather than served as if it were
        // complete.
        match self.abs.resolved(&raw) {
            Ok(Some((GitObjectKind::Tree, payload))) => Some(std::borrow::Cow::Owned(payload)),
            // A blob, a tag, a gitlink, or absent: all "not a tree here".
            Ok(_) => None,
            Err(e) => {
                tracing::debug!(
                    target: "znippy.git",
                    store = %self.abs.label,
                    oid = oid_hex,
                    error = %e,
                    "a reachability walk could not read a tree; the walk stops there"
                );
                None
            }
        }
    }
}

/// The verbatim archive as [`crate::resolve::ArchiveBytes`]: **the mapping
/// where it reaches, a `pread` past its end.**
///
/// One snapshot is taken per read and sliced as many times as the chain is
/// deep, which is [`crate::archive_map::ArchiveMap::snapshot`]'s contract. The
/// `pread` arm is the one a push that landed after the snapshot takes; both
/// arms return the same bytes and differ only in what they cost.
struct ArchiveWindow<'a, S: ObjectIndex> {
    abs: &'a Absorber<S>,
    snap: &'a crate::archive_map::Mapped,
}

impl<S: ObjectIndex> crate::resolve::ArchiveBytes for ArchiveWindow<'_, S> {
    fn at(&self, at: u64, len: u64) -> Result<std::borrow::Cow<'_, [u8]>> {
        // A probe near the end of the archive legitimately gets fewer bytes
        // than it asked for, so the window is clamped rather than refused —
        // the parsers read a grammar, not a fixed width.
        let mapped = self.snap.len();
        if at < mapped {
            let have = (mapped - at).min(len);
            if let Some(b) = self.snap.get(at, have) {
                return Ok(std::borrow::Cow::Borrowed(b));
            }
        }
        let end = self
            .abs
            .reader
            .metadata()
            .map(|m| m.len())
            .unwrap_or(mapped);
        if at >= end {
            return Ok(std::borrow::Cow::Owned(Vec::new()));
        }
        let have = (end - at).min(len);
        Ok(std::borrow::Cow::Owned(self.abs.read_extent(at, have)?))
    }
}

/// A thin pack's external delta base, answered from §14's exploded table.
///
/// Before that table existed this had to read and re-resolve a whole pack per
/// base, and it deliberately cached nothing — because a cache here *would* have
/// been the undecided table. It is decided now (eager, 2026-08-08), so the cache
/// is the table and this is one point lookup.
///
/// **`None` means absent and `Err` means unreadable, and they are not the same
/// answer.** A base this store does not hold still comes back `Ok(None)` and
/// [`crate::resolve::ResolveError::missing_base`] refuses the pack by name.
///
/// # 🔴 This was `.ok().flatten()`
///
/// A store that HELD the base and could not reconstruct it answered exactly
/// like one that never had it, so the resolver blamed the pushed pack: *"this
/// repository genuinely does not have that object"*, about an object one index
/// lookup away. That sentence went to the client on the `ng` line and to the
/// operator in the log, and it named the wrong party — lane AI, 2026-08-30, 21
/// of 140 ordinary pushes. The error travels now.
impl<S: ObjectIndex> BaseSource for Absorber<S> {
    fn content(&self, oid: &[u8]) -> Result<Option<(GitObjectKind, Vec<u8>)>> {
        self.resolved(oid).with_context(|| {
            format!(
                "reading the delta base {} out of this store — it is not absent, it could not \
                 be reconstructed",
                hex::encode(oid)
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::archive_write::{read_journal, SafeWriter};
    use crate::object::GitObjectKind;
    use crate::store::tests::{one_blob_pack, corpus_pack, tmpdir};
    use std::collections::HashSet;
    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
    use std::time::{Duration, Instant};
    use znippy_zoomies::background::Job;
    use znippy_zoomies::gatling_forkjoin::gatling_for_each;

    fn loadavg() -> String {
        std::fs::read_to_string("/proc/loadavg")
            .unwrap_or_default()
            .split_whitespace()
            .take(3)
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// **The one representation answers exactly what the two it replaced did.**
    ///
    /// Before S-082 the store carried the ordinal space three times: `oids_raw`
    /// (flat bytes), `oids` (hex `Vec<String>`) and `ordinal`
    /// (`HashMap<String, u32>`). The last two are gone; oid ⇄ ordinal is now a
    /// slice and a binary search over `oids_raw`, through
    /// [`crate::reach::OrdinalSpace`]. This rebuilds those two OLD tables inline
    /// from the SAME `oids_raw` the store folded, and asserts the new lookups
    /// return the identical answer **for every oid in a real corpus** — the
    /// property that lets the field be removed without a server ever naming the
    /// wrong object in a pack, which no exit code could see.
    ///
    /// Seen RED by an off-by-one binary search (`Equal => Some(mid as u32 + 1)`
    /// in [`crate::reach::OrdinalSpace::ordinal_of_raw`]): every
    /// `ordinal_of_raw` / `ordinal_of_hex` below disagreed with the old
    /// `HashMap`, and the closure comparison at the end disagreed as well.
    #[test]
    fn the_one_ordinal_space_answers_what_the_two_it_replaced_did() {
        let dir = tmpdir("ordinal-space-one-representation");
        let (pack, rows) = corpus_pack();
        let store = GitStore::open(&dir, "rickard").unwrap();
        store.put_pack(&pack).unwrap();
        store.wait_indexed();

        let oid_len = store.hash_kind().oid_len();
        let raw = {
            let d = store.absorber.derived.read().unwrap();
            d.oids_raw.clone()
        };
        // The two tables `refold` used to build, rebuilt here from the same
        // bytes — this IS the "old" answer the new lookups must equal.
        let old_oids: Vec<String> = raw.chunks_exact(oid_len).map(hex::encode).collect();
        let old_ordinal: std::collections::HashMap<String, u32> = old_oids
            .iter()
            .enumerate()
            .map(|(i, o)| (o.clone(), i as u32))
            .collect();

        assert!(
            !old_oids.is_empty(),
            "the fixture pack ({} entries) folded to an EMPTY ordinal space, so every \
             comparison below would hold vacuously",
            rows.len()
        );
        assert_eq!(
            raw.len(),
            old_oids.len() * oid_len,
            "the raw ordinal space is {} bytes for {} oids of {oid_len} bytes",
            raw.len(),
            old_oids.len()
        );

        let space = crate::reach::OrdinalSpace::new(&raw, oid_len);
        assert_eq!(space.len(), old_oids.len(), "the space holds a different count");
        let mut checked = 0usize;
        for (o, h) in old_oids.iter().enumerate() {
            let want_ord = old_ordinal[h];
            // oid → ordinal, hex and raw, both == the old HashMap answer.
            assert_eq!(
                space.ordinal_of_hex(h),
                Some(want_ord),
                "ordinal_of_hex({h}) != the old HashMap answer {want_ord}"
            );
            let raw_oid = hex::decode(h).unwrap();
            assert_eq!(
                space.ordinal_of_raw(&raw_oid),
                Some(want_ord),
                "ordinal_of_raw disagrees with the old HashMap at {h}"
            );
            // ordinal → oid == the old hex Vec's slice, in both spellings.
            assert_eq!(
                space.oid(o as u32),
                Some(raw_oid.as_slice()),
                "oid({o}) != the old oids_raw slice"
            );
            assert_eq!(
                space.oid(o as u32).map(hex::encode).as_deref(),
                Some(h.as_str()),
                "oid({o}) hex != the old hex Vec entry {h}"
            );
            checked += 1;
        }
        assert_eq!(checked, old_oids.len());

        // A non-member answers None both ways, exactly as `HashMap::get` did for
        // an absent key — the binary search must not land on a neighbour.
        let absent = vec![0xffu8; oid_len];
        assert_eq!(space.ordinal_of_raw(&absent), None, "an absent oid resolved to an ordinal");
        assert_eq!(
            space.ordinal_of_hex(&hex::encode(&absent)),
            None,
            "an absent hex oid resolved to an ordinal"
        );
        // A wrong-width key is absent, not a panic.
        assert_eq!(space.ordinal_of_raw(&absent[..oid_len - 1]), None);
        assert_eq!(space.oid(old_oids.len() as u32), None, "an out-of-range ordinal named an oid");

        // And the answer built out of it: the raw closure IS the hex closure,
        // for a real tip rather than for an empty request.
        let tip = store
            .graph_snapshot()
            .into_iter()
            .max_by_key(|c| c.generation)
            .expect("a graph");
        let tip_raw = hex::decode(&tip.oid).unwrap();
        let flat = store.reachable_raw(&[&tip_raw], &[]).unwrap();
        let hexed = store.reachable_oids(&[&tip_raw], &[]).unwrap();
        assert!(
            flat.len() > 1,
            "the tip's closure is {} object(s) — too small to tell an ordering bug from a \
             coincidence",
            flat.len()
        );
        assert_eq!(
            flat.iter().map(hex::encode).collect::<Vec<_>>(),
            hexed,
            "the serving answer and the maintenance answer name different objects"
        );
        assert!(flat.contains(&tip_raw), "a closure without its own tip");
        eprintln!(
            "load {}; {} ordinals agree in both spellings, tip closure {} objects",
            loadavg(),
            checked,
            flat.len()
        );
    }

    /// Distinct commits in a resolved pack — what the graph must hold exactly
    /// once.
    fn commits_in(rows: &[crate::resolve::Resolved]) -> usize {
        rows.iter()
            .filter(|r| r.kind == GitObjectKind::Commit)
            .map(|r| r.oid.clone())
            .collect::<HashSet<Vec<u8>>>()
            .len()
    }

    /// **A push ends in object rows, and no read asked for them.**
    ///
    /// This is the seam this file wires: before it, `put` produced a *pack* row
    /// on the account indexer's channel and the object rows appeared only when
    /// somebody read (or called `absorb_pending` by hand). Here nothing is read
    /// between `put_pack` and `wait_indexed` — the only thing that could have
    /// built the rows is the drain.
    ///
    /// Asserted on applied output: one row per pack entry, every oid resolving
    /// out of the index, and the pack's indexed bit up. `absorb_failures` is
    /// asserted too, because a drain that absorbed nothing and recorded the
    /// failure would otherwise look like a drain that was never called.
    ///
    /// Seen RED by making the drain skip the absorber
    /// (`match absorber.as_deref()` → `match None::<&dyn ObjectAbsorb>` in
    /// `indexer::index_worker`): "the drain built no object rows: 0 of 2687".
    /// Restored.
    ///
    /// MEASURED on oden, 2026-08-08, release, three runs at **1-minute loadavg
    /// 5.77** (another tenant's work — oden is shared, so this is not an idle
    /// box): 2687 objects out of a 5 653 302-byte real pack absorbed in
    /// 161–164 ms, **16 421–16 673 object rows/s**, behind an ack of 29.1–29.4 ms.
    /// An earlier set at loadavg 16.94 gave 15 528 rows/s, so the figure moves
    /// about 7% with the box.
    ///
    /// Read it as a *floor* rather than as the engine's speed: the drain here is
    /// one pack, so it never uses more than one absorb, and the 162 ms covers a
    /// full inflate-and-delta-apply of every entry, a SHA-1 per object, the redb
    /// append and a whole-tail re-fold. Nothing about it has been optimised and
    /// no arm of it has been isolated. The rate is printed with the loadavg of
    /// its own run so a later number is never compared against a different
    /// machine state by accident.
    #[test]
    fn a_push_ends_in_object_rows_and_no_read_asked_for_them() {
        let dir = tmpdir("drain-rows");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let (pack, rows) = corpus_pack();

        let t = Instant::now();
        let tx = store.put_pack(&pack).unwrap();
        let ack = t.elapsed();
        let pack_id = tx.pack_id.expect("a pack push assigns an id");

        // Nothing is read here. The drain is the only thing that can move.
        store.wait_indexed();
        let drained = t.elapsed();

        assert_eq!(
            store.object_count(),
            rows.len(),
            "the drain built no object rows: {} of {}",
            store.object_count(),
            rows.len()
        );
        assert_eq!(store.unindexed_packs(), 0, "the bit is still clear");
        assert!(
            store.indexer().is_indexed(pack_id),
            "the pack's indexed bit is not up after the drain"
        );
        assert_eq!(
            store.indexer().absorb_failures(),
            0,
            "the drain recorded an absorb failure: {:?}",
            store.indexer().last_absorb_error()
        );

        // Every oid answers **out of the rows**, not out of a fallback: the
        // index is asked directly, so nothing can absorb behind this loop.
        for (i, r) in rows.iter().enumerate() {
            let row = store
                .index()
                .lookup(&r.oid)
                .unwrap_or_else(|| panic!("object {i} {} has no row", hex::encode(&r.oid)));
            assert_eq!(
                (row.offset, row.len),
                (tx.extent.unwrap().0 + r.offset, r.len)
            );
            assert_eq!(row.uncompressed_size, r.uncompressed_size);
        }
        assert_eq!(
            store.absorb_pending().unwrap(),
            0,
            "the drain left work for a read to do"
        );
        assert_eq!(
            store.commit_count(),
            commits_in(&rows),
            "the commit graph does not match the pack"
        );

        let secs = (drained - ack).as_secs_f64();
        eprintln!(
            "load {}; {} objects in {} bytes: ack {:.0} µs, drain {:.1} ms, {:.0} object rows/s",
            loadavg(),
            rows.len(),
            pack.len(),
            ack.as_secs_f64() * 1e6,
            (drained - ack).as_secs_f64() * 1e3,
            rows.len() as f64 / secs.max(1e-9),
        );
    }

    // ── the bit across a restart ─────────────────────────────────────────────

    /// Where the child of the kill guard finds its fixture and leaves its marker.
    const KILL_DIR: &str = "GUNNAR_KILL_MID_ABSORB_DIR";

    /// **The other half of [`a_store_reopened_after_a_kill_mid_absorb_requeues_the_pack`]:
    /// the process that dies.**
    ///
    /// It runs as a child of that test and it **aborts on purpose**, which is why
    /// it is `#[ignore]`d: `SIGABRT` from inside a test binary is a failing test
    /// run, and the point is for the *parent* to see the signal.
    ///
    /// The kill lands where it has to land — after `put_pack` has returned, so
    /// the bytes and the journal row are on the platter, and before any row is in
    /// the index, which the held absorb gate makes a **state** rather than a
    /// hope. Nothing is simulated: no injected error, no fault flag, no early
    /// return. The process is gone.
    #[test]
    #[ignore = "spawned by a_store_reopened_after_a_kill_mid_absorb_requeues_the_pack; it aborts on purpose"]
    fn the_child_that_dies_between_durable_bytes_and_indexed_rows() {
        let Ok(dir) = std::env::var(KILL_DIR) else {
            // Run by hand with `--ignored` and no fixture: there is nothing to
            // kill over, so do nothing rather than abort somebody's test run.
            return;
        };
        let dir = PathBuf::from(dir);
        let pack = std::fs::read(dir.join("fixture.pack")).expect("the parent's fixture");

        let store = GitStore::open(&dir, "rickard").expect("open");
        // The drain is parked in front of its absorb for as long as this lives,
        // so no row can land before the abort below.
        let _gate = store.hold_absorb_gate();
        let tx = store.put_pack(&pack).expect("the ack path");
        assert_eq!(tx.pack_id, Some(0), "a fresh archive starts at ordinal 0");
        assert_eq!(store.unindexed_packs(), 1, "the pack is not queued");
        assert_eq!(store.index().len(), 0, "a row landed before the kill");
        std::fs::write(dir.join("ready"), b"durable, not indexed").expect("marker");

        // Not `panic!`, not `exit`: the process stops here with a live gate, a
        // live worker and a live redb handle, which is what a machine that dies
        // mid-absorb leaves behind.
        std::process::abort();
    }

    /// **A store reopened over a pack that was still being absorbed re-queues
    /// it, answers correctly the whole way through, and gets its derived tables
    /// back.**
    ///
    /// The interruption is a **real** one: a child process is spawned, pushes the
    /// pack, and is killed by `SIGABRT` between "bytes durable" and "rows
    /// indexed". The parent then asserts what the kill left on disk — one journal
    /// row, the pack verbatim, **zero** index rows — before opening a store over
    /// it, so the recovery is being tested against the state it claims to
    /// recover from and not against a lucky one.
    ///
    /// Three things are then asserted, all on applied output:
    ///
    /// 1. **the pack is re-queued** — the account indexer of the *new* process
    ///    publishes ordinal 0, which it can only do for a job somebody submitted;
    /// 2. **a read is correct throughout** — `has` is asked the instant the store
    ///    is open, before any drain has been waited for, and must answer `true`;
    /// 3. **`commit_count()` and `reachable()` come back** — the derived tables
    ///    are rebuilt by the same absorb, so the graph holds exactly the pack's
    ///    commits and a tip's closure is non-empty.
    ///
    /// Seen RED by making `open_with` re-queue nothing (`absorber
    /// .adopt_journal(&acked)?` → an empty `Vec`, which is what this store did
    /// before this change): "a durable object read `absent` from a store reopened
    /// over the pack that holds it — the crash-recovery bit did not re-queue
    /// anything". Restored.
    ///
    /// Seen RED a second time by inverting the diff in
    /// [`Absorber::adopt_journal`] (`if absorbed` → `if !absorbed`), so a pack
    /// with **no** rows has its bit set and a pack with rows is re-queued: the
    /// same first assertion fires, because a set bit over an empty index is
    /// exactly the wrong answer a bloom filter's false positive would have
    /// produced — the read stops falling back and says `absent` about an object
    /// whose bytes are durable. Restored.
    ///
    /// **Why the assertions are not immediately after the reopen.** The trap the
    /// drain guards already record applies here too, mirrored: right after
    /// `GitStore::open` the drain may legitimately have finished the re-queued
    /// pack already, so `unindexed_packs() == 1` is not assertable and is not
    /// asserted. What *is* assertable at that instant is the answer to a read,
    /// which must be `true` whichever side of the drain it lands on — and that is
    /// exactly the property §13.12 promises.
    ///
    /// **And it still holds now that a `gc` can retire a pack's journal row.**
    /// The tombstone tells "indexed then garbage-collected" from "never
    /// indexed", and this pack is the second: nothing retired it, so it must
    /// still be re-queued. Seen RED by making `adopt_journal` treat *every* pack
    /// as retired (`retired.contains(&extent.0)` → `true`): "a durable object
    /// read `absent` from a store reopened over the pack that holds it — the
    /// crash-recovery bit did not re-queue anything". Restored.
    #[test]
    fn a_store_reopened_after_a_kill_mid_absorb_requeues_the_pack() {
        use std::os::unix::process::ExitStatusExt;

        let dir = tmpdir("kill-mid-absorb");
        let (pack, rows) = corpus_pack();
        std::fs::write(dir.join("fixture.pack"), &pack).unwrap();

        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "--ignored",
                "--nocapture",
                "git_ops::tests::the_child_that_dies_between_durable_bytes_and_indexed_rows",
            ])
            .env(KILL_DIR, &dir)
            .status()
            .expect("spawn the child that dies");
        assert_eq!(
            status.signal(),
            Some(6),
            "the child did not die by SIGABRT — it {status:?}, so nothing was interrupted"
        );
        assert!(
            dir.join("ready").exists(),
            "the child never reached the kill point"
        );

        // ── what the kill left on disk ───────────────────────────────────────
        let blobs = dir.join("objects.pack");
        let acked = read_journal(&SafeWriter::journal_path(&blobs)).unwrap();
        assert_eq!(
            acked.len(),
            1,
            "the pack's extent is not durable: {acked:?}"
        );
        assert_eq!(acked[0].1, pack.len() as u64);
        let on_disk = std::fs::read(&blobs).unwrap();
        assert_eq!(
            &on_disk[acked[0].0 as usize..(acked[0].0 + acked[0].1) as usize],
            &pack[..],
            "the verbatim bytes did not survive the kill"
        );
        {
            // Opened and dropped before the store takes redb's file lock.
            let tail = ObjectReadStack::<OneTableFourColumns>::open(
                &dir.join("objects.tail"),
                RebuildTriggers::default(),
                crate::arms::DEFAULT_REDB_CACHE_BYTES,
            )
            .unwrap();
            assert_eq!(
                tail.len(),
                0,
                "the kill landed after the rows were indexed, not between the bytes and the rows \
                 — this guard would then be testing nothing"
            );
        }

        // ── the reopen ───────────────────────────────────────────────────────
        let store = GitStore::open(&dir, "rickard").unwrap();
        assert!(
            store.has(&rows[0].oid).unwrap(),
            "a durable object read `absent` from a store reopened over the pack that holds it — \
             the crash-recovery bit did not re-queue anything"
        );

        store.wait_indexed();
        assert_eq!(
            store.object_count(),
            rows.len(),
            "the re-queued pack's objects never reached the index — left: {}, right: {}",
            store.object_count(),
            rows.len()
        );
        assert!(
            store.indexer().is_indexed(0),
            "the re-queued pack's indexed bit never went up in the new process"
        );
        assert_eq!(store.unindexed_packs(), 0);
        assert_eq!(store.absorb_pending().unwrap(), 0);
        for r in rows.iter().take(512) {
            let row = store
                .index()
                .lookup(&r.oid)
                .unwrap_or_else(|| panic!("{} has no row after recovery", hex::encode(&r.oid)));
            assert_eq!((row.offset, row.len), (acked[0].0 + r.offset, r.len));
        }

        // ── the derived tables, which were the second symptom ────────────────
        assert_eq!(
            store.commit_count(),
            commits_in(&rows),
            "the commit graph did not come back: {} of {}",
            store.commit_count(),
            commits_in(&rows)
        );
        let tip = store
            .graph_snapshot()
            .into_iter()
            .max_by_key(|c| c.generation)
            .expect("a graph");
        let tip_raw = hex::decode(&tip.oid).unwrap();
        let closure = store.reachable(&[&tip_raw], &[]).unwrap();
        assert!(
            !closure.is_empty(),
            "reachable() came back empty after the reopen"
        );
        assert!(closure.contains(&tip_raw));
        eprintln!(
            "load {}; killed mid-absorb: {} journal extent(s) recovered {} object rows, {} \
             commits, closure of the tip {} objects",
            loadavg(),
            acked.len(),
            store.object_count(),
            store.commit_count(),
            closure.len(),
        );
    }

    /// **A clean reopen re-queues nothing, and the next push gets a fresh
    /// ordinal.**
    ///
    /// The other side of the diff. A store whose pack was fully absorbed before
    /// it closed must come back with the bit **set**: re-absorbing would be a
    /// whole pack re-resolved for nothing, and — because the commit graph is a
    /// `Vec` — it is the same doubling the drain's own guard exists to prevent.
    ///
    /// "Re-queued nothing" is asserted deterministically rather than by a timing
    /// window: the account indexer in this process publishes a pack only for a
    /// job somebody submitted, so `is_indexed(0)` being **false** after
    /// `wait_indexed` is proof that open submitted none.
    ///
    /// The second half is the ordinal. Pack ids are the journal's row numbers, so
    /// a reopened store must resume after them. Asserted on applied output rather
    /// than on the id alone: the newly pushed pack's object has to be findable,
    /// and it is exactly what goes missing when a fresh pack is handed an
    /// absorbed pack's ordinal — `queue` skips it, the drain skips it, and its
    /// durable bytes are never indexed by anybody.
    ///
    /// Seen RED by making `Absorber::adopt_journal` treat every journal extent as
    /// unabsorbed (`let has_rows = vec![false; journal.len()]`): "a fully
    /// absorbed pack was re-queued on open — the diff is not exact".
    ///
    /// Seen RED a second time by `AtomicU64::new(packs_already_acked(...)?)` →
    /// `AtomicU64::new(0)` in `PushPath::with_absorber`: "a reopened store handed
    /// a fresh pack the ordinal of an absorbed one — left: Some(0), right:
    /// Some(1)". With that same edit **and the id assertion deleted**, the
    /// applied-output one goes too — "the second push's object never reached the
    /// index — its ordinal collided with an absorbed pack's, so every writer
    /// skipped it" — which is what says this guard is about the objects and not
    /// about a counter. Restored.
    #[test]
    fn a_clean_reopen_requeues_nothing_and_the_next_push_gets_a_fresh_ordinal() {
        let dir = tmpdir("clean-reopen");
        let (pack, rows) = corpus_pack();
        let (second, blob_oid) = one_blob_pack(b"a push that arrives after the restart");

        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
            assert_eq!(
                store.object_count(),
                rows.len(),
                "the first run did not index"
            );
        }

        let store = GitStore::open(&dir, "rickard").unwrap();
        store.wait_indexed();
        assert!(
            !store.indexer().is_indexed(0),
            "a fully absorbed pack was re-queued on open — the diff is not exact"
        );
        assert_eq!(store.unindexed_packs(), 0);
        assert_eq!(
            store.absorb_pending().unwrap(),
            0,
            "the reopen left index work"
        );
        assert_eq!(
            store.object_count(),
            rows.len(),
            "the reopened store lost rows"
        );
        assert!(store.has(&rows[0].oid).unwrap());

        let tx = store.put_pack(&second).unwrap();
        assert_eq!(
            tx.pack_id,
            Some(1),
            "a reopened store handed a fresh pack the ordinal of an absorbed one"
        );
        store.wait_indexed();
        assert!(
            store.has(&blob_oid).unwrap(),
            "the second push's object never reached the index — its ordinal collided with an \
             absorbed pack's, so every writer skipped it"
        );
        assert_eq!(store.object_count(), rows.len() + 1);
        assert!(store.indexer().is_indexed(1));
        // And the journal is a log: both packs' extents are in it, in order.
        let acked = read_journal(&SafeWriter::journal_path(store.blobs_path())).unwrap();
        assert_eq!(
            acked.len(),
            2,
            "the reopen truncated the journal: {acked:?}"
        );
        assert_eq!(acked[1], tx.extent.unwrap());
    }

    /// **What the derive-on-open diff costs at a realistic pack count.**
    ///
    /// Not a guard — a measurement, with two assertions on it that keep it from
    /// measuring the wrong thing: every absorbed pack must come back `true`, and
    /// the one pack that has no rows must come back `false`.
    ///
    /// Both cases are timed because they are different algorithms in practice.
    /// The **clean reopen** — every pack absorbed — terminates as soon as each
    /// extent has been hit once, which happens after a few rows per pack because
    /// the tail is in oid order and an oid says nothing about which pack its
    /// object came from. The **crash** case has one pack with no rows at all, and
    /// proving an absence means reading the tail to the end.
    ///
    /// MEASURED on oden 2026-08-08, release, 1000 real pushed packs / 3686 object
    /// rows, 1-minute loadavg 2.77: **0.38 ms** clean and 0.39 ms with one pack
    /// un-absorbed (0.40 / 0.39 ms at loadavg 13.06, so the figure barely moves
    /// with the box). At this row count the two cases are the same, because a
    /// 3686-row tail is scanned to the end faster than the early exit saves
    /// anything; they diverge with the object count, and the table on
    /// [`ObjectReadStack::extents_with_rows`] carries that at a million rows
    /// (0.74 ms against 109 ms).
    ///
    /// The printed line carries the loadavg of its own run, the pack count and
    /// the row count, because none of the three is comparable across machines or
    /// across a busy box.
    #[test]
    fn the_derive_on_open_diff_costs_milliseconds_at_a_realistic_pack_count() {
        const PACKS: usize = 1000;
        let dir = tmpdir("diff-cost");
        let (real, rows) = corpus_pack();

        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&real).unwrap();
            for i in 0..PACKS - 1 {
                let (p, _) = one_blob_pack(format!("pack number {i}").as_bytes());
                store.put_pack(&p).unwrap();
            }
            store.wait_indexed();
            assert_eq!(
                store.object_count(),
                rows.len() + PACKS - 1,
                "the fixture did not absorb"
            );
        }

        let acked = read_journal(&SafeWriter::journal_path(&dir.join("objects.pack"))).unwrap();
        assert_eq!(acked.len(), PACKS, "one journal row per pack");
        // The tail on its own, so what is timed is the diff rather than redb's
        // open and the projection build that a store's open also pays for.
        let tail = ObjectReadStack::<OneTableFourColumns>::open(
            &dir.join("objects.tail"),
            RebuildTriggers::default(),
            crate::arms::DEFAULT_REDB_CACHE_BYTES,
        )
        .unwrap();

        let t = Instant::now();
        let hit = tail.extents_with_rows(&acked).unwrap();
        let clean = t.elapsed();
        assert!(
            hit.iter().all(|&h| h),
            "an absorbed pack was reported unabsorbed"
        );

        // One pack in flight when the machine died: durable bytes, no rows.
        let mut in_flight = acked.clone();
        let end = acked[PACKS - 1].0 + acked[PACKS - 1].1;
        in_flight.push((end, 4096));
        let t = Instant::now();
        let hit = tail.extents_with_rows(&in_flight).unwrap();
        let crashed = t.elapsed();
        assert_eq!(
            hit.iter().filter(|h| !**h).count(),
            1,
            "the pack with no rows is not the only one reported unabsorbed"
        );

        eprintln!(
            "load {}; {PACKS} packs / {} object rows: derive-on-open diff {:.2} ms clean \
             (early exit), {:.2} ms with one pack un-absorbed (full tail scan)",
            loadavg(),
            tail.len(),
            clean.as_secs_f64() * 1e3,
            crashed.as_secs_f64() * 1e3,
        );
    }

    /// **The bit is a bitset over dense ordinals, and one bit is one pack.**
    ///
    /// Ordinals that straddle word boundaries (63, 64, 65) are the whole point:
    /// a shift that ignores the word split, or a word index that does not, sets
    /// a neighbour's bit — and a neighbour's bit set means a durable pack is
    /// declared absorbed with no rows behind it.
    ///
    /// Seen RED by `>> (i % 64) & 1` → `>> (i % 63) & 1` in
    /// `PackState::is_absorbed`: "the bit for ordinal 64 did not go up". Restored.
    ///
    /// Seen RED a second time by `if self.extent[i].is_none()` → `if
    /// self.extent[i].is_none() || true` in `PackState::note`, i.e. letting a
    /// re-queue of a pack that is already recorded count as new work — which is
    /// the race the ack path really produces, since the drain can absorb before
    /// `queue` runs: "an absorbed pack was queued again — left: 6, right: 5".
    /// Restored.
    #[test]
    fn the_indexed_bit_is_a_bitset_over_dense_pack_ordinals() {
        let ids = [0u64, 1, 63, 64, 65, 4095];
        let mut s = PackState::default();
        for id in ids {
            s.note(id, (id * 4096 + 12, 4096));
        }
        assert_eq!(s.unabsorbed, ids.len());
        assert!(
            ids.iter().all(|&i| !s.is_absorbed(i)),
            "a bit is up already"
        );

        s.mark_absorbed(64, (64 * 4096 + 12, 4096));
        assert!(s.is_absorbed(64), "the bit for ordinal 64 did not go up");
        for other in [0u64, 1, 63, 65, 4095] {
            assert!(
                !s.is_absorbed(other),
                "setting ordinal 64 also set ordinal {other} — one bit spilled onto a neighbour"
            );
        }
        assert_eq!(s.unabsorbed, ids.len() - 1);
        assert_eq!(
            s.pending().iter().map(|p| p.pack_id).collect::<Vec<_>>(),
            vec![0, 1, 63, 65, 4095],
            "the pending list is not the clear bits"
        );
        assert_eq!(
            s.pending()[0],
            PendingPack {
                pack_id: 0,
                offset: 12,
                len: 4096,
                resumed: true,
            },
            "a pending pack lost the extent it must be absorbed from"
        );

        // Both writers are idempotent, because both of them race.
        s.mark_absorbed(64, (64 * 4096 + 12, 4096));
        s.note(64, (64 * 4096 + 12, 4096));
        assert!(s.is_absorbed(64));
        assert_eq!(
            s.unabsorbed,
            ids.len() - 1,
            "an absorbed pack was queued again"
        );

        // One bit per pack, and that is the whole cost: 4096 ordinals is 64
        // words. A hash set of the same ordinals is an order of magnitude more,
        // and a bloom would be smaller and wrong.
        assert_eq!(s.words.len(), 64);
        assert_eq!(s.words.len() * 8, 512, "4096 packs is 512 bytes of bits");
    }

    /// **A read that arrives before the drain is served from the pack, on its
    /// own thread, and never waits for the worker.**
    ///
    /// Rickard's rule, 2026-08-30: *nobody waits on the indexer.* Until then
    /// this test asserted the opposite — that a read parked behind the absorb
    /// gate stayed unanswered until the drain released it, which on a kernel
    /// pack is hours, and under the memory watchdog is *as long as the box is
    /// short*. Now the gate is the absorbers' and only the absorbers': the read
    /// finds no row, sees a pending pack, and resolves that pack read-only
    /// from the mmapped bytes for the one oid it wants
    /// (`Absorber::scan_pending`). The drain is still parked, the index is
    /// still empty, and the answer is **present** — from the verbatim truth.
    ///
    /// Seen RED by making `lookup_never_wait` return `Ok(None)` when the index
    /// misses: "a read with the drain parked answered absent for a durable
    /// object". And by putting `self.gate.lock()` back in front of it: the
    /// 2-second bound below trips with the reader still parked.
    #[test]
    fn a_read_before_the_drain_is_served_from_the_pack_and_never_waits() {
        let dir = tmpdir("drain-before");
        let store = Arc::new(GitStore::open(&dir, "rickard").unwrap());
        let (pack, rows) = corpus_pack();
        let (second, blob_oid) = one_blob_pack(b"a second push while the drain is parked");

        // The drain is parked here, before it can absorb anything.
        let gate = store.hold_absorb_gate();
        let tx = store.put_pack(&pack).unwrap();
        let pack_id = tx.pack_id.unwrap();
        assert_eq!(store.unindexed_packs(), 1, "the pack is not queued");
        assert_eq!(store.index().len(), 0, "the index already holds rows");
        assert!(!store.indexer().is_indexed(pack_id), "the bit is already up");

        // (1) a second push does not wait either: the ack path never meets the gate.
        let t = Instant::now();
        let tx2 = store.put_pack(&second).unwrap();
        assert_eq!(tx2.pack_id, Some(pack_id + 1));
        assert!(t.elapsed() < Duration::from_secs(2), "the push waited on the parked drain");

        // (2) reads into exactly that state: present, from the pack, bounded.
        let oid = rows[0].oid.clone();
        let last = rows[rows.len() - 1].oid.clone();
        let t = Instant::now();
        assert!(store.has(&oid).unwrap(), "a read with the drain parked answered absent for a durable object");
        assert!(store.has(&last).unwrap(), "the last object of the pack answered absent");
        assert!(store.has(&blob_oid).unwrap(), "the second (still pending) pack's object answered absent");
        let (kind, body) = store.content(&blob_oid).unwrap().expect("content from the pending pack");
        assert_eq!(kind, GitObjectKind::Blob);
        assert_eq!(body, b"a second push while the drain is parked");
        let stored = store.get(&oid).unwrap().expect("get from the pending pack");
        assert_eq!(stored.extent.0, rows[0].offset + tx.extent.unwrap().0);
        assert_eq!(
            store.size(&last).unwrap(),
            Some(rows[rows.len() - 1].uncompressed_size),
            "size from the pending pack"
        );
        let absent = vec![0xEEu8; 20];
        assert!(!store.has(&absent).unwrap(), "an oid in no pack must still be absent");
        let elapsed = t.elapsed();
        assert!(elapsed < Duration::from_secs(20), "reads took {elapsed:?} with the drain parked");
        // The drain is STILL parked and the index STILL empty: nothing above
        // absorbed anything, and nothing waited.
        assert_eq!(store.index().len(), 0, "a read absorbed the pack behind the parked gate");
        assert!(!store.indexer().is_indexed(pack_id));
        assert_eq!(store.unindexed_packs(), 2);
        eprintln!("{} reads served from two pending packs with the drain parked, in {elapsed:?}", 6);

        // (3) a whole-graph request is refused by name, not waited on.
        let err = store.reachable(&[oid.as_slice()], &[]).unwrap_err();
        assert!(err.to_string().contains("index in progress"), "{err:#}");

        drop(gate);
        // And afterwards it is served from the rows.
        store.wait_indexed();
        assert_eq!(store.unindexed_packs(), 0);
        assert!(store.indexer().is_indexed(pack_id));
        assert_eq!(store.index().len(), rows.len() + 1);
        assert_eq!(store.absorb_pending().unwrap(), 0);
        for r in rows.iter().take(256) {
            assert!(
                store.index().lookup(&r.oid).is_some(),
                "{} is not in the rows after the drain",
                hex::encode(&r.oid)
            );
        }
        assert!(store.reachable(&[oid.as_slice()], &[]).is_ok(), "reachable after the drain");
    }

    /// **The memory watchdog pauses the indexer worker and nobody else.**
    ///
    /// A fake `/proc/meminfo` under the floor is put under the process-wide
    /// watchdog; the worker parks in front of its batch (`index_worker`'s
    /// pre-batch check) and stays parked. Meanwhile a push is acked, every
    /// kind of read answers from the pack, and the progress snapshot returns —
    /// all bounded, none of them behind the pause. Then the fake is raised,
    /// the worker resumes, and the pack is indexed normally.
    ///
    /// Seen RED with the pre-batch check taking the absorb gate before pausing
    /// (the reads' scan does not need the gate, but `absorb_pending`-based
    /// reads did): every read parked for the length of the pause.
    #[test]
    fn a_paused_indexer_blocks_no_push_and_no_read() {
        let dir = tmpdir("paused-indexer");
        let meminfo = dir.join("meminfo");
        let write = |avail_kib: u64| {
            std::fs::write(&meminfo, format!("MemTotal:       16000000 kB\nMemAvailable:   {avail_kib} kB\n"))
                .unwrap()
        };
        write(1_000_000);
        let dog = Arc::new(crate::memguard::MemWatchdog::with(
            &meminfo,
            3_200_000 * 1024,
            Duration::from_millis(10),
        ));
        let store = Arc::new(GitStore::open(&dir, "rickard").unwrap());
        // This store's worker only: every other store in the process keeps
        // the real watchdog.
        store.set_mem_watchdog(dog.clone());
        let (pack, rows) = corpus_pack();
        let (second, blob_oid) = one_blob_pack(b"pushed while the indexer is paused");

        let t_push = Instant::now();
        let tx = store.put_pack(&pack).unwrap();
        let pack_id = tx.pack_id.unwrap();
        // Give the worker time to reach its pre-batch check and park.
        let mut parked = false;
        for _ in 0..200 {
            if dog.is_paused() {
                parked = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(parked, "the worker never paused under a meminfo 1 GB < 3.2 GB");
        assert!(!store.indexer().is_indexed(pack_id), "indexed while paused");
        assert_eq!(store.index().len(), 0);

        // The ack path: a push while paused.
        let tx2 = store.put_pack(&second).unwrap();
        assert_eq!(tx2.pack_id, Some(pack_id + 1));
        assert!(t_push.elapsed() < Duration::from_secs(5), "a push waited on the paused worker");

        // Reads while paused: present, from the pack.
        let t = Instant::now();
        assert!(store.has(&rows[0].oid).unwrap());
        assert!(store.has(&blob_oid).unwrap());
        let (kind, body) = store.content(&blob_oid).unwrap().unwrap();
        assert_eq!((kind, body.as_slice()), (GitObjectKind::Blob, &b"pushed while the indexer is paused"[..]));
        assert_eq!(
            store.extents(&[rows[0].oid.as_slice(), rows[1].oid.as_slice(), blob_oid.as_slice()])
                .unwrap()
                .iter()
                .filter(|e| e.is_some())
                .count(),
            3,
            "the batch path answered absent while paused"
        );
        assert!(t.elapsed() < Duration::from_secs(20), "reads waited on the paused worker");
        // The progress row: information, never a gate.
        let snap = store.index_progress();
        assert_eq!(snap.root, store.root().display().to_string());
        assert!(dog.is_paused(), "the worker resumed on its own — the fake still says 1 GB");
        assert!(!store.indexer().is_indexed(pack_id), "indexed while still paused");

        // A whole-graph request while the worker is paused: the gate is free
        // (a paused worker holds nothing), so the READER absorbs the pending
        // packs on its own thread and answers — the worker is still parked.
        let reach = store.reachable(&[rows[0].oid.as_slice()], &[]).unwrap();
        assert!(!reach.is_empty());
        assert_eq!(store.unindexed_packs(), 0, "the reader did not absorb for itself");
        assert!(dog.is_paused(), "the worker is still parked; the reader did the work");
        assert_eq!(store.index().len(), rows.len() + 1);

        // Memory comes back: the worker resumes, finds nothing to do, and the
        // bits go up through the ordinary drain.
        write(9_000_000);
        store.wait_indexed();
        assert!(store.indexer().is_indexed(pack_id));
        assert!(store.indexer().is_indexed(pack_id + 1));
        assert_eq!(dog.pauses(), 1, "one pause, one resume");
        assert!(!dog.is_paused());
    }

    /// **The bit is cleared after the rows go in, never before.**
    ///
    /// The ordering inside `absorb_gated` is the whole reason a read cannot be
    /// told "absent" while the drain is running, and the only way to see it is to
    /// read *during* one. Four gatling workers (LAW 3 — never rayon, and never a
    /// raw thread pool) hammer `has` over the pack's oids from the moment
    /// `put_pack` returns until the pack's bit is up.
    ///
    /// Asserted on applied output: not one of those reads may answer absent for
    /// an object whose bytes are already durable.
    ///
    /// Seen RED by clearing the bit *before* absorbing (a
    /// `s.pending.retain(|p| p.pack_id != job.pack_id)` added in `absorb_gated`
    /// above the `self.absorb_one(job)` call): "4 reader(s) were told a durable
    /// object was absent — **32 865 593** absent answers over 2687 objects".
    /// Restored. The count is that large because the readers spin until the bit
    /// goes up and, with the bit cleared first, every pass over the sample missed
    /// for the whole length of the absorb.
    ///
    /// The honest limit: this is a race, so a green run proves the window was not
    /// hit, not that no window exists. That is why the printed line carries how
    /// many of the reads actually landed while the pack was still un-indexed —
    /// **a run where that number is 0 proved nothing**, and it is reported rather
    /// than asserted because forcing it would mean pausing the drain, which is
    /// the one thing this test must not do. MEASURED 2026-08-08 on oden at
    /// loadavg 16.94: 336 of 336 reads landed early.
    #[test]
    fn no_read_is_told_absent_while_the_drain_is_running() {
        let dir = tmpdir("drain-during");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let (pack, rows) = corpus_pack();
        let oids: Vec<&[u8]> = rows.iter().map(|r| r.oid.as_slice()).collect();

        let tx = store.put_pack(&pack).unwrap();
        let pack_id = tx.pack_id.unwrap();

        let early = AtomicU64::new(0);
        let absent = AtomicU64::new(0);
        let reads = AtomicU64::new(0);
        let workers = 4usize;
        gatling_for_each(workers, workers, |w| loop {
            let still_pending = store.unindexed_packs() > 0;
            for oid in oids.iter().skip(w).step_by(workers * 8) {
                if still_pending {
                    early.fetch_add(1, AtomicOrdering::Relaxed);
                }
                reads.fetch_add(1, AtomicOrdering::Relaxed);
                if !store.has(oid).unwrap() {
                    absent.fetch_add(1, AtomicOrdering::Relaxed);
                }
            }
            if store.indexer().is_indexed(pack_id) {
                break;
            }
        });

        let absent = absent.load(AtomicOrdering::Acquire);
        assert_eq!(
            absent,
            0,
            "{workers} reader(s) were told a durable object was absent — {absent} absent answers \
             over {} objects",
            rows.len()
        );
        assert_eq!(store.object_count(), rows.len());
        eprintln!(
            "load {}; {} reads across {workers} gatling workers, {} of them while the pack was \
             still un-indexed",
            loadavg(),
            reads.load(AtomicOrdering::Acquire),
            early.load(AtomicOrdering::Acquire),
        );
    }

    /// **One pack is absorbed once, whichever of the two callers gets there
    /// first.**
    ///
    /// Both callers are made to attempt it, deterministically: with the gate
    /// held, the drain is parked inside `ObjectAbsorb::absorb` and a reader is
    /// parked inside `absorb_pending`, both past their own early exits. Releasing
    /// the gate lets exactly one do the work; the other must take the skip.
    ///
    /// The observable is the **commit graph**, not the object table:
    /// `ObjectReadStack::append` is keyed by oid and would swallow a second
    /// identical row, but the graph is a `Vec` and a second absorb pushes every
    /// commit into it again — which silently doubles the fold every reachability
    /// bitmap is built from.
    ///
    /// Seen RED by disabling the `s.absorbed.contains(&job.pack_id)` skip in
    /// `absorb_gated`: "the commit graph carries **1102** commits, the pack has
    /// **551**" — exactly double, both callers having done the whole fold.
    /// Restored.
    #[test]
    fn a_pack_is_absorbed_once_even_when_both_callers_race_for_it() {
        let dir = tmpdir("drain-once");
        let store = Arc::new(GitStore::open(&dir, "rickard").unwrap());
        let (pack, rows) = corpus_pack();

        let gate = store.hold_absorb_gate();
        store.put_pack(&pack).unwrap();

        let s = store.clone();
        let reader = Job::spawn(move || s.absorb_pending().unwrap());
        // Both are now blocked on the gate: the drain inside `absorb`, the reader
        // inside `absorb_pending`, each having already decided there is work.
        std::thread::sleep(Duration::from_millis(100));
        drop(gate);

        let by_read = reader.join().unwrap();
        store.wait_indexed();

        assert_eq!(
            store.commit_count(),
            commits_in(&rows),
            "the commit graph carries {} commits, the pack has {}",
            store.commit_count(),
            commits_in(&rows)
        );
        assert_eq!(store.object_count(), rows.len());
        assert_eq!(store.unindexed_packs(), 0);
        eprintln!(
            "load {}; the read absorbed {by_read} pack(s), the drain absorbed the rest",
            loadavg()
        );
    }

    // ── §14's exploded table ─────────────────────────────────────────────────

    /// **A push produces an exploded row for every object in the pack, and each
    /// one hashes back to its own oid.**
    ///
    /// Eager, decided 2026-08-08: no threshold, no size cap, no type skipped —
    /// so the row count is the *object* count and not some subset of it. Nothing
    /// is read between `put_pack` and `wait_indexed`, so the only thing that
    /// could have built the rows is the background drain, which is the half of
    /// §14 that says "built by the same background indexer".
    ///
    /// The assertion is applied output in its strongest available form: every
    /// object's content is read back out of the table, re-serialised canonically
    /// and **re-hashed**, and the hash has to be the oid it was filed under. A
    /// row count alone could be satisfied by 2687 rows of the wrong bytes; a
    /// re-hash cannot.
    ///
    /// Seen RED by deleting the `sink.explode(&oid, kind, &payload)?` call in
    /// `resolve::resolve_walked`: "the drain built no exploded rows: 0 of 2687".
    /// Restored.
    ///
    /// Seen RED a second time by making the sink skip blobs in
    /// `ExplodedTable::explode` (`if kind == GitObjectKind::Blob { return Ok(()) }`
    /// at the top — which is what a *lazy* or size-capped table would look like
    /// from here): "the drain built no exploded rows: 1420 of 2687". Restored,
    /// because §14's open question was closed EAGER and disk is explicitly not a
    /// consideration — and because the 1267 rows that edit removes are exactly
    /// the blobs a content read wants most.
    #[test]
    fn a_push_produces_an_exploded_row_for_every_object_in_the_pack() {
        let dir = tmpdir("exploded-every-object");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let (pack, rows) = corpus_pack();

        let t = Instant::now();
        store.put_pack(&pack).unwrap();
        let ack = t.elapsed();
        store.wait_indexed();
        // **Drain, printed beside ack**, because the two answer different
        // questions and only one of them was ever in doubt. Ack is unchanged by
        // construction — nothing on it touches this table. Drain is where the
        // eager resolve and the sink both live, and it is the column redb's
        // 2026-08-08 measurement recorded as 316.2–329.8 ms against 166.7–168.6
        // ms with the sink stubbed out. Without it here, "did the medium buy
        // anything but disk" has no answer in this repository.
        let drain = t.elapsed();

        let distinct: HashSet<Vec<u8>> = rows.iter().map(|r| r.oid.clone()).collect();
        let stats = store.exploded_stats();
        // **The push explodes the GRAPH, not the content.** Under the shipped
        // policy the drain writes commits and trees and leaves blobs in the
        // pack; the assertion is therefore two-sided, because "some rows" would
        // pass on a table that wrote one row and on one that wrote all of them,
        // and it is exactly the second that costs 17× the pack.
        let graph_rows = store.exploded_of_kind(GitObjectKind::Commit).unwrap().len();
        assert_eq!(
            store.exploded_eager_rows().unwrap(),
            graph_rows as u64,
            "the drain wrote {} eager rows and there are {} commits — the eager pool \
             holds something other than the graph",
            store.exploded_eager_rows().unwrap(),
            graph_rows
        );
        assert!(
            stats.rows > 0 && stats.rows < distinct.len() as u64,
            "the eager pool holds {} of {} objects; lazy explode means neither 0 \
             (the graph would be blind) nor all of them (that is the 22.4x tier)",
            stats.rows,
            distinct.len()
        );

        // Every one of them, re-hashed. Bytes that came back wrong cannot pass.
        let hash = store.hash_kind();
        let mut checked = 0usize;
        for oid in &distinct {
            let (kind, payload) = store
                .content(oid)
                .unwrap()
                .unwrap_or_else(|| panic!("{} has no exploded row", hex::encode(oid)));
            let rehashed = hash.oid_of(&crate::object::canonical(kind, &payload));
            assert_eq!(
                &rehashed,
                oid,
                "the exploded row filed under {} contains an object that hashes to {}",
                hex::encode(oid),
                hex::encode(&rehashed)
            );
            checked += 1;
        }
        assert_eq!(checked, distinct.len());
        // **Every object came back byte-correct**, and the ones the eager pool
        // does not hold came back by inflating their own delta chain out of the
        // mapped pack ([`crate::resolve::materialize_at`]). So the re-derivation
        // count is the blob count and not zero — asserting zero here is what a
        // test written for the eager tier does, and it would now be asserting
        // that lazy explode is off.
        let after_reads = store.exploded_stats();
        assert!(
            after_reads.rederived > 0,
            "no read re-derived anything, so either every object is eager or the \
             lazy path never ran"
        );
        assert_eq!(
            after_reads.rederived + after_reads.served,
            checked as u64,
            "reads {} = served {} + rederived {} must account for every object",
            checked,
            after_reads.served,
            after_reads.rederived
        );
        // **What it costs on disk, measured rather than assumed.** §14 says the
        // price is "both copies are held" and the decision was taken with "we
        // don't care if disk is tripled" — so the real multiple belongs in the
        // output where anybody can read it, not in a sentence. It is not 3x on a
        // real pack: the verbatim bytes are deflated *and* delta-encoded, the
        // table holds raw inflated content, and redb pages it.
        let inflated: u64 = rows.iter().map(|r| r.uncompressed_size).sum();
        let table = std::fs::metadata(store.exploded_path())
            .map(|m| m.len())
            .unwrap_or(0);
        eprintln!(
            "load {}; {} pack entries → {} exploded rows, all {} re-hashed to their own oid; \
             ack {:.1} ms, drain {:.1} ms, {:.0} rows/s; disk: pack {:.1} MiB verbatim, objects \
             inflate to {:.1} MiB, table file {:.1} MiB ({:.0}x the pack, {:.3}x the payload)",
            loadavg(),
            rows.len(),
            stats.rows,
            checked,
            ack.as_secs_f64() * 1e3,
            drain.as_secs_f64() * 1e3,
            stats.rows as f64 / drain.as_secs_f64(),
            pack.len() as f64 / (1 << 20) as f64,
            inflated as f64 / (1 << 20) as f64,
            table as f64 / (1 << 20) as f64,
            table as f64 / pack.len() as f64,
            table as f64 / inflated.max(1) as f64,
        );
    }

    /// **The amplification measurement, at whatever scale you point it at.**
    ///
    /// [`a_push_produces_an_exploded_row_for_every_object_in_the_pack`] prints
    /// the same ratio on a 5.4 MiB fixture and is a *guard*, so it has to stay
    /// fast. This is the same arithmetic with no assertion about size and no
    /// fixture of its own: give it a pack and it reports what the table cost.
    ///
    /// ```text
    /// ZNIPPY_EXPLODE_BENCH_PACK=/path/to/pack-….pack \
    ///   cargo test -p znippy-plugin-git --lib the_table_costs_what_it_holds \
    ///   -- --ignored --nocapture
    /// ```
    ///
    /// It exists because the 12× figure that killed redb — 16.8 GB of resolved
    /// `linux.git` content in a 204 GB file — was taken by hand off a bench run
    /// that no longer exists, and a number nobody can re-take is a number that
    /// rots. `#[ignore]`d and pack-less by default: with no pack named it
    /// returns, so it never fails a suite for the absence of a corpus nobody
    /// promised to keep.
    #[test]
    #[ignore = "needs a pack: ZNIPPY_EXPLODE_BENCH_PACK=<path> cargo test … -- --ignored --nocapture"]
    fn the_table_costs_what_it_holds() {
        let Ok(path) = std::env::var("ZNIPPY_EXPLODE_BENCH_PACK") else {
            eprintln!("no ZNIPPY_EXPLODE_BENCH_PACK named; nothing measured");
            return;
        };
        let pack = std::fs::read(&path).unwrap_or_else(|e| panic!("reading {path}: {e}"));
        let dir = tmpdir("exploded-cost");
        let store = GitStore::open(&dir, "rickard").unwrap();

        let t = Instant::now();
        store.put_pack(&pack).unwrap();
        let ack = t.elapsed();
        store.wait_indexed();
        let drain = t.elapsed();

        let stats = store.exploded_stats();
        let table = std::fs::metadata(store.exploded_path())
            .map(|m| m.len())
            .unwrap_or(0);
        // The payload the table actually holds, asked of the table rather than
        // of the pack — a pack entry's `uncompressed_size` is what git recorded,
        // and this is what we stored. Only the second one can be divided into
        // the file size and mean anything.
        let mut held = 0u64;
        for kind in [
            GitObjectKind::Commit,
            GitObjectKind::Tree,
            GitObjectKind::Blob,
            GitObjectKind::Tag,
        ] {
            held += store
                .exploded_of_kind(kind)
                .unwrap()
                .iter()
                .map(|(_, p)| p.len() as u64)
                .sum::<u64>();
        }
        let mib = |n: u64| n as f64 / (1 << 20) as f64;
        eprintln!(
            "load {}; pack {} — {:.1} MiB verbatim → {} rows holding {:.1} MiB, table file \
             {:.1} MiB = {:.3}x the payload and {:.1}x the pack; ack {:.0} ms, drain {:.0} ms",
            loadavg(),
            path,
            mib(pack.len() as u64),
            stats.rows,
            mib(held),
            mib(table),
            table as f64 / held.max(1) as f64,
            table as f64 / pack.len() as f64,
            ack.as_secs_f64() * 1e3,
            drain.as_secs_f64() * 1e3,
        );
    }

    /// Where the child of the clean-shutdown guard finds its fixture and leaves
    /// its markers.
    const CLEAN_DIR: &str = "GUNNAR_CLEAN_SHUTDOWN_DIR";

    /// **The other half of
    /// [`a_clean_shutdown_and_reopen_keeps_the_graph_and_reachable`]: the process
    /// that exits normally.**
    ///
    /// A real process, a real push, a real drain, and then a real `drop` — every
    /// worker joined, every redb handle closed, no signal, exit status 0. That is
    /// what makes the parent's reopen a *clean* reopen rather than a recovery,
    /// and it is the case the crash guard cannot reach: after a clean shutdown
    /// every pack's bit is legitimately set and **nothing is re-queued**, so the
    /// derived tables have to have been on disk or they are gone.
    ///
    /// `#[ignore]`d because it is a fixture, not a guard — run on its own it has
    /// no directory to work in and returns.
    #[test]
    #[ignore = "spawned by a_clean_shutdown_and_reopen_keeps_the_graph_and_reachable"]
    fn the_child_that_pushes_and_shuts_down_cleanly() {
        let Ok(dir) = std::env::var(CLEAN_DIR) else {
            return;
        };
        let dir = PathBuf::from(dir);
        let pack = std::fs::read(dir.join("fixture.pack")).expect("the parent's fixture");

        let store = GitStore::open(&dir, "rickard").expect("open");
        store.put_pack(&pack).expect("the ack path");
        store.wait_indexed();
        assert_eq!(store.unindexed_packs(), 0, "the child shut down mid-index");

        let tip = store
            .graph_snapshot()
            .into_iter()
            .max_by_key(|c| c.generation)
            .expect("the child built no graph at all");
        let tip_raw = hex::decode(&tip.oid).unwrap();
        let closure = store.reachable(&[&tip_raw], &[]).unwrap();
        assert!(!closure.is_empty(), "the child's own reachable() was empty");

        std::fs::write(dir.join("tip"), &tip.oid).expect("marker");
        std::fs::write(dir.join("closure"), closure.len().to_string()).expect("marker");
        std::fs::write(dir.join("commits"), store.commit_count().to_string()).expect("marker");
        std::fs::write(dir.join("objects"), store.object_count().to_string()).expect("marker");

        // **The clean shutdown.** Not a signal and not an abort: the store drops,
        // which closes the channel, joins the account indexer's worker and closes
        // redb. The process then returns normally with status 0.
        drop(store);
        std::fs::write(dir.join("clean"), b"closed").expect("marker");
    }

    /// **`commit_count()` and `reachable()` are correct after a CLEAN shutdown
    /// and reopen.** This is the guard the exploded table exists to make pass.
    ///
    /// It was the live bug: the commit graph was folded from commit and tree
    /// *payloads* which were stored nowhere, accumulated in RAM as packs were
    /// absorbed. A store killed mid-absorb got them back only because the
    /// interrupted pack was re-queued and re-resolved
    /// ([`a_store_reopened_after_a_kill_mid_absorb_requeues_the_pack`]); a store
    /// that shut down **cleanly** re-queued nothing, and MEASURED on oden
    /// 2026-08-08 came back with 2687 rows and **0 of 551 commits** —
    /// `reachable()` returning a commit alone instead of its closure, and `gc`
    /// seeing an empty live set. Both are quiet wrong answers.
    ///
    /// The shape is the crash guard's: a **real** child process, which here exits
    /// normally, and the parent asserts against what is on disk. Two assertions
    /// carry it and they have to be in this order:
    ///
    /// 1. **`commit_count()` immediately after `open`**, before anything is
    ///    waited on — so the graph can only have come from the fold over the
    ///    exploded table that `open` performs, not from a re-absorb;
    /// 2. **`is_indexed(0)` is false after `wait_indexed()`** — the account
    ///    indexer in *this* process publishes a pack only for a job somebody
    ///    submitted, so a clear bit proves open re-queued nothing and the graph
    ///    above is not a recovery artefact.
    ///
    /// `reachable()` is then asserted against the closure the child computed on
    /// the same tip, so it is the same answer and not merely a non-empty one.
    ///
    /// Seen RED by deleting `store.refold()?` from the end of
    /// `GitStore::open_with_arms`, so nothing folds the table on open: "the
    /// commit graph did not survive a clean shutdown: 0 of 551 commits — the
    /// exploded table is a warm cache, not a durable table", left 0 right 551.
    /// That is the recorded bug's own number, reproduced. Restored.
    ///
    /// Seen RED a second time by deleting `self.exploded.flush()?` from
    /// `Absorber::absorb_one`, which is the **durability** edit: the rows then
    /// live only in the un-flushed buffer, which answers perfectly inside the
    /// child and is gone when the process ends. It fires assertion (2) rather
    /// than (1) — "the reopen re-queued the pack, so the graph above is a
    /// recovery artefact rather than the table's" — and that is worth writing
    /// down, because assertion (1) *passed*: the 64 MiB flush threshold had
    /// tripped once mid-pack, leaving 1798 of 2687 rows on disk which happened
    /// to include all 551 commits. A guard with only assertion (1) would have
    /// called that edit green. Restored.
    /// **An annotated tag reaches the commit it points at.**
    ///
    /// # The bug this is the guard for
    ///
    /// Reachability bitmaps are built over the commit graph, and no tree points
    /// at a tag, so a tag is in nobody's closure. `reachable`'s `want` loop had
    /// one arm for "not a commit": insert the object itself, and stop. So a
    /// `want` that was an annotated tag answered with **one object** — the tag —
    /// and the commit it names, plus that commit's whole history, was left out.
    ///
    /// It stayed invisible because a tag is nearly always pushed alongside the
    /// branch that carries the same commit, and then the branch's closure
    /// covers it. It surfaces the moment a tag is the ONLY thing naming a
    /// commit — which is what gunnar's replication does, one ref at a time. Six
    /// repositories on the live fleet could not replicate on 2026-08-31, one of
    /// them with 25 tags hanging off a single commit no branch carried, all
    /// refused by the far end as `missing necessary objects … (peeling a tag)`.
    ///
    /// So the fixture asserts the premise it needs: the tag is the only `want`.
    ///
    /// # 🔴 Seen red
    ///
    /// Against the arm as it was (`union.insert(o)` and nothing more):
    /// `the tag's closure is 1 object, so it carries the tag and nothing it
    /// points at`. With the peel: the commit, its trees and its blobs.
    #[test]
    fn an_annotated_tag_reaches_the_commit_it_points_at() {
        let dir = tmpdir("tag-peel");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let (pack, rows) = corpus_pack();
        store.put(&pack, &[]).unwrap();
        store.wait_indexed();

        // Any commit will do: the tag is the only `want`, so nothing else can
        // pull this commit's closure in behind our backs.
        let commit = rows
            .iter()
            .find(|r| r.kind == GitObjectKind::Commit)
            .expect("the corpus has commits");
        let commit_hex = hex::encode(&commit.oid);
        let commit_closure = store.reachable(&[&commit.oid], &[]).unwrap();
        assert!(
            commit_closure.len() > 1,
            "the fixture's commit closes over nothing, so this test could not tell a peel from a              no-op"
        );

        let (tag_pack, tag_oid) = crate::store::tests::one_tag_pack(&commit_hex, "v1.0");
        store.put(&tag_pack, &[]).unwrap();
        store.wait_indexed();

        let closure = store.reachable(&[&tag_oid], &[]).unwrap();
        assert!(
            closure.contains(&tag_oid),
            "the tag itself is not in its own closure"
        );
        assert!(
            closure.contains(&commit.oid),
            "the tag's closure is {} object(s), so it carries the tag and nothing it points at —              the commit {} it names is missing and a mirror built from this answer cannot be              read",
            closure.len(),
            &commit_hex[..12]
        );
        // Not merely the commit: everything the commit reaches, or a clone from
        // this answer is short by a tree.
        for oid in &commit_closure {
            assert!(
                closure.contains(oid),
                "the tag's closure is missing {} which the commit it points at reaches",
                hex::encode(oid)
            );
        }
    }

    #[test]
    fn a_clean_shutdown_and_reopen_keeps_the_graph_and_reachable() {
        let dir = tmpdir("clean-shutdown-graph");
        let (pack, rows) = corpus_pack();
        std::fs::write(dir.join("fixture.pack"), &pack).unwrap();

        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "--ignored",
                "--nocapture",
                "git_ops::tests::the_child_that_pushes_and_shuts_down_cleanly",
            ])
            .env(CLEAN_DIR, &dir)
            .status()
            .expect("spawn the child that shuts down cleanly");
        assert!(
            status.success(),
            "the child did not exit cleanly — it {status:?}, so this is a crash guard and not a \
             clean-shutdown one"
        );
        assert!(
            dir.join("clean").exists(),
            "the child never reached its clean shutdown"
        );

        let tip_hex = std::fs::read_to_string(dir.join("tip")).unwrap();
        let closure_before: usize = std::fs::read_to_string(dir.join("closure"))
            .unwrap()
            .parse()
            .unwrap();
        let commits_before: usize = std::fs::read_to_string(dir.join("commits"))
            .unwrap()
            .parse()
            .unwrap();
        assert_eq!(
            commits_before,
            commits_in(&rows),
            "the child's own graph was already wrong, so the reopen proves nothing"
        );

        // ── the reopen, and (1): the graph before anything is waited on ──────
        let store = GitStore::open(&dir, "rickard").unwrap();
        assert_eq!(
            store.commit_count(),
            commits_in(&rows),
            "the commit graph did not survive a clean shutdown: {} of {} commits — the exploded \
             table is a warm cache, not a durable table",
            store.commit_count(),
            commits_in(&rows)
        );
        let tip_raw = hex::decode(&tip_hex).unwrap();
        let closure = store.reachable(&[&tip_raw], &[]).unwrap();
        assert_eq!(
            closure.len(),
            closure_before,
            "reachable() answers differently after a clean reopen: {} objects against the {} the \
             same tip closed over before the shutdown",
            closure.len(),
            closure_before
        );
        assert!(closure.contains(&tip_raw));

        // ── (2): and none of it came from a re-absorb ────────────────────────
        store.wait_indexed();
        assert!(
            !store.indexer().is_indexed(0),
            "the reopen re-queued the pack, so the graph above is a recovery artefact rather \
             than the table's"
        );
        assert_eq!(store.unindexed_packs(), 0);
        assert_eq!(
            store.absorb_pending().unwrap(),
            0,
            "the reopen left index work"
        );
        assert_eq!(store.object_count(), rows.len());
        assert_eq!(
            store.exploded_stats().written,
            0,
            "this process wrote exploded rows, so the table was rebuilt rather than read"
        );

        eprintln!(
            "load {}; clean shutdown → reopen: {} rows, {} commits, tip closure {} objects \
             (rebuilt nothing)",
            loadavg(),
            store.object_count(),
            store.commit_count(),
            closure.len(),
        );
    }

    /// **A reopen READS `objects.graph`; it does not recompute it — and the
    /// read graph equals the recomputed one.** This is S-065's fix, and the only
    /// thing that can say which path a fold took is a counter, so the assertion
    /// is on [`GitStore::graph_source_stats`], not on the (identical) graph
    /// bytes — the identity-value trap, since both paths yield the same graph.
    ///
    /// One test exercises **both** arms so the counter cannot be blindly stuck:
    ///
    /// 1. A first store builds the graph, persists it, and shuts down cleanly.
    /// 2. `objects.graph` is deleted, so the reopen has no cache: it **recomputes**
    ///    (`(read, recomputed) == (0, 1)`) and re-persists. Its graph and its
    ///    `reachable()` are captured — this is the recomputed truth.
    /// 3. A second reopen finds the cache the step above wrote: it **reads**
    ///    (`(1, 0)`), and its graph and `reachable()` must equal step 2's exactly
    ///    — read == recomputed.
    ///
    /// # 🔴 Seen red
    ///
    /// With the persistence removed (open always folds), step 3 is `(0, 1)`:
    /// "the reopen recomputed the graph instead of reading objects.graph", left
    /// `(0, 1)` right `(1, 0)`. With the token check inverted so a stale cache is
    /// accepted, step 3's `reachable()` diverges from step 2's and the read==
    /// recomputed assertion fires. Restored.
    #[test]
    fn a_reopen_reads_the_persisted_graph_it_does_not_recompute() {
        let dir = tmpdir("persisted-graph");
        let (pack, rows) = corpus_pack();
        let tip_hex;
        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
            tip_hex = store
                .graph_snapshot()
                .into_iter()
                .max_by_key(|c| c.generation)
                .expect("a graph")
                .oid;
            assert!(
                dir.join("objects.graph").exists(),
                "an absorb never persisted the graph, so a reopen has nothing to read"
            );
        }
        let tip_raw = hex::decode(&tip_hex).unwrap();

        // ── (2) no cache → recompute, and capture the recomputed truth ───────
        std::fs::remove_file(dir.join("objects.graph")).unwrap();
        let (recomputed_graph, recomputed_closure) = {
            let store = GitStore::open(&dir, "rickard").unwrap();
            assert_eq!(
                store.graph_source_stats(),
                (0, 1),
                "with no objects.graph the reopen should have recomputed the graph"
            );
            assert_eq!(store.commit_count(), commits_in(&rows));
            let g = store.graph_snapshot();
            let c = store.reachable(&[&tip_raw], &[]).unwrap();
            assert!(!c.is_empty());
            (g, c)
        };

        // ── (3) cache present → read, and it must equal the recomputed truth ──
        let store = GitStore::open(&dir, "rickard").unwrap();
        assert_eq!(
            store.graph_source_stats(),
            (1, 0),
            "the reopen recomputed the graph instead of reading objects.graph"
        );
        assert_eq!(
            store.graph_snapshot(),
            recomputed_graph,
            "the graph READ from objects.graph differs from the one refold RECOMPUTES"
        );
        assert_eq!(
            store.reachable(&[&tip_raw], &[]).unwrap(),
            recomputed_closure,
            "reachable() over the persisted graph differs from reachable() over the recomputed one"
        );
        assert_eq!(store.commit_count(), commits_in(&rows));
    }

    /// **The graph cache switched off leaves no `objects.graph`** — and the store
    /// still answers the same graph and closure, folded from the exploded table.
    /// The switch is flipped on the absorber directly: `ZNIPPY_GIT_GRAPH_CACHE`
    /// is read at open, and setting it process-wide would race the test above.
    ///
    /// Seen red with the persist guard removed: "the graph cache is off and
    /// objects.graph was written anyway".
    #[test]
    fn with_the_graph_cache_off_no_objects_graph_is_written_and_the_graph_is_the_same() {
        let on_dir = tmpdir("graph-cache-on");
        let off_dir = tmpdir("graph-cache-off");
        let (pack, rows) = corpus_pack();
        let on = GitStore::open(&on_dir, "rickard").unwrap();
        on.put_pack(&pack).unwrap();
        on.wait_indexed();
        let off = GitStore::open(&off_dir, "rickard").unwrap();
        off.absorber.graph_cache.store(false, std::sync::atomic::Ordering::Relaxed);
        std::fs::remove_file(off_dir.join("objects.graph")).ok();
        off.put_pack(&pack).unwrap();
        off.wait_indexed();
        assert!(on_dir.join("objects.graph").exists(), "the default still persists the graph");
        assert!(
            !off_dir.join("objects.graph").exists(),
            "the graph cache is off and objects.graph was written anyway"
        );
        assert_eq!(off.graph_source_stats().0, 0, "a store with the cache off never reads one");
        assert_eq!(on.graph_snapshot(), off.graph_snapshot());
        assert_eq!(off.commit_count(), commits_in(&rows));
    }

    /// **The token gates the read: a cache whose token does not match the
    /// object set is rejected and the graph is recomputed.** This is what makes
    /// `objects.graph` a memo rather than a second truth — and a push, a gc, or
    /// a torn write all reach the store through exactly this door.
    ///
    /// The object set is left unchanged and the token in the cache is corrupted
    /// directly, so the ONE thing under test is the token comparison and not
    /// some incidental object-count difference.
    ///
    /// # 🔴 Seen red
    ///
    /// With the token comparison dropped (`Some((_, g)) => g`), the corrupted
    /// cache is read and the reopen is `(1, 0)`: "a cache with the wrong token
    /// was trusted". Restored.
    #[test]
    fn a_graph_whose_token_does_not_match_is_rejected() {
        let dir = tmpdir("wrong-token-graph");
        let (pack, _rows) = corpus_pack();
        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
        }
        // Flip a byte inside the 32-byte token (offset 5..37) without touching
        // the graph body, so only the token is wrong.
        let path = dir.join("objects.graph");
        let mut bytes = std::fs::read(&path).unwrap();
        assert!(bytes.len() > 37 && &bytes[..4] == b"GRPH");
        bytes[6] ^= 0xff;
        std::fs::write(&path, &bytes).unwrap();

        let store = GitStore::open(&dir, "rickard").unwrap();
        assert_eq!(
            store.graph_source_stats(),
            (0, 1),
            "a cache with the wrong token was trusted instead of being recomputed"
        );
    }

    /// **The ordinal space comes off the persisted index, not off a scan — and
    /// no `objects.ordinal` is ever written.** This replaces S-082's memo test:
    /// the memo spared a cold open the redb scan that rebuilt the sorted oid
    /// list, and since 2026-09-04 that list IS the persisted index's oid column,
    /// so there is nothing to spare and no file to validate. What is asserted:
    ///
    /// 1. A first store absorbs the corpus; its ordinal space equals the tail in
    ///    oid order and every oid is accounted to one of the two sources. Then
    ///    it folds explicitly, so redb is empty and the index holds everything.
    /// 2. The reopen is warm: its space comes **entirely off the index** —
    ///    `(folded, tail) == (n, 0)` — and equals step 1's space, closure and
    ///    counts exactly. `objects.ordinal` does not exist after either session.
    ///
    /// # 🔴 Seen red
    ///
    /// With `ObjectReadStack::oids_raw` returning only the redb tail on a
    /// persisting stack, step 2's space is empty (redb holds nothing after the
    /// fold) and `reachable()` over it is empty: "the ordinal space after the
    /// warm reopen is not the tail in oid order". Restored.
    #[test]
    fn the_ordinal_space_comes_off_the_index_not_a_scan() {
        let dir = tmpdir("ordinal-off-the-index");
        let (pack, rows) = corpus_pack();
        let tip_hex;
        let (first_oids, first_closure, first_objects, first_commits);
        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
            tip_hex = store
                .graph_snapshot()
                .into_iter()
                .max_by_key(|c| c.generation)
                .expect("a graph")
                .oid;
            let tip_raw = hex::decode(&tip_hex).unwrap();
            let n = store.object_count() as u64;
            let (folded, tail) = store.ordinal_source_stats();
            assert_eq!(folded + tail, n, "every oid is accounted to the index or the tail");
            let oids = store.ordinal_oids();
            let scanned: Vec<String> =
                store.index().oids_in_order().unwrap().iter().map(hex::encode).collect();
            assert_eq!(oids, scanned, "the ordinal space is not the repository in oid order");
            assert!(
                !dir.join("objects.ordinal").exists(),
                "no memo may be written: the index's oid column is the ordinal space"
            );
            // Fold, so the reopen has everything on the index and nothing in redb.
            store.index().rebuild().unwrap();
            first_closure = store.reachable(&[&tip_raw], &[]).unwrap();
            assert!(!first_closure.is_empty());
            first_oids = oids;
            first_objects = store.object_count();
            first_commits = store.commit_count();
        }
        let tip_raw = hex::decode(&tip_hex).unwrap();

        let store = GitStore::open(&dir, "rickard").unwrap();
        let n = store.object_count() as u64;
        assert_eq!(
            store.ordinal_source_stats(),
            (n, 0),
            "after a fold the warm reopen's ordinal space must come entirely off the index"
        );
        assert_eq!(
            store.ordinal_oids(),
            first_oids,
            "the ordinal space after the warm reopen is not the tail in oid order"
        );
        assert_eq!(
            store.reachable(&[&tip_raw], &[]).unwrap(),
            first_closure,
            "reachable() over the index's ordinal space differs from the first session's"
        );
        assert_eq!(store.object_count(), first_objects);
        assert_eq!(store.commit_count(), first_commits);
        assert_eq!(store.commit_count(), commits_in(&rows));
        assert!(!dir.join("objects.ordinal").exists(), "still no memo after the reopen");
    }

    /// **A stale `objects.ordinal` left by an older binary is removed at open.**
    /// The file is dead weight now (279 MB on the kernel mirror) and its
    /// contents are never read, so a store that carries one loses it the first
    /// time this build opens it — and keeps working.
    ///
    /// # 🔴 Seen red
    ///
    /// With the `remove_file` in `open_with_arms` dropped, the file survives the
    /// open: "a stale objects.ordinal must be removed at open". Restored.
    #[test]
    fn a_stale_objects_ordinal_from_an_older_binary_is_removed_at_open() {
        let dir = tmpdir("stale-ordinal");
        let (pack, _rows) = corpus_pack();
        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
        }
        // The old memo's shape: magic, version, oid_len, epoch, count, oids.
        let path = dir.join("objects.ordinal");
        let mut bytes = b"ORDL".to_vec();
        bytes.push(1);
        bytes.push(20);
        bytes.extend_from_slice(&7u64.to_le_bytes());
        bytes.extend_from_slice(&1u64.to_le_bytes());
        bytes.extend_from_slice(&[0xabu8; 20]);
        std::fs::write(&path, &bytes).unwrap();
        assert!(path.exists(), "precondition");

        let store = GitStore::open(&dir, "rickard").unwrap();
        assert!(!path.exists(), "a stale objects.ordinal must be removed at open");
        assert!(store.object_count() > 0, "and the store still answers");
    }

    /// **A content read is served from the table, not re-derived** — and the only
    /// thing that can say so is a counter.
    ///
    /// Both paths return the **identical** bytes: the table hands back what the
    /// resolver produced, and the fallback re-resolves the same pack and produces
    /// it again. A byte comparison therefore proves nothing at all about which
    /// one ran — this is the identity-value trap in its exact form, and it fired
    /// on this codebase once already. So the assertion is on
    /// [`ExplodedStats::served`] against [`ExplodedStats::rederived`], both of
    /// which are bumped where the work happens.
    ///
    /// The fallback is not asserted away: it is exercised in the same test, on a
    /// store whose table has been dropped, and the counters move the other way.
    /// A guard that only saw the fast path could not tell a working counter from
    /// one that is never incremented.
    ///
    /// Seen RED by deleting the `if let Some(hit) = self.exploded.content(oid)?`
    /// early return in `Absorber::resolved`, so every read re-derives: "512 content
    /// reads re-resolved a whole pack instead of hitting the table — served 0,
    /// rederived 512". The bytes were still correct on every one of them, which
    /// is the point. Restored.
    ///
    /// Seen RED a second time by bumping `served` unconditionally at the top of
    /// `ExplodedTable::content`, before the `pending`/redb probe — the counter
    /// then reports a hit whether or not the table had the object. The first half
    /// fires on the double count, "512 content reads re-resolved a whole pack
    /// instead of hitting the table — served 1024, rederived 0", and
    /// `exploded::tests::a_row_round_trips_and_the_kind_index_finds_it` fires with
    /// it ("a content read was not counted", left 5 right 2). Restored — a
    /// counter that cannot be wrong about a miss is the only kind worth
    /// asserting on.
    #[test]
    fn a_content_read_is_served_from_the_table_and_not_re_derived() {
        const READS: usize = 512;
        let dir = tmpdir("exploded-served");
        let (pack, rows) = corpus_pack();
        let oids: Vec<Vec<u8>> = rows
            .iter()
            .map(|r| r.oid.clone())
            .collect::<HashSet<Vec<u8>>>()
            .into_iter()
            .take(READS)
            .collect();

        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();

            // ── FIRST read: the lazy path, timed ────────────────────────
            let before = store.exploded_stats();
            let t = Instant::now();
            let mut first: Vec<(GitObjectKind, Vec<u8>)> = Vec::with_capacity(oids.len());
            for oid in &oids {
                first.push(
                    store
                        .content(oid)
                        .unwrap()
                        .expect("the store lost an object"),
                );
            }
            let cold = t.elapsed();
            let after = store.exploded_stats();
            let rederived = after.rederived - before.rederived;
            assert_eq!(
                rederived + (after.served - before.served),
                oids.len() as u64,
                "{} reads = served {} + rederived {} must account for every one",
                oids.len(),
                after.served - before.served,
                rederived
            );
            assert!(
                rederived > 0,
                "not one read re-derived: either every object is eager or the lazy \
                 path never ran, and this test then proves nothing about either"
            );

            // The write-back is off the read path, so it has to be waited for
            // HERE and only here — a reader never does.
            store.explode_cache_maintain().unwrap();
            // **How many of those reads the cache DECLINED.** A shallow, small
            // object is cheaper to inflate again than to keep, so it is read
            // directly and nothing is written
            // (`exploded_cache::worth_caching`). Those objects are re-derived
            // on every read for ever, on purpose, and the second pass below
            // has to expect exactly that many — not zero, which is what this
            // test asserted before the admission policy existed and would now
            // be asserting that the policy is off.
            let declined = store.explode_cache_use().direct_reads;
            assert!(
                declined > 0,
                "not one of {} reads was declined as cheap; either every object in \
                 this corpus is expensive or the admission policy is not running",
                oids.len()
            );

            // ── SECOND read: the design note's "= today" column ──────────
            let mid = store.exploded_stats();
            let t = Instant::now();
            for (i, oid) in oids.iter().enumerate() {
                let again = store.content(oid).unwrap().expect("the store lost an object");
                assert_eq!(again, first[i], "the second read of an object disagreed with the first");
            }
            let warm = t.elapsed();
            let end = store.exploded_stats();
            assert_eq!(
                end.rederived - mid.rederived,
                declined,
                "the second pass re-derived {} objects and the cache declined {declined} — \
                 every EXPENSIVE object must come out of the table the second time, and \
                 every cheap one must be read directly again",
                end.rederived - mid.rederived
            );
            assert_eq!(
                end.served - mid.served,
                oids.len() as u64 - declined,
                "the expensive objects did not come out of the table on the second pass"
            );
            eprintln!(
                "load {}; {} content reads: FIRST {:.1} ms ({:.1} µs/read, {} re-derived from \
                 the pack, {declined} of them too cheap to cache) → SECOND {:.1} ms \
                 ({:.1} µs/read) = {:.1}x",
                loadavg(),
                oids.len(),
                cold.as_secs_f64() * 1e3,
                cold.as_secs_f64() * 1e6 / oids.len() as f64,
                rederived,
                warm.as_secs_f64() * 1e3,
                warm.as_secs_f64() * 1e6 / oids.len() as f64,
                cold.as_secs_f64() / warm.as_secs_f64().max(f64::MIN_POSITIVE),
            );
        }

        // ── and the fallback, so the counter is not a constant ───────────────
        //
        // The table is dropped and the *drain* is what would rebuild it, so the
        // reads have to happen before it gets there. `absorb_pending` is called
        // by hand first so the fallback under test is the content path's and not
        // the index's.
        std::fs::remove_file(dir.join("objects.exploded")).unwrap();
        // **And the lazy pool with it.** Dropping only the eager table leaves
        // the write-backs of the pass above sitting in `objects.exploded.cN`,
        // and those would answer — the fallback would then be measured on a
        // store that still has a cache, which is the exact shape of a test that
        // cannot fail. One `drop_explode_cache` is the sanctioned door, and it
        // is what `repo gc` calls.
        for e in std::fs::read_dir(&dir).unwrap().flatten() {
            if e.file_name().to_string_lossy().starts_with("objects.exploded.c") {
                std::fs::remove_file(e.path()).unwrap();
            }
        }
        let store = GitStore::open(&dir, "rickard").unwrap();
        let gate = store.hold_absorb_gate();
        let before = store.exploded_stats();
        let mut rederived = 0u64;
        for oid in oids.iter().take(8) {
            // Straight at the absorber: the store's `content` would absorb the
            // re-queued pack first and rebuild the very table this is testing
            // the absence of.
            assert!(
                store.absorber.resolved(oid).unwrap().is_some(),
                "the verbatim truth could not re-derive {}",
                hex::encode(oid)
            );
            rederived += 1;
        }
        let after = store.exploded_stats();
        // The drain starts the instant the store opens; on a loaded box it can
        // rebuild the small corpus's table before the gate above is taken, and
        // then the reads are legitimately served from it. Seen 2026-08-30 under
        // a parallel suite. That run proves nothing about the fallback and says
        // so, rather than failing on a race the test does not control.
        let drain_won = store.unindexed_packs() == 0;
        drop(gate);
        if drain_won {
            eprintln!("the drain rebuilt the table before the gate was held; the fallback was not observed this run");
            return;
        }
        assert_eq!(
            after.served - before.served,
            0,
            "a dropped table still reported {} reads served",
            after.served - before.served
        );
        assert_eq!(
            after.rederived - before.rederived,
            rederived,
            "the fallback ran but was not counted"
        );
    }

    /// ★ **THE READ-AFTER-ACK GAP (lane U → lane Q): every read path answers
    /// with the indexer PAUSED, and none of them waits for it.**
    ///
    /// MEASURED on the rig 2026-08-30 (lane U, both ISOs, timing-dependent):
    /// right after an ACKED push a `clone` came back
    /// `remote error: object … is not in this repository (peeling a tag)` and a
    /// `push --mirror` on top got `[remote rejected] … missing necessary
    /// objects`. Both of those are gunnar's `Graph::load` — `GitServe::read` —
    /// answering `None` for an object whose bytes were fsynced before the client
    /// was told the push had landed. §13.12 says an index miss falls back to the
    /// journal; the tag-peel and connectivity-check paths were not observed to.
    ///
    /// So this holds the absorb gate — the indexer paused, exactly the state
    /// lane P's watchdog puts it in — and requires **`has`, `header` and `read`
    /// to answer for every object of a just-acked pack**, byte-correct, and to
    /// do it inside a deadline. The deadline is not decoration: "nobody waits"
    /// (the design note's rule) is violated by a read that blocks on the gate
    /// just as badly as by one that answers absent, and a blocking read looks
    /// exactly like a correct one to an assertion that has no clock.
    ///
    /// Seen RED by returning `Ok(None)` from `Absorber::resolved`'s pending arm:
    /// 1352 of 1352 objects report "the store said absent for an object it had
    /// already acked".
    #[test]
    fn every_read_path_answers_a_just_acked_push_with_the_indexer_paused() {
        use crate::serve::GitServe as _;
        let dir = tmpdir("read-after-ack");
        let store = Arc::new(GitStore::open(&dir, "rickard").unwrap());
        let (pack, rows) = corpus_pack();

        // The ack: `put_pack` returning is what the client is told.
        store.put_pack(&pack).unwrap();

        // The indexer, paused. A watchdog pause (lane P) pauses the indexer and
        // nothing else, so this is the shape the appliance is really in.
        let gate = store.hold_absorb_gate();
        assert!(
            store.unindexed_packs() > 0,
            "the drain absorbed the pack before the gate was taken, so this run \
             read an INDEXED store and proves nothing about the window"
        );

        let distinct: Vec<Vec<u8>> = rows
            .iter()
            .map(|r| r.oid.clone())
            .collect::<HashSet<Vec<u8>>>()
            .into_iter()
            .collect();
        let hash = store.hash_kind();
        let n = distinct.len();

        // On another thread, so the deadline measures the reads and not this
        // test's own patience.
        let (tx, rx) = std::sync::mpsc::channel::<Result<(usize, usize, usize)>>();
        let reader = {
            let store = store.clone();
            let distinct = distinct.clone();
            std::thread::spawn(move || {
                let mut had = 0usize;
                let mut headed = 0usize;
                let mut readback = 0usize;
                let r = (|| -> Result<()> {
                    for oid in &distinct {
                        if store.has(oid)? {
                            had += 1;
                        }
                        if crate::serve::GitServe::header(&*store, oid)?.is_some() {
                            headed += 1;
                        }
                        // The tag-peel / connectivity-check path, byte for byte.
                        let Some((kind, payload)) = crate::serve::GitServe::read(&*store, oid)? else {
                            continue;
                        };
                        let k = match kind {
                            crate::index_layout::ObjType::Commit => GitObjectKind::Commit,
                            crate::index_layout::ObjType::Tree => GitObjectKind::Tree,
                            crate::index_layout::ObjType::Blob => GitObjectKind::Blob,
                            crate::index_layout::ObjType::Tag => GitObjectKind::Tag,
                            // A read resolves the chain, so a delta type coming
                            // back out of it is the store contradicting itself.
                            other => anyhow::bail!("`read` answered with a {other:?}"),
                        };
                        let rehashed = hash.oid_of(&crate::object::canonical(k, &payload));
                        if &rehashed == oid {
                            readback += 1;
                        }
                    }
                    Ok(())
                })();
                let _ = tx.send(r.map(|_| (had, headed, readback)));
            })
        };

        // The deadline. Generous — a cold pending scan of the corpus is
        // milliseconds — and it is against a WALL clock while the gate is held,
        // so a read that parks on the absorber trips it.
        let out = rx
            .recv_timeout(Duration::from_secs(20))
            .expect(
                "a read path blocked on the paused indexer for 20 s: 'nobody waits' is the \
                 design note's rule and a read that waits for the drain is a bug by definition",
            );
        let (had, headed, readback) = out.expect("a read path errored inside the index window");
        drop(gate);
        let _ = reader.join();

        assert_eq!(
            (had, headed, readback),
            (n, n, n),
            "the store answered for {had}/{n} `has`, {headed}/{n} `header` and {readback}/{n} \
             byte-correct `read`s of a pack it had already ACKED — an object the client was \
             told had landed must never read as absent"
        );
    }

    /// ★ **An account at its explode budget serves EVERY object, correctly —
    /// only slower.**
    ///
    /// The quota is a cache size, not a storage limit: over budget the server
    /// EVICTS, it does not refuse. So a repository squeezed to a budget far
    /// under what it holds must still answer every read byte-for-byte, and the
    /// only thing that may change is where the bytes came from — the table, or
    /// the pack via [`crate::resolve::materialize_at`].
    ///
    /// This is requirement (c) of the quota: *"an account at its budget must
    /// still serve every read correctly, only slower"*. The `rederived`
    /// counter is what proves the eviction really happened, because identical
    /// bytes come back either way and a byte comparison cannot tell a working
    /// cache from a dead one — the identity-value trap in its exact form.
    ///
    /// Seen RED by having `write_back` return the payload's bytes from a
    /// half-written segment (`out.truncate(1)`): "the store returned the wrong
    /// bytes for an object under a squeezed budget".
    #[test]
    fn an_account_at_its_budget_serves_every_object_only_slower() {
        let dir = tmpdir("explode-budget");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let (pack, rows) = corpus_pack();
        store.put_pack(&pack).unwrap();
        store.wait_indexed();

        let oids: Vec<Vec<u8>> = rows
            .iter()
            .map(|r| r.oid.clone())
            .collect::<HashSet<Vec<u8>>>()
            .into_iter()
            .collect();

        // Every object once, unsqueezed: the truth to compare against.
        let mut truth: Vec<(GitObjectKind, Vec<u8>)> = Vec::with_capacity(oids.len());
        for oid in &oids {
            truth.push(store.content(oid).unwrap().expect("the store lost an object"));
        }
        store.explode_cache_maintain().unwrap();

        // Now the plan changes: a budget far under what this repository holds.
        store.set_explode_budget(64 << 10);
        let before = store.exploded_stats();
        for _ in 0..3 {
            for (i, oid) in oids.iter().enumerate() {
                let got = store
                    .content(oid)
                    .unwrap()
                    .expect("an object went absent when the budget was lowered");
                assert_eq!(
                    got, truth[i],
                    "the store returned the wrong bytes for an object under a squeezed budget"
                );
            }
            store.explode_cache_maintain().unwrap();
        }
        let after = store.exploded_stats();
        let band = store.explode_cache_use();

        assert!(
            band.evicted_bytes > 0 || band.lazy_bytes <= 64 << 10,
            "the budget was lowered to 64 KiB and the lazy pool holds {} B with nothing \\
             evicted — the quota is not enforced, so this run proves nothing about reading \\
             under one: {band:?}",
            band.lazy_bytes
        );
        assert!(
            after.rederived > before.rederived,
            "not one read re-derived from the pack under a 64 KiB budget, so the cache was \\
             never squeezed and 'only slower' was never tested"
        );
        eprintln!(
            "load {}; {} objects read 3x under a 64 KiB budget: {} re-derived, {} served, \
{} evicted bytes over {} segments; every byte identical",
            loadavg(),
            oids.len(),
            after.rederived - before.rederived,
            after.served - before.served,
            band.evicted_bytes,
            band.evicted_segments,
        );
    }

    /// ★ **A THIN push on top of a just-acked one is accepted with the indexer
    /// PAUSED** — lane U's second rig symptom.
    ///
    /// MEASURED on the rig 2026-08-30 (lane U): right after an acked push,
    /// `git push --mirror` of the next pack came back
    /// `[remote rejected] … missing necessary objects`, on a varying set of
    /// repositories run to run — a race, not a repository. A thin pack names
    /// its delta bases by oid and expects the server to have them; the server
    /// **did** have them, in a pack it had acked and not yet indexed, and
    /// `scan_pending`'s re-entrancy guard answered `None` for every base looked
    /// up from inside a scan rather than only for the ones that would have
    /// started a second scan.
    ///
    /// Seen RED by restoring that guard (`if nested { return Ok((out, None)) }`):
    /// *"reading the thin pack's object errored inside the index window:
    /// resolving a pending pack read-only for lookups — this pack is thin: it
    /// deltas against 42088154… which is not in it, and no base source could
    /// produce that object's content"*. The **push** is accepted either way —
    /// `external_bases_exist` finds the base with a top-level `lookup_one`
    /// before it ever resolves — so the assertion that discriminates is the
    /// READ with the gate still held, and an earlier draft of this test that
    /// dropped the gate first passed under both arms.
    #[test]
    fn a_thin_push_on_top_of_an_unindexed_one_is_accepted() {
        let dir = tmpdir("thin-on-unindexed");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let (pack, rows) = corpus_pack();
        store.put_pack(&pack).unwrap();

        // The indexer, paused — so the base can only be found in the pack that
        // was acked a moment ago.
        let gate = store.hold_absorb_gate();
        assert!(
            store.unindexed_packs() > 0,
            "the drain absorbed the first pack before the gate was taken; this run \
             pushed onto an INDEXED store and proves nothing"
        );

        // A base with a payload, and its real size: a `REF_DELTA` declares the
        // source size and the resolver checks it, so a made-up number would fail
        // for a reason that has nothing to do with the window under test.
        let base = rows
            .iter()
            .find(|r| r.kind == GitObjectKind::Blob && r.uncompressed_size > 0)
            .expect("the corpus has a blob");
        let thin = crate::pack_fixture::thin_ref_delta_pack(
            &base.oid,
            base.uncompressed_size,
            b"lane Q was here\n",
        );

        let tx = store.put_pack(&thin).unwrap_or_else(|e| {
            panic!("the thin push was refused: {e:#}");
        });
        assert!(tx.pack_id.is_some(), "the thin pack was not stored");

        // **And its object reads back with the gate STILL HELD.** This is the
        // nested case and the one the guard was too wide for: the read scans
        // pack B, B's entry is a ref-delta, its base is in pack A, and
        // resolving it is a second `scan_pending` from inside the first. A
        // lookup into A's already-built scan terminates; only a *build* would
        // not.
        let hash = store.hash_kind();
        let oid = hash.oid_of(&crate::object::canonical(
            GitObjectKind::Blob,
            b"lane Q was here\n",
        ));
        let got = store.content(&oid);
        drop(gate);
        let (kind, payload) = got
            .expect("reading the thin pack's object errored inside the index window")
            .expect("the thin pack's own object is absent after its push was acked");
        assert_eq!(kind, GitObjectKind::Blob);
        assert_eq!(payload, b"lane Q was here\n");
    }

    /// **Dropping the table and reopening still answers correctly — fall back,
    /// then rebuild.**
    ///
    /// §14 calls the resolved table *droppable*: derived, verifiable against the
    /// verbatim truth, and deletable at any time without consulting a client.
    /// This is that sentence as an operation — `rm objects.exploded` between two
    /// opens — and §13.12's rule applied to it unchanged: **absent means fall
    /// back, never means wrong.**
    ///
    /// Three things are asserted, in this order:
    ///
    /// 1. the file really is gone and the reopened store really does start with
    ///    an empty table — otherwise the rest is testing a warm one;
    /// 2. **`reachable()` is already correct**, asked before any drain has been
    ///    waited on: the fall-back absorb runs inline and rebuilds what the
    ///    answer needs;
    /// 3. the table is **rebuilt** — one row per object again, the graph back,
    ///    and the rows written by *this* process, which is what says a rebuild
    ///    happened rather than a survival.
    ///
    /// Seen RED by `let exploded_is_whole = self.exploded.rows()? >= self.objects.len()
    /// as u64;` → `= true;` in `Absorber::adopt_journal`, so a dropped table is
    /// never noticed and nothing is re-queued. Assertion (2) fires first:
    /// **"reachable() after dropping the table: 1 objects, against 2683
    /// before"** — one object, the tip alone, which is the recorded bug's exact
    /// symptom ("`reachable` on a commit returns that commit alone rather than
    /// its closure") arrived at from the other direction. Restored.
    ///
    /// Seen RED a second time by `>=` → `>` in the same expression, which makes a
    /// *whole* table look short. This guard stays green — the rebuild is
    /// correct — and two others fire instead:
    /// [`a_clean_shutdown_and_reopen_keeps_the_graph_and_reachable`]'s "the
    /// reopen re-queued the pack, so the graph above is a recovery artefact
    /// rather than the table's", and the pre-existing
    /// [`a_clean_reopen_requeues_nothing_and_the_next_push_gets_a_fresh_ordinal`]'s
    /// "a fully absorbed pack was re-queued on open — the diff is not exact".
    /// That pair is the point: one guard catches the table not being rebuilt when
    /// it should be, the others catch it being rebuilt when it should not.
    /// Restored.
    #[test]
    fn dropping_the_exploded_table_and_reopening_still_answers() {
        let dir = tmpdir("exploded-dropped");
        let (pack, rows) = corpus_pack();
        let tip_hex;
        let closure_before;
        {
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
            let tip = store
                .graph_snapshot()
                .into_iter()
                .max_by_key(|c| c.generation)
                .expect("a graph");
            let tip_raw = hex::decode(&tip.oid).unwrap();
            closure_before = store.reachable(&[&tip_raw], &[]).unwrap().len();
            tip_hex = tip.oid;
        }

        // (1) — the drop.
        let table = dir.join("objects.exploded");
        assert!(table.exists(), "the store never built an exploded table");
        std::fs::remove_file(&table).unwrap();
        {
            let fresh = crate::exploded_arrow::ExplodedArchive::open(&table).unwrap();
            assert_eq!(fresh.rows().unwrap(), 0, "the drop did not drop anything");
        }
        // Opening an absent table does not create one — so this only has
        // anything to remove if the assertion above was inspecting a live file.
        let _ = std::fs::remove_file(&table);

        // (2) — a correct answer with the table gone.
        let store = GitStore::open(&dir, "rickard").unwrap();
        let tip_raw = hex::decode(&tip_hex).unwrap();
        let closure = store.reachable(&[&tip_raw], &[]).unwrap();
        assert_eq!(
            closure.len(),
            closure_before,
            "reachable() after dropping the table: {} objects, against {} before",
            closure.len(),
            closure_before
        );
        assert!(store.has(&rows[0].oid).unwrap());

        // (3) — and it is back. The GRAPH is what comes back at push time; a
        // blob comes back when somebody reads it, which is the whole of lazy
        // explode, so the count to compare against is the graph's and not the
        // pack's.
        store.wait_indexed();
        let stats = store.exploded_stats();
        let distinct: HashSet<Vec<u8>> = rows.iter().map(|r| r.oid.clone()).collect();
        // Commits, and NOT `of_kind(Tree)`: under the shipped policy a tree is
        // lazy, so the trees this test's own reads cached are in the lazy pool
        // and `of_kind` unions both.
        let graph_rows = store.exploded_of_kind(GitObjectKind::Commit).unwrap().len();
        // The EAGER pool, not `stats.rows`: step (2) above read objects through
        // the store, and every one of those reads wrote its object back into the
        // lazy pool, which `stats.rows` also counts. Comparing the sum against
        // the graph would be comparing "what the push wrote" against "what the
        // push wrote plus what this test happened to read".
        let eager = store.exploded_eager_rows().unwrap();
        assert_eq!(
            eager, graph_rows as u64,
            "the dropped table came back holding {eager} rows against a {}-object graph",
            graph_rows
        );
        assert!(
            eager > 0 && eager < distinct.len() as u64,
            "the rebuilt pool holds {eager} of {} objects — neither 0 nor all of them is \
             the lane Q shape",
            distinct.len()
        );
        assert!(
            stats.written > 0,
            "the table came back without this process writing a row — it was never dropped"
        );
        assert_eq!(
            store.commit_count(),
            commits_in(&rows),
            "the graph did not come back with the table: {} of {}",
            store.commit_count(),
            commits_in(&rows)
        );
        assert_eq!(
            store.object_count(),
            rows.len(),
            "the rebuild lost index rows"
        );
        eprintln!(
            "load {}; dropped and rebuilt: {} rows written, {} commits, tip closure {} objects",
            loadavg(),
            stats.written,
            store.commit_count(),
            closure.len(),
        );
    }

    // ─────────────────────────────────────────────────────────────────────
    // lane ENGINE-OPT scaffold: a graded linear-history generator, the O(C)
    // negotiation timing test, and the cross-push memo-invalidation guard.
    // ─────────────────────────────────────────────────────────────────────

    /// A linear commit history of `n` commits as a clone pack, optionally
    /// chained onto `start_parent` (an oid already in the store). Each commit
    /// carries its own one-entry tree and one unique blob, so the object count
    /// is `3n` and the graph is a single parent chain `n` deep — the shape that
    /// makes a negotiation's cost O(commits), which is what this lane memoizes.
    fn linear_history_pack_from(
        n: usize,
        start_parent: Option<&[u8]>,
    ) -> (Vec<u8>, Vec<Vec<u8>>) {
        use crate::object::canonical;
        use crate::pack_fixture::{build_pack, Item};
        let hash = GitHashKind::Sha1;
        let mut items: Vec<Item> = Vec::with_capacity(n * 3);
        let mut commits: Vec<Vec<u8>> = Vec::with_capacity(n);
        let mut prev: Option<Vec<u8>> = start_parent.map(|p| p.to_vec());
        for c in 0..n {
            let body = format!("blob for commit {c} of {n}, parent {prev:?}\n").into_bytes();
            let blob_oid = hash.oid_of(&canonical(GitObjectKind::Blob, &body));
            items.push(Item::Whole(GitObjectKind::Blob, body));

            let mut tpayload = Vec::new();
            tpayload.extend_from_slice(b"100644 f.bin\0");
            tpayload.extend_from_slice(&blob_oid);
            let tree_oid = hash.oid_of(&canonical(GitObjectKind::Tree, &tpayload));
            items.push(Item::Whole(GitObjectKind::Tree, tpayload));

            let mut cbody = format!("tree {}\n", hex::encode(&tree_oid));
            if let Some(parent) = &prev {
                cbody.push_str(&format!("parent {}\n", hex::encode(parent)));
            }
            cbody.push_str(
                "author A U Thor <a@example.com> 1700000000 +0000\n\
                 committer A U Thor <a@example.com> 1700000000 +0000\n\n\
                 commit\n",
            );
            let cbody = cbody.into_bytes();
            let commit_oid = hash.oid_of(&canonical(GitObjectKind::Commit, &cbody));
            items.push(Item::Whole(GitObjectKind::Commit, cbody));
            prev = Some(commit_oid.clone());
            commits.push(commit_oid);
        }
        (build_pack(&items), commits)
    }

    /// The O(commits) negotiation cost, graded. `reachable` rebuilt the
    /// `by_commit` and graph maps on every call — O(C) regardless of how few
    /// objects the request touched — so the `root` query (closure ~1) isolates
    /// that map-build cost from the walk, and the `tip` query (full closure)
    /// pays both. Median of nine, min–max, with the loadavg of its own run.
    #[test]
    #[ignore = "perf measurement; run with --release --ignored --nocapture"]
    fn bench_reachable_negotiation() {
        for &n in &[48usize, 2_000, 20_000] {
            let dir = tmpdir(&format!("bench-reach-{n}"));
            let (pack, commits) = linear_history_pack_from(n, None);
            let store = GitStore::open(&dir, "rickard").unwrap();
            store.put_pack(&pack).unwrap();
            store.wait_indexed();
            let root = commits.first().unwrap().clone();
            let tip = commits.last().unwrap().clone();
            // warm the reach bitmaps once so the loop times the negotiation, not
            // the one-time bitmap build.
            let _ = store.reachable(&[&tip], &[]).unwrap();

            let reps = 9usize;
            let (mut root_t, mut tip_t) = (Vec::new(), Vec::new());
            for _ in 0..reps {
                let t = Instant::now();
                let _ = store.reachable(&[&root], &[]).unwrap();
                root_t.push(t.elapsed());
                let t = Instant::now();
                let _ = store.reachable(&[&tip], &[]).unwrap();
                tip_t.push(t.elapsed());
            }
            root_t.sort();
            tip_t.sort();
            let tip_closure = store.reachable(&[&tip], &[]).unwrap().len();
            eprintln!(
                "load {}; n={n}: reachable(root, closure~1) med {:?} [{:?}..{:?}]  |  \
                 reachable(tip, closure {}) med {:?} [{:?}..{:?}]",
                loadavg(),
                root_t[reps / 2],
                root_t[0],
                root_t[reps - 1],
                tip_closure,
                tip_t[reps / 2],
                tip_t[0],
                tip_t[reps - 1],
            );
        }
    }

    /// **A negotiation answered from the memoized reach view is the answer a
    /// cold fold gives — including across a push that changes the fold.**
    ///
    /// Lane ENGINE-OPT memoizes the `by_commit` and graph lookup maps that
    /// `reachable` used to rebuild on every call, in `Derived`, folded by the
    /// same call that folds `commit_raw`. The bug this discipline exists to
    /// catch is a memo that SURVIVES a fold it should not: after a push adds
    /// commits, the warm store must answer with the new closure, byte-identical
    /// (order included — both spaces sort the same oids) to a fresh store
    /// opened cold on the same bytes.
    ///
    /// Seen RED by skipping the memo rebuild in `refold` (leaving `graph_index`
    /// from before the push): the post-push tip is then not a known commit,
    /// `reachable` contributes it alone, and the warm answer is a handful of
    /// objects where the cold fold gives the whole chain — the assertion names
    /// both lengths.
    #[test]
    fn reachable_memo_matches_a_cold_fold_across_a_push() {
        let dir = tmpdir("reach-memo-across-push");
        let (pack_a, commits_a) = linear_history_pack_from(40, None);
        let store = GitStore::open(&dir, "rickard").unwrap();
        store.put_pack(&pack_a).unwrap();
        store.wait_indexed();
        let tip_a = commits_a.last().unwrap().clone();
        let warm_a = store.reachable(&[&tip_a], &[]).unwrap();
        assert!(
            warm_a.len() > 10,
            "A's closure is too small to tell a stale memo from a coincidence: {}",
            warm_a.len()
        );

        // Push B: a second linear history chained ONTO A's tip, so B's tip
        // closes over A too. This is a fold that genuinely grows the graph.
        let (pack_b, commits_b) = linear_history_pack_from(40, Some(&tip_a));
        store.put_pack(&pack_b).unwrap();
        store.wait_indexed();
        let tip_b = commits_b.last().unwrap().clone();
        let warm_b_full = store.reachable(&[&tip_b], &[]).unwrap();
        let warm_b_minus_a = store.reachable(&[&tip_b], &[&tip_a]).unwrap();
        assert!(
            warm_b_full.len() > warm_a.len(),
            "the push did not grow the closure ({} !> {}), so the memo could be \
             stale and this test would not know",
            warm_b_full.len(),
            warm_a.len()
        );

        // The cold oracle: a fresh handle on the same bytes, folded from disk.
        drop(store);
        let cold = GitStore::open(&dir, "rickard").unwrap();
        cold.wait_indexed();
        let cold_b_full = cold.reachable(&[&tip_b], &[]).unwrap();
        let cold_b_minus_a = cold.reachable(&[&tip_b], &[&tip_a]).unwrap();

        assert_eq!(
            warm_b_full, cold_b_full,
            "warm memo != cold fold for want=tip_b (a memo that survived the push)"
        );
        assert_eq!(
            warm_b_minus_a, cold_b_minus_a,
            "warm memo != cold fold for want=tip_b have=tip_a"
        );
        // tip_a is still answered identically after the push (its closure did
        // not change; only the store grew around it).
        let cold_a = cold.reachable(&[&tip_a], &[]).unwrap();
        assert_eq!(
            warm_a, cold_a,
            "tip_a's closure changed across the push"
        );
        eprintln!(
            "load {}; A closure {}, B closure {}, B−A {}",
            loadavg(),
            warm_a.len(),
            warm_b_full.len(),
            warm_b_minus_a.len(),
        );
    }

    /// **The clone-after-push lever, witnessed.** A push folds; the fold used
    /// to drop the reachability table and the next reader rebuilt it by
    /// walking every commit's trees — 0.2 ms per object, 10 s on a 51k-object
    /// repository, measured 2026-09-05. Now the fold CARRIES the table
    /// (renumbered) when the graph grew by no more than the carry rule allows.
    /// RED before the carry: `reach_rebuilt` went 1 → 2 across the push.
    #[test]
    fn a_push_carries_the_reach_table_across_the_fold() {
        let dir = tmpdir("reach-carry-across-push");
        let (pack_a, commits_a) = linear_history_pack_from(40, None);
        let store = GitStore::open(&dir, "rickard").unwrap();
        store.put_pack(&pack_a).unwrap();
        store.wait_indexed();
        let tip_a = commits_a.last().unwrap().clone();
        let warm_a = store.reachable(&[&tip_a], &[]).unwrap();
        assert_eq!(store.reach_source_stats(), (0, 1), "the first read builds the table once");

        // A push of 30 commits onto A's tip: within the carry rule (64 or a
        // tenth of 40, whichever is larger), so the fold carries.
        let (pack_b, commits_b) = linear_history_pack_from(30, Some(&tip_a));
        store.put_pack(&pack_b).unwrap();
        store.wait_indexed();
        let tip_b = commits_b.last().unwrap().clone();
        let warm_b = store.reachable(&[&tip_b], &[]).unwrap();
        let warm_b_minus_a = store.reachable(&[&tip_b], &[&tip_a]).unwrap();
        assert_eq!(
            store.reach_source_stats(),
            (1, 1),
            "the fold carried the table; no read rebuilt it"
        );
        assert!(warm_b.len() > warm_a.len(), "the push grew the closure");
        assert_eq!(warm_b_minus_a.len(), warm_b.len() - warm_a.len(), "tip_b − tip_a is exactly the pushed objects");
        assert_eq!(store.reachable(&[&tip_a], &[]).unwrap(), warm_a, "tip_a's closure survived the renumbering");

        // The cold oracle: the same bytes folded from disk with a fresh table.
        drop(store);
        let cold = GitStore::open(&dir, "rickard").unwrap();
        cold.wait_indexed();
        assert_eq!(cold.reachable(&[&tip_b], &[]).unwrap(), warm_b, "carried != rebuilt for want=tip_b");
        assert_eq!(
            cold.reachable(&[&tip_b], &[&tip_a]).unwrap(),
            warm_b_minus_a,
            "carried != rebuilt for want=tip_b have=tip_a"
        );
        assert_eq!(cold.reach_source_stats(), (0, 1), "the cold handle built once and carried nothing");
    }

    /// The carry rule's other arm: a push larger than the allowance drops the
    /// table and the next read rebuilds it whole — bounded staleness, never a
    /// walk that grows without limit.
    #[test]
    fn a_push_past_the_carry_allowance_rebuilds_the_reach_table() {
        let dir = tmpdir("reach-carry-rebuild");
        let (pack_a, commits_a) = linear_history_pack_from(20, None);
        let store = GitStore::open(&dir, "rickard").unwrap();
        store.put_pack(&pack_a).unwrap();
        store.wait_indexed();
        let tip_a = commits_a.last().unwrap().clone();
        let _ = store.reachable(&[&tip_a], &[]).unwrap();
        assert_eq!(store.reach_source_stats(), (0, 1));
        // 100 commits > max(64, 20/10): over the allowance.
        let (pack_b, commits_b) = linear_history_pack_from(100, Some(&tip_a));
        store.put_pack(&pack_b).unwrap();
        store.wait_indexed();
        let tip_b = commits_b.last().unwrap().clone();
        let warm_b = store.reachable(&[&tip_b], &[]).unwrap();
        assert_eq!(store.reach_source_stats(), (0, 2), "over the allowance: not carried, rebuilt once more");
        drop(store);
        let cold = GitStore::open(&dir, "rickard").unwrap();
        cold.wait_indexed();
        assert_eq!(cold.reachable(&[&tip_b], &[]).unwrap(), warm_b, "rebuilt warm != cold fold");
    }

    /// ★ **A push alone makes the cache give space back at the disk line.**
    /// Owner 2026-09-28: the indexing thread should also de-cache.
    ///
    /// The lazy pool is filled into several segments under a 10 % disk, then
    /// the disk reads 85 % and a pack is pushed. No reader touches the store
    /// after that, so only the indexer can have started the cleanup.
    ///
    /// Seen RED by removing `self.exploded.kick()` from `absorb_one_inner`:
    /// the pool kept every segment after the push.
    #[test]
    fn a_push_past_the_disk_line_evicts_the_oldest_cache_without_a_read() {
        let dir = tmpdir("push-disk-line");
        let store = GitStore::open(&dir, "rickard").unwrap();
        let c = store.absorber.exploded.clone();
        c.set_global_line(0);
        c.set_segment_bytes_for_test(256 << 10);
        c.set_disk_reading_for_test(10);
        // Incompressible, deep enough to be admitted: the cache must hold it.
        let mut x: u32 = 0x9E37_79B9;
        let big: Vec<u8> = (0..64 << 10)
            .map(|_| {
                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                (x >> 24) as u8
            })
            .collect();
        let cost = crate::resolve::ReadCost {
            depth: crate::exploded_cache::CHEAP_DEPTH + 8,
            inflated: big.len() as u64,
            external_base: false,
        };
        for i in 0..24u32 {
            let mut oid = vec![0u8; 20];
            oid[..4].copy_from_slice(&i.to_be_bytes());
            c.write_back(&oid, GitObjectKind::Blob, &big, cost).unwrap();
            c.maintain().unwrap();
        }
        let before = c.use_now();
        assert!(before.segments >= 4, "precondition: rotated into segments, has {}", before.segments);
        assert_eq!(before.evicted_segments, 0, "precondition: nothing evicted under a 10 % disk");

        c.set_disk_reading_for_test(85);
        let (pack, _) = one_blob_pack(b"pushed after the disk crossed its line\n");
        store.put(&pack, &[]).unwrap();
        store.wait_indexed();
        let deadline = Instant::now() + Duration::from_secs(10);
        while c.use_now().evicted_segments == 0 && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(20));
        }
        let after = c.use_now();
        assert!(after.evicted_segments > 0, "the push did not make the cache give anything back");
        assert_eq!(after.segments, 1, "past the line the pool keeps only its live segment");
    }
}