ostrya 0.12.1

Pure-Rust async reimplementation of the ostree repository library
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
//! Static deltas in a pull: the search for a delta on the source and its
//! application into the transaction of the pull.
//!
//! A [`DeltaSource`] is the remote of the pull, over HTTP or over ssh, or the
//! directory of the source repository of a local pull. The pull reads the same
//! paths from each source, under the same size caps. [`PART_CAP`] sets the
//! limit of part fetches in flight from a remote. The rules that a caller
//! sees are on `Repo::pull`, under `# Static deltas`, and on
//! `PullOptions::require_static_deltas`.
//!
//! `PullOptions::static_deltas` replaces the search with a list of deltas
//! that the caller gives. The sibling module `chain` plans chains of deltas
//! from such a list, and [`discover`] then fetches the steps of the chains. A
//! pull from a remote runs its plan one time for each level of intermediate
//! commits, with the jobs of that level, and then one time for the targets.
//! A local pull applies and imports each level of intermediate commits in
//! turn, and then the targets. It parses, applies, and drops the job of one
//! step of a list at a time, so the heap holds one job of the list.
//!
//! [`discover_dependencies`] finds one delta for each dependency of a pull,
//! after the pull read the commits that name the dependencies. The sibling
//! module `dependency` gives the source commit of each search. With a list,
//! the search takes one entry of the list, and plans no chain. The searches
//! check no signature of a superblock, as [`discover_dependencies`] states.
//! From a remote, the searches keep each superblock after its checks and the
//! commit that it carries in a record file, as the discovery of a chain below
//! does. The pull parses the superblock of a dependency again just before its
//! parts, as [`DependencyDeltas`] states.
//!
//! The discovery of a chain keeps one record for each step of the plan, and
//! drops each parsed superblock after its checks. So the heap holds one
//! parsed superblock at a time. A record from a remote keeps the raw
//! superblock in one unlinked temp file in `tmp/` of the repository, with no
//! map. Discovery writes the bytes to the file after the digest check and
//! before the other checks. A failed check stops the pull, so each record
//! that discovery keeps holds verified bytes. The file has a size limit,
//! [`MAX_RECORD_FILE`]. A discovery that would pass it fails the pull. A
//! record from a local source keeps no bytes, and the parse of a level reads
//! the superblock from the source again and checks its digest. The parse of a
//! level gives the jobs of that level alone, and the parse of a record gives
//! the job of one step.
//!
//! For the commit of each step, discovery fetches the `.commitmeta` from a
//! remote. From a local source it reads the `.commitmeta` only if the policy
//! checks commits. Then it checks the signatures of the commit that the
//! superblock carries. For a remote source, if the check parsed the
//! `.commitmeta` and `[ex-ostrya] keep-detached-related` of the destination is
//! `false`, discovery then drops `ostrya.related` from that parse, and the
//! record file keeps the result. For a target, it also makes the ref-binding
//! check of each requested ref that names it. For a remote source it also makes
//! the timestamp check of each of these refs, and for a local source it makes
//! none, because a local pull has none. So a refused target costs no part.
//!
//! The pull checks no commit of the last plan a second time. A commit that
//! has no record in the last plan gets the check of the pull when the pull
//! fetches it. This is a target whose chain a later plan drops, or a dropped
//! intermediate commit that a depth walk reaches as a parent. If discovery
//! fetched the `.commitmeta` of such a commit, the pull requests it again.
//!
//! Over HTTP, discovery requests the `.commitmeta` after the superblock. On a
//! stream session, discovery sends the request of the superblock and the
//! request of the `.commitmeta` as one pair, as [`fetch_step`] states. The
//! reply of the `.commitmeta` arrives while discovery parses the superblock,
//! so the heap then holds one superblock and one `.commitmeta`: up to
//! [`MAX_SUPERBLOCK`] plus [`MAX_METADATA_SIZE`] bytes, and the parse of the
//! superblock. A missing superblock costs its paired `.commitmeta` request.
//! If a later plan reaches the same commit, discovery requests and counts the
//! `.commitmeta` again, so the metadata count can be one higher than over
//! HTTP for each such superblock.
//!
//! If the source does not hold a superblock of the plan, discovery excludes
//! that delta, plans again, and fetches only the steps that it did not fetch
//! before. The planner limits the number of deltas that one discovery plans
//! again around.
//!
//! The digest check, the parse, and the check of the inline parts of a
//! superblock run on the blocking pool.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::os::unix::fs::FileExt;
use std::sync::{Arc, Mutex, PoisonError};

use ostrya_core::{Checksum, Commit, ObjectName, ObjectType, RepoMode, Value};
use ostrya_rt::FileReader;

use crate::delta::{
    Blob, DeltaFallback, DeltaPart, DeltaSuperblock, MAX_SUPERBLOCK, apply_part, check_inline_part,
    concat_to_blob, decode_inline_part, decode_part_stream, inline_part_at, verify_inline_part,
};
use crate::deltagen::{
    STATIC_DELTAS_KEY, SUPERBLOCK_FILE, delta_index_relative_path, delta_name, delta_relative_dir,
    index_delta_map, parse_delta_name,
};
use crate::error::{Error, Result};
use crate::fetch::{FetchRequest, Fetched, Fetcher, Priority};
use crate::object::MAX_METADATA_SIZE;
use crate::pull::verify::Verification;
use crate::pull::{ModeChecks, PullCounters, PullFlags, PullOptions, RefPlace};
use crate::read::CommitState;
use crate::related::{self, RelatedField, RelatedRule};
use crate::repo::Repo;
use crate::repo_fs::{FsResultExt, RepoDir, RepoLayout, TempFile};
use crate::summary::{AdvertisedDelta, INDEXED_DELTAS_KEY, Summary, delta_digest};
use crate::transaction::Transaction;

use super::chain::{
    ChainPlan, ChainSearch, Edges, Planned, check_complete, complete_sources, scratch_allowed,
};
use super::drive::Slots;
use super::http::{cached_source, fetch_remote_detached};
use super::source::{RemoteSource, Transfer, session_error};
use super::{
    CheckedDetached, CheckedMeta, TipChecks, check_commit_signatures_filtered,
    check_local_commit_signatures, check_tip_refs, count_fetched,
};

/// The number of delta parts that one pull fetches at a time.
pub(crate) const PART_CAP: usize = 2;

/// The size limit of the record file of one discovery, 1 GiB.
///
/// One step keeps at most [`MAX_SUPERBLOCK`] bytes of superblock and
/// [`MAX_METADATA_SIZE`] bytes of `.commitmeta`, 256 MiB in total. So the file
/// holds four steps of the maximum size. The limit applies to the length of
/// the file, the bytes of the records that discovery drops included.
///
/// The search for the deltas of the dependencies has a record file of its
/// own, with the same limit. It keeps the superblocks and the commits that
/// they carry. A superblock carries its commit, so the commit is smaller than
/// the superblock, and the file holds four superblocks of the maximum size
/// with their commits.
const MAX_RECORD_FILE: u64 = 8 * MAX_METADATA_SIZE;

/// A static delta that a pull applies for one commit.
///
/// Without a list of static deltas, discovery builds the job of each target
/// commit that has a delta, and the job lives until the pull returns. With a
/// list, discovery keeps a record for each step of the chains, and the pull
/// builds the jobs from the records. For a pull from a remote,
/// [`DeltaPlan::parse_level`] builds the jobs of the intermediate commits of
/// one level before the run of that level, and the jobs live for that run
/// alone. [`DeltaPlan::target_jobs`] builds the jobs of the target commits
/// after the run of the last level. A local pull builds the job of one step
/// at a time with [`DeltaPlan::parse_record`], and drops it after its parts.
/// The run of the dependencies builds the job of a dependency just before its
/// parts, and drops it after its last part, as [`DependencyDeltas`] states.
/// A job holds only what the application of the parts reads.
///
/// The parse of a superblock reads the raw superblock bytes, the signature
/// array, and the metadata dict, and drops them before the job exists. The
/// heap cost of a job is one meta-entry for each part and at most 128 KiB of
/// inline part bodies. The meta-entries list each object that the delta
/// produces. The superblock size that a remote chooses does not change this
/// cost.
///
/// The job keeps the inline part bodies in one [`Blob`]. If the bodies total
/// 128 KiB or less, the blob is on the heap. If they total more, the blob is
/// one read-only map of an anonymous temp file in `tmp/` of the repository.
/// This file costs disk space and address space up to the superblock size,
/// and the pull releases it when it drops the job.
pub(crate) struct DeltaJob {
    /// The request path prefix of the delta, `deltas/<fanout>/<rest>`.
    dir: String,
    /// The name of the delta in hex, `<to>` or `<from>-<to>`. It is the key in
    /// the advertisement and the name in a message.
    name: String,
    /// The normal-form bytes of the target commit. The superblock carries them,
    /// and the pull stages the commit from them.
    ///
    /// The jobs of a pull from a remote are in a map that the concurrent steps
    /// share. The step of the commit takes a shared reference to the bytes,
    /// and does not copy them.
    pub(crate) commit_bytes: Arc<Vec<u8>>,
    /// The meta-entries of the parts, in part order: the checksum of each part,
    /// the size that caps its fetch, and the objects that it produces.
    meta_entries: Vec<DeltaPart>,
    /// The objects that the delta references and hands over loose.
    fallbacks: Vec<DeltaFallback>,
    /// One slot for each part, in part order. A slot holds the part if the
    /// superblock carries it inline, already verified against its meta-entry.
    /// A slot is `None` if the pull fetches the part as a file.
    inline: Vec<Option<InlinePart>>,
    /// The bodies of the inline parts, one after the other, in part order.
    inline_bodies: Blob,
}

/// A part that the superblock carries inline, copied out of the metadata dict.
struct InlinePart {
    /// The compression byte.
    compression: u8,
    /// The start, in [`DeltaJob::inline_bodies`], of the body that follows the
    /// compression byte.
    start: usize,
    /// The length of that body.
    len: usize,
}

impl DeltaJob {
    /// Returns the objects that the delta names and does not carry.
    ///
    /// The pull fetches these objects loose.
    pub(crate) fn fallbacks(&self) -> Vec<ObjectName> {
        loose_fallbacks(&self.fallbacks)
    }

    /// Returns the number of parts of the delta, inline parts and part files.
    pub(crate) fn parts(&self) -> usize {
        self.meta_entries.len()
    }

    /// Returns the number of part files and the sum of their declared sizes.
    ///
    /// A part file is a part that the pull fetches as a file. The superblock
    /// declares the size of each part.
    pub(crate) fn fetched_parts(&self) -> (u32, u64) {
        self.meta_entries
            .iter()
            .zip(&self.inline)
            .filter(|(_, inline)| inline.is_none())
            .fold((0, 0), |(parts, bytes), (entry, _)| {
                (parts + 1, bytes.saturating_add(entry.size))
            })
    }
}

/// Returns the names of the objects of `fallbacks`, which the pull fetches
/// loose.
fn loose_fallbacks(fallbacks: &[DeltaFallback]) -> Vec<ObjectName> {
    fallbacks
        .iter()
        .map(|fallback| ObjectName::new(fallback.checksum, fallback.objtype))
        .collect()
}

/// The deltas that discovery found for one pull.
///
/// Without a list of static deltas, `jobs` holds the delta of each target
/// commit that has one, and the plan holds no record. With a list, `jobs` is
/// empty. The plan then holds one record for each commit that a chain makes,
/// and the levels of the intermediate commits. The pull applies the levels in
/// order. A commit with a record and in no level is a target, and the pull
/// applies it last.
#[derive(Default)]
pub(crate) struct DeltaPlan {
    /// The job of each target commit, from the search for one delta.
    pub(crate) jobs: HashMap<Checksum, DeltaJob>,
    /// The record of the step that makes each commit of the chains.
    records: HashMap<Checksum, StepRecord>,
    /// The intermediate commits of the chains, by level, in plan order. A
    /// commit of level `k + 1` is made from a commit of level `k`. A commit
    /// with a record and in no level is a target, which the pull applies
    /// last.
    levels: Vec<Vec<Checksum>>,
    /// The entries of field 2 of each intermediate commit of the chains whose
    /// field 2 is not empty, for a local source.
    dependencies: HashMap<Checksum, Vec<(String, Checksum)>>,
    /// The file of the raw bytes of the records from a remote.
    store: Option<RecordStore>,
    /// The list of static deltas, after the discovery of the chains. The
    /// pull looks up the delta of each dependency in it.
    edges: Option<Edges>,
}

impl DeltaPlan {
    /// Adds the part files of each job and of each record, and their declared
    /// sizes, to the planned counts in `progress`.
    pub(crate) fn plan_parts(&self, progress: &PullCounters) {
        let jobs = self.jobs.values().map(DeltaJob::fetched_parts);
        let records = self.records.values().map(|record| record.parts);
        for (parts, bytes) in jobs.chain(records) {
            progress.parts_planned(parts, bytes);
        }
    }

    /// Parses the records of `commits` again, and returns the job of each
    /// commit that has a record.
    ///
    /// A record from a remote reads the bytes that discovery verified from
    /// the record file. A record from a local source reads the superblock
    /// from `source` again and checks it against the listed digest. The parse
    /// takes the inline parts of each job, as [`take_inline_parts`] states.
    ///
    /// # Errors
    ///
    /// - [`Error::ChecksumMismatch`] if a superblock of a local source does
    ///   not have the listed digest.
    /// - [`Error::InvalidFormat`] if a local source no longer holds a
    ///   superblock.
    pub(crate) async fn parse_level(
        &self,
        repo: &Repo,
        source: &DeltaSource<'_>,
        commits: &[Checksum],
    ) -> Result<HashMap<Checksum, DeltaJob>> {
        let mut jobs = HashMap::with_capacity(commits.len());
        for commit in commits {
            if let Some(job) = self.parse_record(repo, source, commit).await? {
                jobs.insert(*commit, job);
            }
        }
        Ok(jobs)
    }

    /// Parses the record of `commit` again, as
    /// [`parse_level`](DeltaPlan::parse_level) does, and returns its job.
    /// Returns `None` if the plan holds no record of `commit`.
    ///
    /// # Errors
    ///
    /// The errors of [`parse_level`](DeltaPlan::parse_level).
    pub(crate) async fn parse_record(
        &self,
        repo: &Repo,
        source: &DeltaSource<'_>,
        commit: &Checksum,
    ) -> Result<Option<DeltaJob>> {
        let Some(record) = self.records.get(commit) else {
            return Ok(None);
        };
        let fetched = read_record(self.store.as_ref(), source, record).await?;
        fetched.into_job(repo).await.map(Some)
    }

    /// Returns the intermediate commits of the chains, by level, in plan
    /// order.
    pub(crate) fn levels(&self) -> &[Vec<Checksum>] {
        &self.levels
    }

    /// Takes the jobs of the target commits.
    ///
    /// Without a list, these are the jobs of the search for one delta. With a
    /// list, the call also parses the records of the commits that are in no
    /// level, as [`parse_level`](DeltaPlan::parse_level) does, in checksum
    /// order. A pull from a remote calls it after the run of the last level,
    /// so the heap holds the jobs of one run at a time.
    ///
    /// # Errors
    ///
    /// The errors of [`parse_level`](DeltaPlan::parse_level).
    pub(crate) async fn target_jobs(
        &mut self,
        repo: &Repo,
        source: &DeltaSource<'_>,
    ) -> Result<HashMap<Checksum, DeltaJob>> {
        let mut jobs = std::mem::take(&mut self.jobs);
        let in_level: HashSet<&Checksum> = self.levels.iter().flatten().collect();
        let mut targets: Vec<Checksum> = self
            .records
            .keys()
            .filter(|commit| !in_level.contains(commit))
            .copied()
            .collect();
        targets.sort_unstable();
        jobs.extend(self.parse_level(repo, source, &targets).await?);
        Ok(jobs)
    }

    /// Returns the check that discovery made of `commit`.
    ///
    /// For a checked commit, the result holds the verified `.commitmeta` from
    /// the record file, and states whether the rule of `[ex-ostrya]
    /// keep-detached-related` ran over it. It holds `None` if no repository
    /// holds a `.commitmeta`, or if the rule keeps no property. A record from a
    /// local source keeps no bytes, so for a plan from a local source the
    /// result holds `None` and states only whether discovery checked the
    /// commit. The call then reads nothing.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] if the record file cannot be read.
    /// - [`Error::InvalidFormat`] if the plan holds no record file.
    pub(crate) async fn commit_check(&self, commit: &Checksum) -> Result<CommitCheck> {
        let Some(record) = self.records.get(commit) else {
            return Ok(CommitCheck::NotChecked);
        };
        match (&record.detached, self.store.as_ref()) {
            (Detached::NotChecked, _) => Ok(CommitCheck::NotChecked),
            (
                Detached::Checked {
                    kept: Some(range),
                    filtered,
                    ..
                },
                Some(store),
            ) => Ok(CommitCheck::Checked {
                detached: Some(store.read(range.clone()).await?),
                filtered: *filtered,
            }),
            (Detached::Checked { kept: Some(_), .. }, None) => Err(Error::InvalidFormat(
                "the record file holds no record".into(),
            )),
            (
                Detached::Checked {
                    kept: None,
                    filtered,
                    ..
                },
                _,
            ) => Ok(CommitCheck::Checked {
                detached: None,
                filtered: *filtered,
            }),
        }
    }

    /// Returns `true` if discovery checked `commit`, as
    /// [`CommitCheck::Checked`] states. The call reads nothing.
    pub(crate) fn checked(&self, commit: &Checksum) -> bool {
        self.records
            .get(commit)
            .is_some_and(|record| matches!(record.detached, Detached::Checked { .. }))
    }

    /// Returns what the check of `commit` in discovery read of its
    /// `.commitmeta` in a local source, or [`CheckedDetached::Unchecked`] if
    /// discovery did not check the commit or read no local source. The call
    /// reads nothing.
    pub(super) fn checked_detached(&self, commit: &Checksum) -> CheckedDetached {
        match self.records.get(commit).map(|record| &record.detached) {
            Some(Detached::Checked { local, .. }) => *local,
            _ => CheckedDetached::Unchecked,
        }
    }

    /// Takes the entries of field 2 of each intermediate commit of the
    /// chains, as names and checksums in the stored order. Discovery read them
    /// from the superblock of the step of a local source and checked their
    /// format.
    ///
    /// The map holds no commit whose field 2 is empty. For a plan from a
    /// remote source, the map is empty. The call reads nothing, and a second
    /// call returns an empty map.
    pub(crate) fn take_dependencies(&mut self) -> HashMap<Checksum, Vec<(String, Checksum)>> {
        std::mem::take(&mut self.dependencies)
    }

    /// Takes the list of static deltas, or `None` for a pull with no list or
    /// a commit-only pull. A second call returns `None`.
    pub(crate) fn take_edges(&mut self) -> Option<Edges> {
        self.edges.take()
    }
}

/// The check that discovery made of one commit.
pub(crate) enum CommitCheck {
    /// Discovery did not check the commit. The commit step checks it.
    NotChecked,
    /// Discovery checked the signatures of the commit, and made the
    /// ref-binding check of each requested ref that names it. For a remote
    /// source, discovery also made the timestamp check of each of these refs.
    Checked {
        /// The verified `.commitmeta`. It is `None` if no repository holds a
        /// `.commitmeta`, or if the rule keeps no property.
        detached: Option<Vec<u8>>,
        /// `true` if `detached` is the result of the rule of `[ex-ostrya]
        /// keep-detached-related`. `false` if `detached` holds the bytes as
        /// the source holds them, and the commit step runs the rule over them.
        filtered: bool,
    },
}

/// A step of a chain whose superblock discovery fetched and verified.
struct StepRecord {
    /// The delta of the step, as the list gives it.
    delta: AdvertisedDelta,
    /// The number of part files of the delta and the sum of their declared
    /// sizes.
    parts: (u32, u64),
    /// The range of the raw superblock in the record file. `None` for a local
    /// source, which keeps no bytes.
    superblock: Option<Range<u64>>,
    /// The check of the commit of the step.
    detached: Detached,
}

/// The check of the commit of a step, which discovery runs for each commit of
/// a chain.
enum Detached {
    /// Discovery did not check the commit yet.
    NotChecked,
    /// Discovery checked the commit, as [`CommitCheck::Checked`] states.
    Checked {
        /// The range of the verified `.commitmeta` in the record file. `None`
        /// if the remote and the localcache repositories hold none, if the
        /// rule keeps no property, and for a local source, which keeps no
        /// bytes.
        kept: Option<Range<u64>>,
        /// `true` if `kept` holds the result of the rule, as
        /// [`CommitCheck::Checked`] states.
        filtered: bool,
        /// What the check read of the `.commitmeta` in a local source.
        local: CheckedDetached,
    },
}

/// The result of the check of one commit of a chain.
struct Checked {
    /// The range of the verified `.commitmeta` in the record file, from a
    /// remote.
    kept: Option<Range<u64>>,
    /// `true` if `kept` holds the result of the rule, as
    /// [`CommitCheck::Checked`] states.
    filtered: bool,
    /// What the check read of the `.commitmeta` in a local source.
    /// [`CheckedDetached::Unchecked`] if the source is a remote, or if the
    /// policy checks no commit.
    local: CheckedDetached,
    /// The entries of field 2 of the commit, in the stored order, after the
    /// format check. The list is empty for a remote source: a pull from a
    /// remote reads field 2 when it stages the commit.
    dependencies: Vec<(String, Checksum)>,
}

/// The file that keeps the raw superblocks and the verified `.commitmeta`
/// files of a discovery from a remote. If the check of the signatures parsed a
/// `.commitmeta` and the rule of `[ex-ostrya] keep-detached-related` drops
/// `ostrya.related`, the file keeps the result of the rule. Else it keeps the
/// `.commitmeta` as the source holds it.
///
/// The file is one unlinked temp file in `tmp/` of the repository, open for
/// reads and writes and not mapped. It opens at the first write. Discovery
/// appends to it, and a record holds the range of its bytes. The bytes of a
/// record that discovery drops stay in the file. The file goes away when the
/// pull drops it.
///
/// The search for the deltas of the dependencies has a file of its own,
/// which its concurrent searches share. It keeps the superblocks and the
/// commits that they carry, as [`discover_dependencies`] states.
///
/// The length of the file has a limit. Discovery checks the limit before each
/// write, so the file never passes it. A write that would pass the limit
/// fails the pull with [`Error::Pull`].
struct RecordStore {
    /// The repository whose `tmp/` holds the file.
    repo: Repo,
    /// The file, after the first write.
    file: Option<Arc<std::fs::File>>,
    /// The length of the file.
    len: u64,
    /// The limit of the length of the file.
    limit: u64,
    /// What the file keeps. The error of the limit names it.
    records: Records,
}

/// What a [`RecordStore`] keeps.
#[derive(Clone, Copy)]
enum Records {
    /// The superblocks and the `.commitmeta` files of the discovery of a
    /// chain.
    Chain,
    /// The superblocks and the commits of the search for the deltas of the
    /// dependencies.
    Dependencies,
}

impl RecordStore {
    /// Returns a record store in `tmp/` of `repo` for the discovery of a
    /// chain, with no file yet, and with the limit [`MAX_RECORD_FILE`].
    fn new(repo: &Repo) -> RecordStore {
        RecordStore {
            repo: repo.clone(),
            file: None,
            len: 0,
            limit: MAX_RECORD_FILE,
            records: Records::Chain,
        }
    }

    /// Returns a record store in `tmp/` of `repo` for the search for the
    /// deltas of the dependencies, with no file yet, and with the limit
    /// [`MAX_RECORD_FILE`].
    fn for_dependencies(repo: &Repo) -> RecordStore {
        RecordStore {
            records: Records::Dependencies,
            ..RecordStore::new(repo)
        }
    }

    /// Checks that `len` more bytes keep the file in its limit.
    ///
    /// `what` names the bytes in the error.
    ///
    /// # Errors
    ///
    /// [`Error::Pull`] if the file would pass its limit.
    fn check_room(&self, len: u64, what: impl FnOnce() -> String) -> Result<()> {
        match self.len.checked_add(len) {
            Some(end) if end <= self.limit => Ok(()),
            _ => Err(Error::Pull(match self.records {
                Records::Chain => format!(
                    "static delta list: {} passes the limit of {} bytes for the superblocks \
                     and the detached metadata that discovery keeps",
                    what(),
                    self.limit
                ),
                Records::Dependencies => format!(
                    "static deltas of the dependencies: {} passes the limit of {} bytes for \
                     the superblocks and the commits that the search keeps",
                    what(),
                    self.limit
                ),
            })),
        }
    }

    /// Returns the file, and opens it if it is not open.
    async fn file(&mut self) -> Result<Arc<std::fs::File>> {
        if let Some(file) = &self.file {
            return Ok(Arc::clone(file));
        }
        let root = self.repo.root_dir().clone();
        let file =
            Arc::new(ostrya_rt::unblock(move || TempFile::create(&root)?.into_file()).await?);
        self.file = Some(Arc::clone(&file));
        Ok(file)
    }

    /// Returns the file, and opens it on the calling thread if it is not
    /// open. The caller is on the blocking pool.
    fn file_blocking(&mut self) -> Result<Arc<std::fs::File>> {
        if let Some(file) = &self.file {
            return Ok(Arc::clone(file));
        }
        let file = Arc::new(TempFile::create(self.repo.root_dir())?.into_file()?);
        self.file = Some(Arc::clone(&file));
        Ok(file)
    }

    /// Reserves `len` bytes at the end of the file, and returns the start of
    /// the reserved range. The caller writes the bytes. The call opens no
    /// file.
    ///
    /// `what` names the bytes in the error.
    ///
    /// # Errors
    ///
    /// [`Error::Pull`] if the bytes would pass the limit of the file.
    fn reserve(&mut self, len: u64, what: impl FnOnce() -> String) -> Result<u64> {
        self.check_room(len, what)?;
        let start = self.len;
        self.len += len;
        Ok(start)
    }

    /// Appends `bytes` on the blocking pool, and returns their range.
    ///
    /// `what` names the bytes in the error.
    ///
    /// # Errors
    ///
    /// - [`Error::Pull`] if the bytes would pass the limit of the file. The
    ///   call then opens no file and writes nothing.
    /// - [`Error::Io`] if the file cannot be opened or written.
    async fn append(
        &mut self,
        bytes: Vec<u8>,
        what: impl FnOnce() -> String,
    ) -> Result<Range<u64>> {
        self.check_room(bytes.len() as u64, what)?;
        let file = self.file().await?;
        let start = self.len;
        let end = start + bytes.len() as u64;
        ostrya_rt::unblock(move || file.write_all_at(&bytes, start)).await?;
        self.len = end;
        Ok(start..end)
    }

    /// Reads the bytes at `range` on the blocking pool.
    async fn read(&self, range: Range<u64>) -> Result<Vec<u8>> {
        let file = self
            .file
            .clone()
            .ok_or_else(|| Error::InvalidFormat("the record file holds no record".into()))?;
        ostrya_rt::unblock(move || {
            let len = usize::try_from(range.end - range.start)
                .map_err(|_| Error::InvalidFormat("a record is larger than memory".into()))?;
            let mut bytes = vec![0; len];
            file.read_exact_at(&mut bytes, range.start)?;
            Ok(bytes)
        })
        .await
    }
}

/// A superblock that discovery fetched and parsed, with its source and
/// target checked against the request, its signatures checked if the search
/// checks them, and its inline parts verified.
struct FetchedDelta {
    /// The request path prefix of the delta, `deltas/<fanout>/<rest>`.
    dir: String,
    /// The name of the delta in hex, `<to>` or `<from>-<to>`.
    name: String,
    /// The normal-form bytes of the target commit.
    commit_bytes: Vec<u8>,
    meta_entries: Vec<DeltaPart>,
    fallbacks: Vec<DeltaFallback>,
    /// The metadata dict, which carries the inline parts.
    metadata: Value,
    /// The position in `metadata` of each inline part, in part order.
    inline_index: Vec<Option<usize>>,
}

impl FetchedDelta {
    /// Copies the inline parts out of the metadata dict, and returns the job.
    async fn into_job(self, repo: &Repo) -> Result<DeltaJob> {
        let (inline, inline_bodies) = take_inline_parts(
            repo,
            &self.metadata,
            &self.inline_index,
            &self.dir,
            &self.meta_entries,
        )
        .await?;
        let FetchedDelta {
            dir,
            name,
            commit_bytes,
            meta_entries,
            fallbacks,
            metadata,
            ..
        } = self;
        drop(metadata);
        Ok(DeltaJob {
            dir,
            name,
            commit_bytes: Arc::new(commit_bytes),
            meta_entries,
            fallbacks,
            inline,
            inline_bodies,
        })
    }

    /// Returns the bytes of the target commit, and drops the rest of the
    /// parsed superblock.
    fn into_commit_bytes(self) -> Vec<u8> {
        self.commit_bytes
    }

    /// Returns the head of a delta from `from` whose superblock and commit
    /// the record file keeps at `superblock` and `commit`, and drops the
    /// parsed superblock.
    fn into_head(
        self,
        from: Option<Checksum>,
        superblock: Range<u64>,
        commit: Range<u64>,
    ) -> DependencyHead {
        DependencyHead {
            from,
            superblock,
            parts: self.meta_entries.len(),
            fallbacks: loose_fallbacks(&self.fallbacks),
            commit: Some(commit),
        }
    }

    /// Returns the number of part files and the sum of their declared sizes.
    fn parts(&self) -> (u32, u64) {
        self.meta_entries
            .iter()
            .enumerate()
            .filter(|(part, _)| self.inline_index.get(*part).copied().flatten().is_none())
            .fold((0, 0), |(parts, bytes), (_, entry)| {
                (parts + 1, bytes.saturating_add(entry.size))
            })
    }

    /// Verifies each inline part in place against its meta-entry, with no
    /// copy.
    fn verify_inline_parts(&self) -> Result<()> {
        for (part, entry) in self.meta_entries.iter().enumerate() {
            if let Some((compression, body)) =
                inline_part_at(&self.metadata, &self.inline_index, part, || {
                    self.dir.clone()
                })?
            {
                verify_inline_part(compression, body, entry)?;
            }
        }
        Ok(())
    }
}

/// A superblock that the blocking pool parsed, before the check of its
/// signatures.
struct ParsedDelta {
    delta: FetchedDelta,
    /// The raw superblock bytes that the signatures cover.
    superblock_bytes: Vec<u8>,
    /// The signature array.
    signatures: Option<Value>,
    /// The result of the check of the inline parts. The pull reports it after
    /// the check of the signatures.
    inline: Result<()>,
}

impl ParsedDelta {
    /// Checks the signatures of the superblock if `verification` is set, as
    /// [`verify_fetched_delta`] states, then gives the result of the check of
    /// the inline parts. Returns the delta, with the raw bytes and the
    /// signature array dropped.
    async fn verify(self, verification: Option<&Verification>) -> Result<FetchedDelta> {
        let ParsedDelta {
            delta,
            superblock_bytes,
            signatures,
            inline,
        } = self;
        // The check gives the bytes to the blocking pool in an `Arc`, with no
        // copy.
        let superblock_bytes = Arc::new(superblock_bytes);
        if let Some(verification) = verification {
            verify_fetched_delta(
                verification,
                &delta.name,
                &superblock_bytes,
                signatures.as_ref(),
            )
            .await?;
        }
        drop(superblock_bytes);
        inline?;
        Ok(delta)
    }
}

/// Finds the delta for each target commit, keyed by that commit.
///
/// The pull fetches a commit with no entry object by object. Discovery looks
/// for no delta in these cases:
///
/// - a commit that this repository already holds complete, because the walk
///   then fetches nothing
/// - a [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull, whose plan holds the
///   commit objects alone
/// - a pull held to [`subpaths`](PullOptions::subpaths) into an `archive`
///   repository with no
///   [`require_static_deltas`](PullOptions::require_static_deltas), which
///   fetches the subpaths loose
/// - a pull with
///   [`disable_static_deltas`](PullOptions::disable_static_deltas) set
///
/// If `disable_static_deltas` is set, discovery returns before all other
/// checks. A pull that requires static deltas from a source with no summary
/// fails before the other skips. `advert` holds what the summary of the
/// source states about its deltas, and is `None` for a source with no
/// summary. A pull that requires static deltas and finds no delta for a
/// commit fails as [`discover_one`] states.
///
/// Two refs that name one commit share one delta, because the plan fetches
/// that commit once. Discovery reads the source commit from the ref in this
/// repository, so it tries the refs in request order. The first ref that
/// yields a delta decides.
///
/// Each delta index request and each superblock request adds one to the
/// metadata count in `progress`, whatever the source answers. The `ostree`
/// command counts the same way. The discovery of a chain also counts the
/// `.commitmeta` of each commit of a chain, as [`check_step_commit`] states.
///
/// `edges` is the index of a list of static deltas. With a list, discovery
/// reads no summary and no delta index, and [`discover_chain`] plans and
/// fetches the chains. It also checks the commit of each step, a target
/// included, before the pull opens its transaction. `tips` holds the checks
/// of each requested ref, with the timestamp check that the caller resolved,
/// and the place of the refs, where discovery reads the current commit of a
/// ref. A local pull passes
/// [`TimestampBase::Off`](super::TimestampBase::Off). A
/// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull ignores the list. A pull that
/// requires static deltas needs no summary for the list. The plan keeps the
/// list for the deltas of the dependencies, as
/// [`DeltaPlan::take_edges`] gives it. `related` is the rule of
/// `[ex-ostrya] keep-detached-related` that the entry of the pull read.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn discover(
    repo: &Repo,
    source: &DeltaSource<'_>,
    advert: Option<&DeltaAdvert>,
    targets: &[(String, Checksum)],
    opts: &PullOptions,
    tips: TipChecks<'_>,
    edges: Option<Edges>,
    verification: &Verification,
    related: RelatedRule,
    progress: &PullCounters,
) -> Result<DeltaPlan> {
    if opts.disable_static_deltas {
        return Ok(DeltaPlan::default());
    }
    if let Some(edges) = edges {
        if opts.flags.contains(PullFlags::COMMIT_ONLY) {
            return Ok(DeltaPlan::default());
        }
        return discover_chain(
            repo,
            source,
            targets,
            opts,
            tips,
            edges,
            verification,
            related,
            progress,
        )
        .await;
    }
    let mut jobs = HashMap::new();
    // If there is no summary, nothing advertises a delta, so a pull that
    // requires a delta fails whatever it looks for.
    if opts.require_static_deltas && advert.is_none() {
        return Err(no_summary_error());
    }
    if opts.flags.contains(PullFlags::COMMIT_ONLY)
        || (!opts.subpaths.is_empty()
            && repo.mode() == RepoMode::Archive
            && !opts.require_static_deltas)
    {
        return Ok(DeltaPlan::default());
    }
    for (ref_name, to) in targets {
        if jobs.contains_key(to) || complete_here(repo, to).await? {
            continue;
        }
        let tip = repo
            .resolve_relpath_tip(tips.place.ref_path(ref_name)?)
            .await?;
        let from = source_commit(repo, tip, to).await?;
        let scratch = scratch_allowed(tip, from, to);
        if let Some(found) = discover_one(
            repo,
            source,
            advert,
            None,
            ref_name,
            from,
            scratch,
            *to,
            &HashMap::new(),
            opts,
            Some(verification),
            progress,
            None,
        )
        .await?
        {
            jobs.insert(*to, found.fetched.into_job(repo).await?);
        }
    }
    Ok(DeltaPlan {
        jobs,
        ..DeltaPlan::default()
    })
}

/// The search for the delta of one dependency of a pull.
///
/// The module `dependency` builds it from the paired entries of the
/// dependency.
pub(crate) struct DependencyLookup {
    /// The dependency.
    pub(crate) checksum: Checksum,
    /// The dependency in an error: `<name> of <ref>`. `<ref>` is the first
    /// target whose chain names the dependency, and `<name>` is the name of
    /// the entry nearest to its tip. If no chain of a target names the
    /// dependency, `<ref>` is the first target of the pull, and `<name>` comes
    /// from the commit of the pull with the lowest checksum that names it.
    pub(crate) subject: String,
    /// The first paired entry that this repository holds complete.
    pub(crate) from: Option<Checksum>,
    /// `true` if this repository holds no paired entry complete, so the pull
    /// can take the from-scratch delta.
    pub(crate) scratch: bool,
}

/// The deltas that [`discover_dependencies`] found, keyed by dependency.
///
/// A delta from a remote keeps a [`DependencyHead`] on the heap, and its
/// checked superblock and the commit that it carries in the record file of
/// the search. The step of the commit reads the commit from the record file,
/// and takes the fallbacks of the head. The head then keeps the number of
/// parts and the range of the superblock alone. Just before the parts of the
/// delta, [`load_job`] parses the superblock again from the record file, and
/// the job lives until [`release_job`] after the last part. The run loads at
/// most [`PART_CAP`] jobs at a time, so the heap holds at most that number of
/// jobs, whatever the number of dependencies. A head whose delta has no part,
/// or whose commit needs no delta, goes in the step of the commit.
///
/// A delta from a local source keeps no bytes: [`take_job`] reads its
/// superblock from the source again, checks it against its digest, and parses
/// it, just before the pull applies it.
///
/// [`load_job`]: DependencyDeltas::load_job
/// [`release_job`]: DependencyDeltas::release_job
/// [`take_job`]: DependencyDeltas::take_job
#[derive(Default)]
pub(crate) struct DependencyDeltas {
    /// The head of the delta of each dependency, from a remote. The steps of
    /// the run share the map.
    heads: Mutex<HashMap<Checksum, DependencyHead>>,
    /// The file of the checked superblocks and commits from a remote.
    store: Option<RecordStore>,
    /// The jobs that the run loaded and did not release yet.
    live: Mutex<HashMap<Checksum, Arc<DeltaJob>>>,
    /// The source commit and the superblock digest of the delta of each
    /// dependency, from a local source.
    local: HashMap<Checksum, (Option<Checksum>, Option<Checksum>)>,
}

/// What [`DependencyDeltas`] keeps on the heap of the delta of one dependency
/// from a remote, until the run releases its job.
struct DependencyHead {
    /// The source commit of the delta, or `None` for a from-scratch delta.
    from: Option<Checksum>,
    /// The range of the checked superblock in the record file.
    superblock: Range<u64>,
    /// The number of parts of the delta, inline parts and part files.
    parts: usize,
    /// The range in the record file of the normal-form bytes of the
    /// dependency, which the superblock carries. `None` after the step of the
    /// commit.
    commit: Option<Range<u64>>,
    /// The objects that the delta names and does not carry, as
    /// [`DeltaJob::fallbacks`] gives them. Empty after the step of the commit.
    fallbacks: Vec<ObjectName>,
}

impl DependencyDeltas {
    /// Returns `true` if no dependency has a delta.
    pub(crate) fn is_empty(&self) -> bool {
        self.heads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_empty()
            && self.local.is_empty()
    }

    /// Reads the commit bytes of the delta of `dependency` from a remote
    /// from the record file, on the blocking pool. Returns `None` if the
    /// dependency has no delta or the step of the commit took the delta.
    ///
    /// Discovery wrote the bytes after the parse of the superblock verified
    /// that they hash to `dependency`.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if the record file cannot be read.
    pub(crate) async fn commit_bytes(&self, dependency: &Checksum) -> Result<Option<Vec<u8>>> {
        let range = self
            .heads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(dependency)
            .and_then(|head| head.commit.clone());
        match (range, &self.store) {
            (Some(range), Some(store)) => store.read(range).await.map(Some),
            _ => Ok(None),
        }
    }

    /// Returns the number of parts and the fallbacks of the delta of
    /// `dependency` from a remote, or `None` if it has no delta.
    ///
    /// The step of the commit calls it one time. The head then drops the
    /// range of the commit and its fallbacks, and keeps the number of parts
    /// and the range of the superblock alone. A delta with no part has no
    /// load step, so its head goes here.
    pub(crate) fn take_commit_delta(
        &self,
        dependency: &Checksum,
    ) -> Option<(usize, Vec<ObjectName>)> {
        let mut heads = self.heads.lock().unwrap_or_else(PoisonError::into_inner);
        let head = heads.get_mut(dependency)?;
        let taken = (head.parts, std::mem::take(&mut head.fallbacks));
        head.commit = None;
        if head.parts == 0 {
            heads.remove(dependency);
        }
        Some(taken)
    }

    /// Parses the job of the delta of `dependency` from the record file, and
    /// keeps it until [`release_job`](DependencyDeltas::release_job).
    ///
    /// These are the bytes that discovery checked, so the parse checks no
    /// digest and no inline part again. Discovery checked no signature of the
    /// superblock, and the parse checks none. A delta that no
    /// summary advertised has no digest, and the bytes are still the bytes
    /// that discovery checked. The call sends no request.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] if the record file cannot be read.
    /// - [`Error::InvalidFormat`] if discovery kept no superblock of
    ///   `dependency`.
    pub(crate) async fn load_job(&self, repo: &Repo, dependency: &Checksum) -> Result<()> {
        let kept = self
            .heads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(dependency)
            .map(|head| (head.from, head.superblock.clone()));
        let (Some((from, range)), Some(store)) = (kept, &self.store) else {
            return Err(Error::InvalidFormat(format!(
                "the static delta to {dependency}: discovery kept no superblock"
            )));
        };
        let fetched = parse_kept(store, range, from, *dependency).await?;
        let mut job = fetched.into_job(repo).await?;
        // The step of the commit read the commit bytes and the fallbacks. The
        // parts read neither, so the job keeps neither.
        job.commit_bytes = Arc::default();
        job.fallbacks = Vec::new();
        self.live
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(*dependency, Arc::new(job));
        Ok(())
    }

    /// Returns the job of the delta of `dependency` that
    /// [`load_job`](DependencyDeltas::load_job) parsed, or `None` if the job
    /// is not loaded.
    pub(crate) fn live_job(&self, dependency: &Checksum) -> Option<Arc<DeltaJob>> {
        self.live
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(dependency)
            .cloned()
    }

    /// Drops the job and the head of the delta of `dependency`: after its
    /// last part, or in the step of a commit that needs no delta.
    pub(crate) fn release_job(&self, dependency: &Checksum) {
        self.live
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(dependency);
        self.heads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(dependency);
    }

    /// Returns the number of loaded jobs.
    #[cfg(test)]
    pub(crate) fn live_jobs(&self) -> usize {
        self.live
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .len()
    }

    /// Returns `true` if the head of the delta of `dependency` still keeps
    /// the range of its commit or a fallback.
    #[cfg(test)]
    pub(crate) fn holds_commit_data(&self, dependency: &Checksum) -> bool {
        self.heads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(dependency)
            .is_some_and(|head| head.commit.is_some() || !head.fallbacks.is_empty())
    }

    /// Returns `true` if the delta of `dependency` from a remote has a head.
    #[cfg(test)]
    pub(crate) fn has_head(&self, dependency: &Checksum) -> bool {
        self.heads
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .contains_key(dependency)
    }

    /// Returns the deltas `deltas` of the local source `src`, kept as the
    /// search of [`discover_dependencies`] keeps the deltas from a remote: in
    /// one shared record file in `tmp/` of `repo`, with a head of each.
    #[cfg(test)]
    pub(crate) async fn kept_from(
        repo: &Repo,
        src: &Repo,
        deltas: &[(Option<Checksum>, Checksum)],
    ) -> DependencyDeltas {
        let shared = Arc::new(Mutex::new(RecordStore::for_dependencies(repo)));
        let progress = PullCounters::new(None);
        let mut found = DependencyDeltas::default();
        for (from, to) in deltas {
            let (fetched, kept) = fetch_job(
                &DeltaSource::Local(src),
                *from,
                *to,
                None,
                None,
                &progress,
                Some(Keep::Shared(&shared)),
            )
            .await
            .unwrap()
            .unwrap();
            let kept = kept.unwrap();
            found.heads.get_mut().unwrap().insert(
                *to,
                fetched.into_head(*from, kept.superblock, kept.commit.unwrap()),
            );
        }
        found.store = Arc::into_inner(shared).map(|store| store.into_inner().unwrap());
        found
    }

    /// Takes the job of the delta of `dependency` from a local source, or
    /// returns `None` if it has no such delta. The call reads the superblock
    /// from `source` again and checks it against its digest.
    ///
    /// # Errors
    ///
    /// - [`Error::ChecksumMismatch`] if the superblock does not have its
    ///   digest.
    /// - [`Error::InvalidFormat`] if the source no longer holds the
    ///   superblock.
    pub(crate) async fn take_job(
        &mut self,
        repo: &Repo,
        source: &DeltaSource<'_>,
        dependency: &Checksum,
    ) -> Result<Option<DeltaJob>> {
        let Some((from, digest)) = self.local.remove(dependency) else {
            return Ok(None);
        };
        let DeltaSource::Local(src) = source else {
            return Err(Error::InvalidFormat(format!(
                "static delta {}: discovery kept no superblock",
                delta_name(from.as_ref(), dependency)
            )));
        };
        let fetched = read_local_superblock(src, from, *dependency, digest).await?;
        fetched.into_job(repo).await.map(Some)
    }
}

/// Finds the delta of each dependency of `lookups`, keyed by the dependency.
///
/// The search of each dependency is the search of [`discover_one`] for a
/// target, with the `from` and the scratch rule of its lookup. With `edges`,
/// the search takes one delta of the list to the dependency, and plans no
/// chain. Else it reads the delta index of the dependency and the map of
/// `advert`, as for a target, or requests the delta by name if `advert` is
/// `None`. The call adds the part files of each delta and their declared
/// sizes to the planned counts in `progress`.
///
/// The searches check no signature of a superblock. Field 2 of the commit
/// that names a dependency holds its checksum, the `to` of the search. The
/// parse of a superblock checks that the commit that it carries hashes to
/// its `to`, and [`fetch_job`] checks that `to` against the search. The
/// digest, the `from`, and the inline parts get their checks, as for a
/// target.
///
/// For a remote, the searches run together, up to the number of requests
/// that the session admits. For a local source, they run one at a time. The
/// call takes the results in the order of `lookups`, so the first error in
/// that order is the error of the call.
///
/// For a remote, the searches share one record file, which opens at the
/// first write. Each search writes the superblock that it fetched to the file
/// after the digest check, and the commit that the superblock carries after
/// the parse, as [`fetch_job`] states. The file has the limit
/// [`MAX_RECORD_FILE`]. A failed check fails the pull, so the file holds
/// checked bytes. The result keeps a [`DependencyHead`] of each delta, and
/// the parsed superblock drops. A search holds the superblock that it fetched
/// and the parse of it until its checks end, so the heap holds at most one
/// superblock and its parse for each search in flight. A delta from a local
/// source keeps no bytes, as [`DependencyDeltas`] states.
///
/// After a search fails, the call starts no further search. The searches in
/// flight end, so the first error in the order of `lookups` is still the
/// error of the call.
///
/// `known` holds the completeness of commits that the caller checked. The
/// searches check no such commit again. The caller passes no lookup for a
/// dependency that this repository holds complete, and makes no call for a
/// pull with [`disable_static_deltas`](PullOptions::disable_static_deltas)
/// set.
///
/// # Errors
///
/// - The errors of [`discover_one`], except [`Error::Signature`]. Under
///   [`require_static_deltas`](PullOptions::require_static_deltas), a
///   dependency with no delta gives [`Error::Pull`] with the subject of its
///   lookup.
/// - [`Error::Pull`] if the superblocks and the commits from a remote would
///   pass the limit of the record file. The pull then does not fetch loose.
/// - [`Error::Io`] if the record file cannot be opened or written.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn discover_dependencies(
    repo: &Repo,
    source: &DeltaSource<'_>,
    advert: Option<&DeltaAdvert>,
    edges: Option<&Edges>,
    lookups: Vec<DependencyLookup>,
    known: &HashMap<Checksum, bool>,
    opts: &PullOptions,
    progress: &PullCounters,
) -> Result<DependencyDeltas> {
    let limit = match source {
        DeltaSource::Remote(remote) => remote.max_outstanding(),
        DeltaSource::Local(_) => 1,
    };
    // The searches share the record file. Each search reserves its ranges
    // under the lock, and writes them on the blocking pool. The file opens at
    // the first write.
    let shared = match source {
        DeltaSource::Remote(_) => Some(Arc::new(Mutex::new(RecordStore::for_dependencies(repo)))),
        DeltaSource::Local(_) => None,
    };
    let store = shared.as_ref();
    let mut found = DependencyDeltas::default();
    let mut ready: Vec<Option<Result<Option<Kept>>>> = Vec::new();
    ready.resize_with(lookups.len(), || None);
    let mut next = 0;
    let mut pending = lookups.into_iter().enumerate();
    let mut slots = Slots::new(limit);
    // A failed search fails the call, so the call starts no search after it.
    let mut failed = false;
    loop {
        while !failed
            && slots.has_room()
            && let Some((at, lookup)) = pending.next()
        {
            slots.push(async move {
                let kept = async {
                    let Some(delta) = discover_one(
                        repo,
                        source,
                        advert,
                        edges,
                        &lookup.subject,
                        lookup.from,
                        lookup.scratch,
                        lookup.checksum,
                        known,
                        opts,
                        None,
                        progress,
                        store,
                    )
                    .await?
                    else {
                        return Ok(None);
                    };
                    let parts = delta.fetched.parts();
                    let delta = match delta.kept {
                        Some(KeptRanges {
                            superblock,
                            commit: Some(commit),
                        }) => Found::Head(delta.fetched.into_head(delta.from, superblock, commit)),
                        _ => Found::Local(delta.from, delta.digest),
                    };
                    Ok(Some(Kept {
                        dependency: lookup.checksum,
                        parts,
                        delta,
                    }))
                };
                (at, kept.await)
            });
        }
        let Some((at, result)) = slots.next_ready().await else {
            drop(slots);
            // Each search ended, and with it each blocking call that held the
            // store.
            found.store = shared
                .and_then(Arc::into_inner)
                .map(|store| store.into_inner().unwrap_or_else(PoisonError::into_inner));
            return Ok(found);
        };
        failed |= result.is_err();
        ready[at] = Some(result);
        while let Some(result) = ready.get_mut(next).and_then(Option::take) {
            next += 1;
            let Some(kept) = result? else {
                continue;
            };
            progress.parts_planned(kept.parts.0, kept.parts.1);
            match kept.delta {
                Found::Head(head) => {
                    found
                        .heads
                        .get_mut()
                        .unwrap_or_else(PoisonError::into_inner)
                        .insert(kept.dependency, head);
                }
                Found::Local(from, digest) => {
                    found.local.insert(kept.dependency, (from, digest));
                }
            }
        }
    }
}

/// The delta of one dependency that a search of [`discover_dependencies`]
/// found, with the number of its part files and their declared sizes.
struct Kept {
    /// The dependency.
    dependency: Checksum,
    /// The number of part files of the delta and the sum of their declared
    /// sizes.
    parts: (u32, u64),
    /// What the pull keeps of the delta.
    delta: Found,
}

/// What [`DependencyDeltas`] keeps of the delta of one dependency.
enum Found {
    /// The head, from a remote.
    Head(DependencyHead),
    /// The source commit and the superblock digest, from a local source.
    Local(Option<Checksum>, Option<Checksum>),
}

/// Plans the chains of static deltas to the targets over `edges`, and fetches
/// and verifies the superblock of each step.
///
/// The targets are the commits of `targets` that this repository does not
/// hold complete, each once, in the order of the refs, as [`chain_targets`]
/// states. The planner of the sibling module `chain` finds and merges the
/// chains.
///
/// Discovery fetches the steps of the plan in level order, and the steps to
/// the targets last. For each step it fetches the superblock, checks its
/// digest, its source and target, its signatures, and its inline parts, and
/// keeps a record. Then it drops the parsed superblock, and keeps only the
/// bytes of the commit for the check of the commit. For the commit of each
/// step it also fetches or reads the `.commitmeta`, as [`fetch_step`] and
/// [`check_step_commit`] state, and checks the commit, as
/// [`check_step_commit`] states. A commit gets one check, also if a later
/// plan makes it from another step. For a local source, discovery makes no
/// timestamp check, because a local pull has none.
///
/// For a local source, discovery also reads field 2 of the commit of each
/// step and checks the format of its entries. It keeps the entries of each
/// intermediate commit of the last plan.
/// [`DeltaPlan::take_dependencies`] gives them to the pull, which follows the
/// dependencies of each intermediate commit.
///
/// If the source does not hold the superblock of a step, discovery excludes
/// that delta and plans again. It fetches only the steps that it did not
/// fetch before. Each pass excludes one delta, so the loop ends. The planner
/// limits the number of deltas that it plans again around. At the end
/// discovery drops each record that the last plan does not use. A target
/// with no chain gets no record, and the pull fetches its objects loose.
///
/// # Errors
///
/// - [`Error::Pull`] if the pull requires static deltas and a plan has no
///   chain to a target. A delta from scratch to the target that the scratch
///   rule refuses counts as a chain, and the pull fetches loose.
/// - [`Error::ChecksumMismatch`] if a superblock does not have its listed
///   digest.
/// - [`Error::Pull`] if a superblock produces another commit, or from
///   another commit, than its entry of the list.
/// - [`Error::Signature`] if the signatures of a superblock or of a commit
///   of a chain fail the policy of the pull.
/// - [`Error::Pull`] if a requested ref that names a commit of a chain fails
///   the ref-binding check or the timestamp check.
/// - [`Error::Pull`] if the superblocks and the `.commitmeta` files of a
///   remote would pass the limit of the record file, [`MAX_RECORD_FILE`].
///   The pull then does not fetch loose.
/// - [`Error::InvalidFormat`] if a superblock or an inline part is
///   malformed.
/// - [`Error::InvalidRelated`] if field 2 of the commit of a step of a local
///   source has an entry with an empty name or with a checksum that is not 32
///   bytes. Discovery reports it after the checks of the commit, as
///   [`check_step_commit`] states.
#[allow(clippy::too_many_arguments)]
async fn discover_chain(
    repo: &Repo,
    source: &DeltaSource<'_>,
    targets: &[(String, Checksum)],
    opts: &PullOptions,
    tips: TipChecks<'_>,
    edges: Edges,
    verification: &Verification,
    related: RelatedRule,
    progress: &PullCounters,
) -> Result<DeltaPlan> {
    let (wanted, names) = chain_targets(repo, targets, tips.place).await?;
    if wanted.is_empty() {
        return Ok(DeltaPlan {
            edges: Some(edges),
            ..DeltaPlan::default()
        });
    }
    let target_commits: Vec<Checksum> = wanted.iter().map(|(target, _)| *target).collect();
    let (edges, complete) = complete_sources(repo, edges, &target_commits).await?;
    let (mut search, mut pass) = ostrya_rt::unblock(move || {
        let search = ChainSearch::new(edges, complete, wanted);
        let pass = Pass::new(&search);
        (search, pass)
    })
    .await;

    let mut store = match source {
        DeltaSource::Remote(_) => Some(RecordStore::new(repo)),
        DeltaSource::Local(_) => None,
    };
    // The requested refs of each target, in the order of the refs. Discovery
    // makes the checks of these refs when it checks the commit.
    let mut refs_of: HashMap<Checksum, Vec<&str>> = HashMap::new();
    for (name, target) in targets {
        refs_of.entry(*target).or_default().push(name.as_str());
    }
    let ctx = CheckCtx {
        repo,
        source,
        localcache: &opts.localcache_repos,
        verification,
        related,
        progress,
        tips,
    };
    // The record of each fetched step, by list index.
    let mut records: HashMap<usize, StepRecord> = HashMap::new();
    // The check of each commit, by commit. A commit keeps its check when a
    // later plan makes it from another step.
    let mut checked: HashMap<Checksum, Checked> = HashMap::new();
    'plan: loop {
        if opts.require_static_deltas {
            for ((target, planned), name) in search.targets().zip(&names) {
                if !pass.plan.steps.contains_key(target) && *planned != Planned::Declined {
                    return Err(none_found_error(name, target));
                }
            }
        }
        for commit in std::mem::take(&mut pass.order) {
            let index = pass.plan.steps[&commit];
            // Discovery checked the commit of each step that it fetched.
            if records.contains_key(&index) {
                continue;
            }
            let check = !checked.contains_key(&commit);
            let delta = *search.edges().delta(index);
            let Some(step) = fetch_step(&ctx, &delta, check, store.as_mut()).await? else {
                (search, pass) = ostrya_rt::unblock(move || {
                    search.exclude(index);
                    let pass = Pass::new(&search);
                    (search, pass)
                })
                .await;
                continue 'plan;
            };
            records.insert(
                index,
                StepRecord {
                    delta,
                    parts: step.fetched.parts(),
                    superblock: step.kept,
                    detached: Detached::NotChecked,
                },
            );
            let FetchedStep {
                fetched, detached, ..
            } = step;
            // Only the commit bytes stay for the check. The rest of the parsed
            // superblock drops here.
            let commit_bytes = fetched.into_commit_bytes();
            if check {
                let refs = refs_of.get(&commit).map(Vec::as_slice).unwrap_or_default();
                let result =
                    check_step_commit(&ctx, &commit, commit_bytes, refs, detached, store.as_mut())
                        .await?;
                checked.insert(commit, result);
            }
        }
        break;
    }

    // A local source counts the `.commitmeta` of each intermediate commit of
    // the last plan alone, by the rule of the import of the pull.
    if let DeltaSource::Local(src) = source {
        for commit in pass.plan.levels.iter().flatten() {
            let size = match checked.get(commit).map(|check| &check.local) {
                Some(CheckedDetached::Read { at: 0, len, .. }) => Some(*len),
                Some(CheckedDetached::Absent | CheckedDetached::Read { .. }) => None,
                Some(CheckedDetached::Unchecked) | None => {
                    src.held_object_size(ObjectType::CommitMeta, commit).await?
                }
            };
            if let Some(size) = size {
                count_fetched(progress, ObjectType::CommitMeta, size);
            }
        }
    }

    // The pull follows the dependencies of the intermediate commits alone.
    // The walk of the commit chains reads field 2 of each target again.
    let intermediate: HashSet<&Checksum> = pass.plan.levels.iter().flatten().collect();
    let mut kept_records = HashMap::with_capacity(pass.plan.steps.len());
    let mut dependencies = HashMap::new();
    for (commit, index) in &pass.plan.steps {
        let Some(mut record) = records.remove(index) else {
            continue;
        };
        if let Some(check) = checked.remove(commit) {
            record.detached = Detached::Checked {
                kept: check.kept,
                filtered: check.filtered,
                local: check.local,
            };
            if intermediate.contains(commit) && !check.dependencies.is_empty() {
                dependencies.insert(*commit, check.dependencies);
            }
        }
        kept_records.insert(*commit, record);
    }
    Ok(DeltaPlan {
        jobs: HashMap::new(),
        records: kept_records,
        levels: pass.plan.levels,
        dependencies,
        store,
        edges: Some(search.into_edges()),
    })
}

/// The plan of one pass of the discovery of a chain, with the order in which
/// discovery fetches its steps.
struct Pass {
    plan: ChainPlan,
    /// The commits of the plan in fetch order: the levels in order, then the
    /// targets that no step reads, in the order of the targets.
    order: Vec<Checksum>,
}

impl Pass {
    /// Merges the chains of `search`, and orders the steps of the result.
    fn new(search: &ChainSearch) -> Pass {
        let plan = search.merged();
        let intermediate: HashSet<Checksum> = plan.levels.iter().flatten().copied().collect();
        let order = plan
            .levels
            .iter()
            .flatten()
            .copied()
            .chain(
                search
                    .targets()
                    .map(|(target, _)| *target)
                    .filter(|target| {
                        plan.steps.contains_key(target) && !intermediate.contains(target)
                    }),
            )
            .collect();
        Pass { plan, order }
    }
}

/// Returns each commit of `targets` that this repository does not hold
/// complete, once, in the order of the refs, with its scratch rule. Also
/// returns the first ref that names each commit, for an error.
///
/// A step from scratch to a target is allowed if the scratch rule allows it
/// for one of the refs that name the target. The checks of the commits run on
/// the blocking pool in batches: one pass for the targets, and one for the
/// commits that the refs name here.
async fn chain_targets<'t>(
    repo: &Repo,
    targets: &'t [(String, Checksum)],
    place: RefPlace<'_>,
) -> Result<(Vec<(Checksum, bool)>, Vec<&'t str>)> {
    let mut unique: Vec<Checksum> = Vec::new();
    let mut seen: HashSet<Checksum> = HashSet::new();
    for (_, to) in targets {
        if seen.insert(*to) {
            unique.push(*to);
        }
    }
    let held: HashSet<Checksum> = check_complete(repo, &unique)
        .await?
        .into_iter()
        .filter_map(|(commit, complete)| complete.then_some(commit))
        .collect();
    let mut tips: Vec<(&str, Checksum, Option<Checksum>)> = Vec::new();
    for (ref_name, to) in targets {
        if held.contains(to) {
            continue;
        }
        let tip = repo.resolve_relpath_tip(place.ref_path(ref_name)?).await?;
        tips.push((ref_name.as_str(), *to, tip));
    }
    // A tip can be the source commit only if it is not the target.
    let mut candidates: Vec<Checksum> = Vec::new();
    let mut seen: HashSet<Checksum> = HashSet::new();
    for (_, to, tip) in &tips {
        if let Some(tip) = tip
            && tip != to
            && seen.insert(*tip)
        {
            candidates.push(*tip);
        }
    }
    let complete: HashSet<Checksum> = check_complete(repo, &candidates)
        .await?
        .into_iter()
        .filter_map(|(commit, complete)| complete.then_some(commit))
        .collect();
    let mut wanted: Vec<(Checksum, bool)> = Vec::new();
    let mut names: Vec<&str> = Vec::new();
    let mut position: HashMap<Checksum, usize> = HashMap::new();
    for (name, to, tip) in tips {
        let from = tip.filter(|tip| *tip != to && complete.contains(tip));
        let scratch = scratch_allowed(tip, from, &to);
        match position.get(&to) {
            Some(&i) => wanted[i].1 |= scratch,
            None => {
                position.insert(to, wanted.len());
                wanted.push((to, scratch));
                names.push(name);
            }
        }
    }
    Ok((wanted, names))
}

/// What the check of the commit of each step reads, for one discovery.
struct CheckCtx<'a> {
    /// The repository that the pull writes into.
    repo: &'a Repo,
    source: &'a DeltaSource<'a>,
    /// The localcache repositories of the pull, in the order of the reads.
    localcache: &'a [Repo],
    verification: &'a Verification,
    /// The rule of `[ex-ostrya] keep-detached-related` of the destination.
    /// Discovery applies it to the `.commitmeta` of a commit that it checks
    /// from a remote, if the check of the signatures parses the
    /// `.commitmeta`.
    related: RelatedRule,
    progress: &'a PullCounters,
    /// The checks of each requested ref that names a commit.
    tips: TipChecks<'a>,
}

/// A step whose superblock [`fetch_step`] fetched and verified.
struct FetchedStep {
    fetched: FetchedDelta,
    /// The range of the raw superblock in the record file.
    kept: Option<Range<u64>>,
    /// The `.commitmeta` of the commit of the step, if the fetch got it with
    /// the superblock. The inner `None` is a `.commitmeta` that no repository
    /// holds.
    detached: Option<Option<Vec<u8>>>,
}

/// Fetches and verifies the superblock of the step `delta`, as [`fetch_job`]
/// states, and returns `None` if the source does not hold it.
///
/// If `pair` is set and the source is a remote over a stream session, the
/// function can also get the `.commitmeta` of the commit of the step. If a
/// localcache repository holds the `.commitmeta`, the function sends the
/// request of the superblock alone and reads no `.commitmeta`. Else it sends
/// the request of the superblock and the request of the `.commitmeta` as one
/// pair, the superblock first, so the two cost one round trip. The reply of
/// the `.commitmeta` arrives while the function parses and verifies the
/// superblock. So the heap then holds one superblock, one `.commitmeta`, and
/// the parse of the superblock: up to [`MAX_SUPERBLOCK`] plus
/// [`MAX_METADATA_SIZE`] bytes of raw data.
///
/// A `.commitmeta` that the remote serves adds one to the metadata count,
/// also if the remote does not hold the superblock. A failure of the
/// superblock reports before a failure of the `.commitmeta`. If the remote
/// does not hold the superblock, the function drops the `.commitmeta`. If a
/// later plan makes the same commit from another delta, discovery requests
/// the `.commitmeta` again and counts it again. So for the same pull, the
/// metadata count over a stream session can be higher than over HTTP: one
/// more for each missing superblock whose commit has a `.commitmeta` on the
/// remote.
///
/// If the function gets no `.commitmeta`, [`check_step_commit`] reads it
/// after the superblock: from the first localcache repository that holds it,
/// else from the remote. This is so if `pair` is not set, for each other
/// source, and if a localcache repository holds the `.commitmeta`.
async fn fetch_step(
    ctx: &CheckCtx<'_>,
    delta: &AdvertisedDelta,
    pair: bool,
    store: Option<&mut RecordStore>,
) -> Result<Option<FetchedStep>> {
    let job = fetch_job(
        ctx.source,
        delta.from,
        delta.to,
        Some(delta.superblock),
        Some(ctx.verification),
        ctx.progress,
        store.map(Keep::Own),
    );
    let (job, detached) = match ctx.source {
        DeltaSource::Remote(remote) if pair && matches!(remote.transfer(), Transfer::Stream(_)) => {
            let name = ObjectName::new(delta.to, ObjectType::CommitMeta);
            match cached_source(ctx.localcache, name).await? {
                Some(_) => (job.await, None),
                None => {
                    let (job, detached) = futures_lite::future::zip(
                        job,
                        fetch_remote_detached(remote, ctx.progress, &delta.to),
                    )
                    .await;
                    (job, Some(detached))
                }
            }
        }
        _ => (job.await, None),
    };
    let job = job?;
    let detached = detached.transpose()?;
    Ok(job.map(|(fetched, kept)| FetchedStep {
        fetched,
        kept: kept.map(|kept| kept.superblock),
        detached,
    }))
}

/// Checks the commit `commit` of a step, and returns the check.
///
/// The check covers the signatures of the commit, and the ref-binding check
/// and the timestamp check of each ref of `refs`, in order. `refs` are the
/// requested refs that name the commit. They are empty for a commit that
/// is an intermediate commit alone. The checks of the refs run after the
/// check of the signatures, also if the policy checks no commit.
///
/// `commit_bytes` are the bytes of the commit that its superblock carries.
/// The parse of the superblock verified that they hash to `commit`. The
/// checks of the refs parse them on the blocking pool. Under
/// [`TimestampCheck::CurrentRef`](crate::pull::TimestampCheck::CurrentRef),
/// the timestamp check reads the commit of each ref on the blocking pool too.
/// The check reads the `.commitmeta` that the pull puts in place, as the
/// check of a fetched commit does.
///
/// - From a remote, `detached` is the `.commitmeta` that [`fetch_step`] got
///   with the superblock. If it is `None`, the `.commitmeta` comes from the
///   first localcache repository that holds it, else from the remote. A file
///   that the remote serves adds one to the metadata count. If the policy
///   checks commits and the rule of `[ex-ostrya] keep-detached-related` drops
///   `ostrya.related`, the check parses the bytes, and the rule reads that
///   parse right after the check, on the blocking pool. The record file keeps
///   the result of the rule. A rule that keeps no property keeps no range. Else
///   the record file keeps the verified bytes, and the commit step runs the
///   rule over them. The result holds the range in the record file.
/// - From a local source, the `.commitmeta` comes from the source, else from
///   the first localcache repository that holds it. The reads and the parse
///   run in one call on the blocking pool. The record keeps no bytes. If the
///   policy checks no commit, discovery reads no `.commitmeta`. The result
///   holds the position of the source that holds the file, the size of the
///   file, and its SHA-256. The import of the commit compares the SHA-256
///   with the file that the sources hold then, and fails on other bytes.
///   [`discover_chain`] counts the file at its end, for each intermediate
///   commit of the last plan alone.
///
/// If no repository holds a `.commitmeta`, the check reads the detached
/// metadata of this repository.
///
/// For a local source, the check also reads field 2 of the commit and checks
/// the format of its entries. It reports a defective entry after the other
/// checks, and the result holds the entries. One call on the blocking pool
/// decodes field 2 and makes the parse for the checks of the refs.
///
/// # Errors
///
/// - [`Error::Signature`] if the signatures fail the policy of the pull.
/// - [`Error::Pull`] if the ref binding of the commit does not name a ref
///   of `refs`, or if the commit is older than the timestamp check allows.
/// - [`Error::Pull`] if the `.commitmeta` would pass the limit of the record
///   file.
/// - [`Error::InvalidRelated`] if field 2 of the commit from a local source
///   has an entry with an empty name or with a checksum that is not 32 bytes.
async fn check_step_commit(
    ctx: &CheckCtx<'_>,
    commit: &Checksum,
    commit_bytes: Vec<u8>,
    refs: &[&str],
    detached: Option<Option<Vec<u8>>>,
    store: Option<&mut RecordStore>,
) -> Result<Checked> {
    // A local pull follows the dependencies of each commit that a step makes,
    // so for a local source the check reads field 2 of the commit and checks
    // its format. The bytes can be as large as `MAX_METADATA_SIZE`, so one
    // call on the blocking pool decodes field 2 alone, and parses the commit
    // for the checks of the refs. The check takes each result at its own
    // point.
    let (commit_bytes, local_parse) = match ctx.source {
        DeltaSource::Local(_) => {
            let checksum = *commit;
            let parse = !refs.is_empty();
            ostrya_rt::unblock(move || {
                let dependencies = related::parse_dependencies(&commit_bytes).and_then(|entries| {
                    related::checked_entries(RelatedField::Dependencies, Some(checksum), entries)
                });
                let parsed = parse.then(|| Commit::parse(&commit_bytes));
                (commit_bytes, Some((parsed, dependencies)))
            })
            .await
        }
        DeltaSource::Remote(_) => (commit_bytes, None),
    };
    // The signature check gives the bytes to the blocking pool in an `Arc`,
    // with no copy.
    let commit_bytes = Arc::new(commit_bytes);
    let (parsed, dependencies) = local_parse.unzip();
    let mut checked = match ctx.source {
        DeltaSource::Remote(remote) => {
            let detached = match detached {
                Some(detached) => detached,
                None => {
                    super::http::fetch_detached_metadata(
                        remote,
                        ctx.localcache,
                        ctx.progress,
                        commit,
                    )
                    .await?
                }
            };
            // If the check parses the `.commitmeta`, the rule reads that parse
            // right after the check, and the record file keeps its result.
            // Else the record file keeps the bytes of the source, and the
            // commit step applies the rule to them. A parse error of the rule
            // then comes only for a commit that the pull fetches.
            let checked = check_commit_signatures_filtered(
                ctx.repo,
                ctx.verification,
                ctx.related,
                commit,
                (&commit_bytes).into(),
                detached,
            )
            .await?;
            let (detached, filtered) = match checked {
                Some(CheckedMeta::Filtered(kept)) => (kept, true),
                Some(CheckedMeta::Source(bytes)) => (Some(bytes), false),
                None => (None, false),
            };
            let kept = match (detached, store) {
                (Some(bytes), Some(store)) => Some(
                    store
                        .append(bytes, || format!("the .commitmeta of commit {commit}"))
                        .await?,
                ),
                _ => None,
            };
            Checked {
                kept,
                filtered,
                local: CheckedDetached::Unchecked,
                dependencies: Vec::new(),
            }
        }
        DeltaSource::Local(_) if !ctx.verification.checks_commits() => Checked {
            kept: None,
            filtered: false,
            local: CheckedDetached::Unchecked,
            dependencies: Vec::new(),
        },
        DeltaSource::Local(src) => {
            // The source comes first, then the localcache repositories, then
            // this repository. One call on the blocking pool reads and parses.
            let sources: Vec<Repo> = std::iter::once((*src).clone())
                .chain(ctx.localcache.iter().cloned())
                .collect();
            let local = check_local_commit_signatures(
                ctx.repo,
                ctx.verification,
                sources,
                commit,
                (&commit_bytes).into(),
            )
            .await?;
            Checked {
                kept: None,
                filtered: false,
                local,
                dependencies: Vec::new(),
            }
        }
    };
    if !refs.is_empty() {
        let parsed = match parsed.flatten() {
            Some(parsed) => parsed?,
            // The bytes can be as large as `MAX_METADATA_SIZE`, so the parse
            // runs on the blocking pool. The bytes drop there.
            None => ostrya_rt::unblock(move || Commit::parse(&commit_bytes)).await?,
        };
        check_tip_refs(ctx.repo, ctx.tips, commit, &parsed, refs).await?;
    }
    // A defective entry of field 2 fails the pull after the other checks of
    // the commit.
    if let Some(dependencies) = dependencies {
        checked.dependencies = dependencies?;
    }
    Ok(checked)
}

/// Reads the superblock of `record` again and parses it on the blocking
/// pool.
///
/// A record from a remote reads its range of `store`. These are the bytes
/// that discovery verified, so the parse checks no signature and no inline
/// part again. A record from a local source reads the superblock from the
/// source again and checks it against the listed digest. The same digest
/// gives the bytes that discovery verified.
async fn read_record(
    store: Option<&RecordStore>,
    source: &DeltaSource<'_>,
    record: &StepRecord,
) -> Result<FetchedDelta> {
    let AdvertisedDelta {
        from,
        to,
        superblock: digest,
    } = record.delta;
    match (&record.superblock, store, source) {
        (Some(range), Some(store), _) => parse_kept(store, range.clone(), from, to).await,
        (None, _, DeltaSource::Local(src)) => {
            read_local_superblock(src, from, to, Some(digest)).await
        }
        _ => Err(Error::InvalidFormat(format!(
            "static delta {}: discovery kept no superblock",
            delta_name(from.as_ref(), &to)
        ))),
    }
}

/// Reads the superblock of the delta from `from` to `to` at `range` of
/// `store`, and parses it on the blocking pool.
///
/// These are the bytes that discovery checked, so the parse checks no
/// digest, no signature, and no inline part again.
async fn parse_kept(
    store: &RecordStore,
    range: Range<u64>,
    from: Option<Checksum>,
    to: Checksum,
) -> Result<FetchedDelta> {
    let bytes = store.read(range).await?;
    let (parsed, _) =
        ostrya_rt::unblock(move || parse_superblock(bytes, None, None, from, to, false)).await?;
    parsed.verify(None).await
}

/// Reads the superblock of the delta from `from` to `to` from the local source
/// `src` again, checks it against `digest` if it is set, and parses it on the
/// blocking pool.
///
/// Discovery checked the superblock with the same digest, so the parse checks
/// no signature and no inline part again.
async fn read_local_superblock(
    src: &Repo,
    from: Option<Checksum>,
    to: Checksum,
    digest: Option<Checksum>,
) -> Result<FetchedDelta> {
    let path = format!(
        "{}/{SUPERBLOCK_FILE}",
        delta_relative_dir(from.as_ref(), &to)
    );
    let bytes = read_local(src, path, MAX_SUPERBLOCK)
        .await?
        .ok_or_else(|| {
            Error::InvalidFormat(format!(
                "static delta {}: the source repository holds no superblock",
                delta_name(from.as_ref(), &to)
            ))
        })?;
    let (parsed, _) =
        ostrya_rt::unblock(move || parse_superblock(bytes, digest, None, from, to, false)).await?;
    parsed.verify(None).await
}

/// Returns `true` if this repository holds a commit and each object that it
/// references.
pub(super) async fn complete_here(repo: &Repo, commit: &Checksum) -> Result<bool> {
    let repo = repo.clone();
    let commit = *commit;
    ostrya_rt::unblock(move || complete_here_blocking(&repo, &commit)).await
}

/// Runs [`complete_here`] on the calling thread.
pub(super) fn complete_here_blocking(repo: &Repo, commit: &Checksum) -> Result<bool> {
    Ok(repo.has_object_blocking(ObjectType::Commit, commit)?
        && repo.commit_state_blocking(commit)? == CommitState::Normal)
}

/// Returns the source commit of a from-to delta: `tip`, if this repository
/// holds it complete.
///
/// `tip` is the commit that the pulled ref names in this repository. If the
/// ref names no commit, or a commit whose objects are not all here, the
/// result is `None`. The pull then looks for a from-scratch delta. A delta
/// patches against the objects of the source commit, and a part fails to read
/// the objects that a partial commit does not hold.
///
/// If the ref names the target, the result is also `None`, because a delta
/// from a commit to itself carries nothing.
async fn source_commit(
    repo: &Repo,
    tip: Option<Checksum>,
    to: &Checksum,
) -> Result<Option<Checksum>> {
    let Some(current) = tip else {
        return Ok(None);
    };
    if current == *to || !complete_here(repo, &current).await? {
        return Ok(None);
    }
    Ok(Some(current))
}

/// The source from which a pull reads a delta.
pub(crate) enum DeltaSource<'a> {
    /// A remote, over HTTP or over ssh.
    Remote(&'a RemoteSource),
    /// Another local repository, read through its directory.
    Local(&'a Repo),
}

impl DeltaSource<'_> {
    /// Reads a whole delta index or superblock under `cap`, or `None` if it is
    /// absent.
    ///
    /// A remote source adds the bytes of a fetched body to the transferred
    /// count itself. For a local read, this method adds the bytes to
    /// `progress`.
    async fn read(&self, path: &str, cap: u64, progress: &PullCounters) -> Result<Option<Vec<u8>>> {
        match self {
            DeltaSource::Remote(source) => source.read_optional(path, Priority::High, cap).await,
            DeltaSource::Local(repo) => {
                let bytes = read_local(repo, path.to_owned(), cap).await?;
                if let Some(bytes) = &bytes {
                    progress.add_transferred(bytes.len() as u64);
                }
                Ok(bytes)
            }
        }
    }
}

/// Reads the whole regular file at `path` in the source repository `repo`, or
/// `None` if it is absent.
///
/// `path` is relative to the root of `repo`, and starts with `deltas/` or
/// `delta-indexes/`. The call opens the directory of that kind, and reads the
/// rest of the path below it with no symlink followed. A FIFO at the path
/// does not block the open. A file that is not a regular file, a symlink at a
/// component, and a file of more than `cap` bytes give
/// [`Error::InvalidFormat`].
async fn read_local(repo: &Repo, path: String, cap: u64) -> Result<Option<Vec<u8>>> {
    let root = repo.root_dir().clone();
    ostrya_rt::unblock(move || {
        let (kind, rest) = if let Some(rest) = path.strip_prefix("deltas/") {
            (RepoLayout::Deltas, rest)
        } else if let Some(rest) = path.strip_prefix("delta-indexes/") {
            (RepoLayout::DeltaIndexes, rest)
        } else {
            debug_assert!(false, "a local delta read names {path}");
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "a local delta read names a path outside deltas/ and delta-indexes/",
            )));
        };
        let Some(dir) = root.open_layout(kind).optional()? else {
            return Ok(None);
        };
        Ok(dir.read_capped(rest, cap).optional()?)
    })
    .await
}

/// Returns the error of a pull that requires static deltas from a source with
/// no summary.
///
/// The message is the message of the `ostree` command.
pub(crate) fn no_summary_error() -> Error {
    Error::Pull(
        "Fetch configured to require static deltas, but no summary deltas or delta index \
         found"
            .into(),
    )
}

/// Returns the error of a pull that requires a static delta and finds none.
///
/// The error names `subject` and the commit `to`. For a target, `subject` is
/// the ref, and the message is the message of the `ostree` command. For a
/// dependency, it is `<name> of <ref>`, as [`DependencyLookup::subject`]
/// states.
fn none_found_error(subject: &str, to: &Checksum) -> Error {
    Error::Pull(format!(
        "Static deltas required, but none found for {subject} to {to}"
    ))
}

/// The delta that an advertised map offers for one target commit.
#[derive(Debug, PartialEq, Eq)]
enum Choice {
    /// The delta from `from` (`None` for the from-scratch delta), with
    /// `digest` as the SHA-256 of its superblock.
    Take {
        from: Option<Checksum>,
        digest: Checksum,
    },
    /// A from-scratch delta in the map, which the pull does not take because
    /// the ref names a commit held here complete, or names the target.
    Declined,
    /// No delta in the map produces the commit from the objects here.
    None,
}

/// Chooses the delta to `to` that `map` offers.
///
/// `from` is the commit that the ref names here, if this repository holds it
/// complete. `scratch` is `true` if the pull can take the from-scratch delta.
/// [`discover_one`] states the order of the choice. `known` holds the
/// completeness of commits that the caller checked, as [`first_complete`]
/// reads it.
async fn choose_delta(
    repo: &Repo,
    map: &Value,
    from: Option<Checksum>,
    scratch: bool,
    to: &Checksum,
    known: &HashMap<Checksum, bool>,
) -> Result<Choice> {
    if let Some(from) = from
        && let Some(digest) = map_digest(map, &delta_name(Some(&from), to))?
    {
        return Ok(Choice::Take {
            from: Some(from),
            digest,
        });
    }
    let candidates: Vec<(Checksum, &str, &Value)> = source_candidates(map, to)
        .filter(|(candidate, _, _)| Some(*candidate) != from)
        .collect();
    let commits: Vec<Checksum> = candidates.iter().map(|(commit, _, _)| *commit).collect();
    if let Some(at) = first_complete(repo, &commits, known).await? {
        let (candidate, name, value) = candidates[at];
        return Ok(Choice::Take {
            from: Some(candidate),
            digest: delta_digest(name, value)?,
        });
    }
    Ok(match map_digest(map, &delta_name(None, to))? {
        Some(digest) if scratch => Choice::Take { from: None, digest },
        Some(_) => Choice::Declined,
        None => Choice::None,
    })
}

/// Chooses the delta to `to` that the list `edges` holds, in the order of
/// [`choose_delta`]. Step 2 goes in list order.
async fn choose_listed(
    repo: &Repo,
    edges: &Edges,
    from: Option<Checksum>,
    scratch: bool,
    to: &Checksum,
    known: &HashMap<Checksum, bool>,
) -> Result<Choice> {
    let mut steps = edges.steps_to(to).to_vec();
    steps.sort_unstable();
    let listed = |index: &usize| edges.delta(*index);
    if let Some(from) = from
        && let Some(delta) = steps.iter().map(listed).find(|d| d.from == Some(from))
    {
        return Ok(Choice::Take {
            from: Some(from),
            digest: delta.superblock,
        });
    }
    let candidates: Vec<&AdvertisedDelta> = steps
        .iter()
        .map(listed)
        .filter(|delta| delta.from.is_some() && delta.from != from)
        .collect();
    let commits: Vec<Checksum> = candidates.iter().filter_map(|delta| delta.from).collect();
    if let Some(at) = first_complete(repo, &commits, known).await? {
        let delta = candidates[at];
        return Ok(Choice::Take {
            from: delta.from,
            digest: delta.superblock,
        });
    }
    Ok(match steps.iter().map(listed).find(|d| d.from.is_none()) {
        Some(delta) if scratch => Choice::Take {
            from: None,
            digest: delta.superblock,
        },
        Some(_) => Choice::Declined,
        None => Choice::None,
    })
}

/// Returns the position of the first commit of `commits` that this repository
/// holds complete, or `None` if it holds none of them complete.
///
/// `known` holds the completeness of commits that the caller checked. The
/// call checks each other commit in order, in one call on the blocking pool,
/// and stops at the first commit held complete.
async fn first_complete(
    repo: &Repo,
    commits: &[Checksum],
    known: &HashMap<Checksum, bool>,
) -> Result<Option<usize>> {
    let mut unknown = Vec::new();
    let mut held = None;
    for (at, commit) in commits.iter().enumerate() {
        match known.get(commit) {
            Some(true) => {
                held = Some(at);
                break;
            }
            Some(false) => {}
            None => unknown.push((at, *commit)),
        }
    }
    if unknown.is_empty() {
        return Ok(held);
    }
    let repo = repo.clone();
    let first = ostrya_rt::unblock(move || -> Result<Option<usize>> {
        for (at, commit) in unknown {
            if complete_here_blocking(&repo, &commit)? {
                return Ok(Some(at));
            }
        }
        Ok(None)
    })
    .await?;
    Ok(first.or(held))
}

/// Returns the source commit, the name, and the value of each `<from>-<to>`
/// entry of `map`, in map order.
///
/// The scan skips each entry that is not a `{sv}`, each key for another
/// target, and each key that is not a delta name in lowercase hex. A key that
/// does not end in `-<to>` is skipped before the hex parse.
fn source_candidates<'a>(
    map: &'a Value,
    to: &Checksum,
) -> impl Iterator<Item = (Checksum, &'a str, &'a Value)> {
    let to = *to;
    let suffix = format!("-{}", to.to_hex());
    map.as_array()
        .unwrap_or_default()
        .iter()
        .filter_map(move |entry| {
            let [key, value] = entry.as_tuple()? else {
                return None;
            };
            let name = key.as_str()?;
            if !name.ends_with(&suffix) {
                return None;
            }
            match parse_delta_name(name)? {
                (Some(from), target) if target == to => Some((from, name, value)),
                _ => None,
            }
        })
}

/// What a remote states about the deltas that it holds.
enum Advertisement<'a> {
    /// A map from delta name to superblock digest: the index file of the
    /// target commit, or the map of the summary. The map of the summary is
    /// borrowed, with no copy.
    Map(Cow<'a, Value>),
    /// The list of static deltas that the caller gives.
    List(&'a Edges),
    /// The remote serves no summary. It advertises nothing, and the pull
    /// requests a delta by name.
    Unlisted,
    /// The remote serves a summary and advertises no delta map.
    Nothing,
}

/// Finds and reads the delta that produces `to`, or `None` if the pull fetches
/// the objects loose.
///
/// `from` is the commit that the pulled ref names here, if this repository
/// holds it complete. `scratch` is `true` if the ref names no commit held
/// complete and does not name `to`. For a dependency, [`DependencyLookup`]
/// gives the two values. `subject` names `to` in an error, as
/// [`none_found_error`] states.
///
/// With `edges`, the list of static deltas, the pull reads no summary map and
/// no delta index. It takes the first delta of the list in the order below.
/// Step 2 then goes in list order.
///
/// If the remote advertises a map, the pull takes the first of these deltas
/// that the map names:
///
/// 1. `<from>-<to>`
/// 2. `<c>-<to>`, for each commit `c` that this repository holds complete, in
///    map order
/// 3. the from-scratch `<to>`, if `scratch` is `true`
///
/// Step 2 skips each key that is not a delta name in lowercase hex. A digest
/// of the chosen delta that is not an `ay` of 32 bytes fails the pull with
/// [`Error::InvalidFormat`].
///
/// Observed: the `ostree` command also takes a from-to delta from a commit
/// that it holds under no ref. If nothing advertises a map, the pull requests
/// the delta from `from` by name. If `from` is `None`, it requests the
/// from-scratch delta.
///
/// A pull that [requires](PullOptions::require_static_deltas) a delta and
/// finds none fails with [`Error::Pull`]. If the ref names a commit held here
/// complete, or names `to`, the pull does not take a from-scratch delta in
/// the map. That delta counts as found, and the pull fetches loose. A
/// superblock that the map or the list names and the remote does not hold
/// counts as none.
///
/// `known` holds the completeness of commits that the caller checked. Step 2
/// checks no such commit again.
///
/// `verification` is the policy for the signatures of the superblock, as
/// [`fetch_job`] states. The search for the delta of a dependency passes
/// `None`.
///
/// If `keep` is set, the search writes the superblock to that record file, as
/// [`fetch_job`] states, and the result holds its range.
#[allow(clippy::too_many_arguments)]
async fn discover_one(
    repo: &Repo,
    source: &DeltaSource<'_>,
    advert: Option<&DeltaAdvert>,
    edges: Option<&Edges>,
    subject: &str,
    from: Option<Checksum>,
    scratch: bool,
    to: Checksum,
    known: &HashMap<Checksum, bool>,
    opts: &PullOptions,
    verification: Option<&Verification>,
    progress: &PullCounters,
    keep: Option<&Arc<Mutex<RecordStore>>>,
) -> Result<Option<FoundDelta>> {
    let advertised = match (edges, advert) {
        (Some(edges), _) => Advertisement::List(edges),
        (None, None) => Advertisement::Unlisted,
        (None, Some(advert)) => match advertised_map(source, advert, &to, progress).await? {
            Some(map) => Advertisement::Map(map),
            None => Advertisement::Nothing,
        },
    };
    let none_found = || -> Result<Option<FoundDelta>> {
        if opts.require_static_deltas {
            return Err(none_found_error(subject, &to));
        }
        Ok(None)
    };

    let choice = match &advertised {
        Advertisement::Map(map) => Some(choose_delta(repo, map, from, scratch, &to, known).await?),
        Advertisement::List(edges) => {
            Some(choose_listed(repo, edges, from, scratch, &to, known).await?)
        }
        Advertisement::Unlisted => None,
        Advertisement::Nothing => return none_found(),
    };
    let (from, digest) = match choice {
        Some(Choice::Take { from, digest }) => (from, Some(digest)),
        // A from-scratch delta for this commit on the remote satisfies the
        // requirement, and the pull does not take it. The pull fetches loose
        // each object of the commit that this repository lacks.
        Some(Choice::Declined) => return Ok(None),
        Some(Choice::None) => return none_found(),
        // Nothing states a digest, so the pull requests the delta by name, and
        // no advertised digest verifies the superblock. The application of the
        // parts still verifies each object that the delta produces.
        None => (from, None),
    };
    // If the remote does not hold an advertised superblock, the advertisement
    // is stale. The pull then fetches the objects loose. If the pull requires
    // static deltas, it fails.
    let keep = keep.map(Keep::Shared);
    let Some((fetched, kept)) =
        fetch_job(source, from, to, digest, verification, progress, keep).await?
    else {
        return none_found();
    };
    Ok(Some(FoundDelta {
        from,
        digest,
        fetched,
        kept,
    }))
}

/// A delta that [`discover_one`] found, fetched, and checked, as
/// [`fetch_job`] states.
struct FoundDelta {
    /// The source commit of the delta, or `None` for a from-scratch delta.
    from: Option<Checksum>,
    /// The digest of the superblock that the map or the list states, or
    /// `None` if nothing states one.
    digest: Option<Checksum>,
    /// The parsed superblock.
    fetched: FetchedDelta,
    /// The ranges of the delta in the record file, if the search kept it.
    kept: Option<KeptRanges>,
}

/// The record file where [`fetch_job`] keeps a raw superblock.
enum Keep<'a> {
    /// The record file of the discovery of a chain, which fetches one
    /// superblock at a time.
    Own(&'a mut RecordStore),
    /// The record file that the concurrent searches of
    /// [`discover_dependencies`] share. The file also keeps the commit that
    /// each superblock carries.
    Shared(&'a Arc<Mutex<RecordStore>>),
}

/// The ranges of one delta in the record file of [`fetch_job`].
struct KeptRanges {
    /// The range of the raw superblock.
    superblock: Range<u64>,
    /// The range of the normal-form bytes of the commit that the superblock
    /// carries, or `None` if the record file keeps no commit.
    commit: Option<Range<u64>>,
}

/// Fetches the superblock of the delta from `from` to `to`, and checks it.
///
/// Returns `None` if the source does not hold the superblock. The request
/// adds one to the metadata count in `progress`, whatever the source answers.
/// If `digest` is set, the SHA-256 of the superblock must be `digest`. The
/// superblock must produce `to` from `from`. If `verification` is set, its
/// signatures must pass that policy, as [`verify_fetched_delta`] states. The
/// search for the delta of a dependency passes `None`, and the function then
/// checks no signature. Each inline part must pass its meta-entry.
///
/// If `keep` is set, the function appends the raw bytes to that record file
/// after the digest check, and returns their range with the parsed delta.
/// Before the digest check, it checks that the bytes keep the record file in
/// its limit, and reserves their range. A superblock that would pass the
/// limit fails before the function opens the file or writes to it. A record
/// file that concurrent searches share gives each search its own range. To
/// such a file, the function also appends the normal-form bytes of the
/// commit that the superblock carries, after the parse verified that they
/// hash to `to`, and returns their range too.
///
/// The digest check, the writes to the record file, the parse, and the check
/// of the inline parts run in one call on the blocking pool. The check of the
/// signatures comes after it, and a failed inline part fails after the check
/// of the signatures.
///
/// # Errors
///
/// - [`Error::Pull`] if the superblock or the commit would pass the limit of
///   the record file of `keep`.
/// - [`Error::ChecksumMismatch`] if the superblock does not have `digest`.
/// - [`Error::Pull`] if the superblock produces another commit, or from
///   another commit.
/// - [`Error::Signature`] if `verification` is set and the signatures fail
///   it.
/// - [`Error::InvalidFormat`] or [`Error::Core`] if the superblock or an
///   inline part is malformed.
async fn fetch_job(
    source: &DeltaSource<'_>,
    from: Option<Checksum>,
    to: Checksum,
    digest: Option<Checksum>,
    verification: Option<&Verification>,
    progress: &PullCounters,
    keep: Option<Keep<'_>>,
) -> Result<Option<(FetchedDelta, Option<KeptRanges>)>> {
    let path = format!(
        "{}/{SUPERBLOCK_FILE}",
        delta_relative_dir(from.as_ref(), &to)
    );
    let fetched = source.read(&path, MAX_SUPERBLOCK, progress).await?;
    progress.metadata_fetched();
    let Some(bytes) = fetched else {
        return Ok(None);
    };
    let len = bytes.len() as u64;
    let what = || {
        format!(
            "the superblock of static delta {}",
            delta_name(from.as_ref(), &to)
        )
    };
    // A shared record file opens at the first write, on the blocking pool
    // and under the lock. No search holds the lock across an await.
    let (own, shared) = match keep {
        Some(Keep::Own(store)) => {
            store.check_room(len, what)?;
            let file = store.file().await?;
            (Some((file, store.reserve(len, what)?)), None)
        }
        Some(Keep::Shared(store)) => {
            let start = store
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .reserve(len, what)?;
            (None, Some((Arc::clone(store), start)))
        }
        None => (None, None),
    };
    let (parsed, kept) = ostrya_rt::unblock(move || {
        let Some((store, start)) = shared else {
            let (parsed, kept) = parse_superblock(bytes, digest, own, from, to, true)?;
            let kept = kept.map(|superblock| KeptRanges {
                superblock,
                commit: None,
            });
            return Ok((parsed, kept));
        };
        let file = store
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .file_blocking()?;
        let (parsed, superblock) = parse_superblock(
            bytes,
            digest,
            Some((Arc::clone(&file), start)),
            from,
            to,
            true,
        )?;
        let commit = &parsed.delta.commit_bytes;
        let len = commit.len() as u64;
        let start = store
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reserve(len, || {
                format!(
                    "the commit of static delta {}",
                    delta_name(from.as_ref(), &to)
                )
            })?;
        file.write_all_at(commit, start)?;
        let kept = superblock.map(|superblock| KeptRanges {
            superblock,
            commit: Some(start..start + len),
        });
        Ok::<_, Error>((parsed, kept))
    })
    .await?;
    let fetched = parsed.verify(verification).await?;
    Ok(Some((fetched, kept)))
}

/// Checks and parses the superblock `bytes` of the delta from `from` to `to`
/// on the calling thread, and checks its source and target.
///
/// If `digest` is set, the SHA-256 of `bytes` must be `digest`. If `sink` is
/// set, the function then writes `bytes` to that file at that offset, before
/// the parse consumes them, and returns their range. If `check_inline` is
/// set, the result holds the check of each inline part against its
/// meta-entry.
fn parse_superblock(
    bytes: Vec<u8>,
    digest: Option<Checksum>,
    sink: Option<(Arc<std::fs::File>, u64)>,
    from: Option<Checksum>,
    to: Checksum,
    check_inline: bool,
) -> Result<(ParsedDelta, Option<Range<u64>>)> {
    if let Some(expected) = digest {
        let actual = Checksum::sha256(&bytes);
        if actual != expected {
            return Err(Error::ChecksumMismatch { expected, actual });
        }
    }
    let kept = match sink {
        Some((file, start)) => {
            file.write_all_at(&bytes, start)?;
            Some(start..start + bytes.len() as u64)
        }
        None => None,
    };
    let name = delta_name(from.as_ref(), &to);
    let superblock = DeltaSuperblock::parse(bytes)?;
    if superblock.to != to || superblock.from != from {
        return Err(Error::Pull(format!(
            "static delta {name}: its superblock produces {} from {}",
            superblock.to,
            match superblock.from {
                Some(from) => from.to_hex(),
                None => "scratch".to_owned(),
            }
        )));
    }
    // The destructure lets the compiler prove where the raw bytes and the
    // signature array go. They go to verification alone. The metadata dict
    // goes to the inline parts.
    let DeltaSuperblock {
        commit_bytes,
        meta_entries,
        fallbacks,
        signatures,
        superblock_bytes,
        metadata,
        inline_index,
        ..
    } = superblock;
    let delta = FetchedDelta {
        dir: delta_relative_dir(from.as_ref(), &to),
        name,
        commit_bytes,
        meta_entries,
        fallbacks,
        metadata,
        inline_index,
    };
    let inline = if check_inline {
        delta.verify_inline_parts()
    } else {
        Ok(())
    };
    Ok((
        ParsedDelta {
            delta,
            superblock_bytes,
            signatures,
            inline,
        },
        kept,
    ))
}

/// Copies the bodies of the inline parts into one [`Blob`].
///
/// The caller verified each inline part against its meta-entry. The function
/// checks again the size and the compression byte of each part, and does not
/// hash it again. It works in part order and copies the bodies out of the
/// metadata dict, so the caller can drop the dict. The heap threshold is 128
/// KiB. If the bodies total more, the blob is one anonymous temp file in
/// `tmp/` of the repository, mapped read-only. The job then keeps no copy of
/// the bodies on the heap.
async fn take_inline_parts(
    repo: &Repo,
    metadata: &Value,
    index: &[Option<usize>],
    dir: &str,
    meta_entries: &[DeltaPart],
) -> Result<(Vec<Option<InlinePart>>, Blob)> {
    let mut inline = Vec::with_capacity(meta_entries.len());
    let mut bodies: Vec<&[u8]> = Vec::new();
    let mut start = 0usize;
    for (part, entry) in meta_entries.iter().enumerate() {
        let Some((compression, body)) = inline_part_at(metadata, index, part, || dir.to_owned())?
        else {
            inline.push(None);
            continue;
        };
        check_inline_part(compression, body, entry)?;
        inline.push(Some(InlinePart {
            compression,
            start,
            len: body.len(),
        }));
        start += body.len();
        bodies.push(body);
    }
    if bodies.is_empty() {
        return Ok((inline, Blob::Ram(Vec::new())));
    }
    Ok((inline, concat_to_blob(&bodies, repo.root_dir()).await?))
}

/// Verifies the detached signatures of a fetched delta over the raw superblock
/// bytes.
///
/// The policy of the pull decides. The sign-api engines that verify a commit
/// also verify the delta, because a delta carries sign-api signatures alone.
/// A delta with none of those signatures passes, and the pull holds the
/// commit that it delivers to the commit policy, as any other target or
/// commit of a chain. The search for the delta of a dependency does not call
/// the function.
///
/// The call is in discovery, where the raw superblock bytes and the signature
/// array are available. The pull drops them after the call and does not keep
/// them until it ends.
async fn verify_fetched_delta(
    verification: &Verification,
    name: &str,
    superblock_bytes: &Arc<Vec<u8>>,
    signatures: Option<&Value>,
) -> Result<()> {
    verification
        .check_delta(name, superblock_bytes, signatures)
        .await
}

/// What the summary of a source states about its deltas: the
/// `ostree.summary.indexed-deltas` key and the `ostree.static-deltas` map.
///
/// The pull keeps these two values and drops the rest of the summary. It
/// reads them for the targets, and for the dependencies after the run of the
/// commits that name them.
pub(crate) struct DeltaAdvert {
    /// `true` if the summary states `indexed-deltas`, or omits the key.
    indexed: bool,
    /// The `ostree.static-deltas` map, or `None` if the summary has none.
    map: Option<Value>,
}

impl DeltaAdvert {
    /// Takes the two values out of `summary`, and drops the rest. The map
    /// moves out of the metadata dict with no copy.
    pub(crate) fn from_summary(mut summary: Summary) -> DeltaAdvert {
        let indexed = indexed_deltas(&summary);
        let map = take_metadata_value(&mut summary.metadata, STATIC_DELTAS_KEY);
        DeltaAdvert { indexed, map }
    }
}

/// Takes the value of `key` out of the metadata dict `metadata`, as
/// [`Summary::metadata_value`] reads it, and leaves a placeholder there.
fn take_metadata_value(metadata: &mut Value, key: &str) -> Option<Value> {
    let Value::Array(entries) = metadata else {
        return None;
    };
    let fields = entries.iter_mut().find_map(|entry| match entry {
        Value::Tuple(fields) if matches!(fields.as_slice(), [name, _] if name.as_str() == Some(key)) => {
            Some(fields)
        }
        _ => None,
    })?;
    match &mut fields[1] {
        Value::Variant(inner) => Some(std::mem::replace(&mut inner.1, Value::Bool(false))),
        _ => None,
    }
}

/// Returns the delta map that the remote advertises for `to`, or `None` if it
/// advertises no map.
///
/// The map is the index file if the remote serves one. If it serves no index,
/// the map is the `ostree.static-deltas` map of the summary.
///
/// If the summary states `indexed-deltas`, the pull requests the index first.
/// A summary that omits the key counts as `true`, because that is the
/// repository default. A remote that holds deltas and no index (no reindex
/// ran) answers 404 for the index. The pull then reads the summary map.
async fn advertised_map<'a>(
    source: &DeltaSource<'_>,
    advert: &'a DeltaAdvert,
    to: &Checksum,
    progress: &PullCounters,
) -> Result<Option<Cow<'a, Value>>> {
    if advert.indexed {
        let path = delta_index_relative_path(to);
        let fetched = source.read(&path, MAX_METADATA_SIZE, progress).await?;
        progress.metadata_fetched();
        if let Some(bytes) = fetched {
            let map = index_delta_map(&bytes)?.ok_or_else(|| {
                Error::InvalidFormat(format!(
                    "the remote's delta index for {to} holds no {STATIC_DELTAS_KEY} map"
                ))
            })?;
            return Ok(Some(Cow::Owned(map)));
        }
    }
    Ok(advert.map.as_ref().map(Cow::Borrowed))
}

/// Returns `true` if the summary states that the remote indexes its deltas.
///
/// A summary without the key counts as `true`, which is the repository
/// default.
fn indexed_deltas(summary: &Summary) -> bool {
    summary
        .metadata_value(INDEXED_DELTAS_KEY)
        .and_then(Value::as_bool)
        .unwrap_or(true)
}

/// Returns the superblock digest that a delta map holds for `name`, or `None`
/// if the map does not name it.
fn map_digest(map: &Value, name: &str) -> Result<Option<Checksum>> {
    let Some(entry) = map.dict_get(name) else {
        return Ok(None);
    };
    delta_digest(name, entry).map(Some)
}

/// Reads one part of a delta from `source` and applies it into the
/// transaction of the pull.
///
/// Discovery verified each inline part, so the function decompresses and
/// applies an inline part with no request.
///
/// A part file streams from the connection, or from the part file of the
/// source repository, under the size that the superblock declares for it.
/// The function verifies the body against the checksum that the superblock
/// states for the part. The verified body then decompresses into the
/// random-access blob that the operations read. The blob is on the heap while
/// it is small, and a mapped temp file when it is large.
///
/// A remote can answer a part request with more bytes than the part holds, or
/// with other bytes. A part file in a local source can grow or change. In
/// each case, the pull writes at most the declared size before it refuses the
/// part. The application of the blob writes each object under the checksum
/// that the superblock names, so a part that produces other objects fails.
///
/// `checks` are the mode checks of the pull. Each content object that a part
/// produces must pass them, as a loose fetch of that object must. After the
/// body of a part file passes the checksum, the function adds one part and
/// its declared size to `progress`. For a local source, it also adds that
/// size to the transferred count.
pub(crate) async fn apply_job_part(
    txn: &Transaction,
    source: &DeltaSource<'_>,
    job: &DeltaJob,
    index: usize,
    checks: ModeChecks,
    progress: &PullCounters,
) -> Result<()> {
    let entry = job.meta_entries.get(index).ok_or_else(|| {
        Error::InvalidFormat(format!(
            "static delta {}: no part {index} in its superblock",
            job.name
        ))
    })?;
    if let Some(Some(part)) = job.inline.get(index) {
        let staging = txn.staging_dir().clone();
        let body = &job.inline_bodies.as_slice()[part.start..part.start + part.len];
        let payload = decode_inline_part(part.compression, body, &staging).await?;
        return apply_part(txn, payload.as_slice(), &entry.objects, &staging, checks).await;
    }
    let path = format!("{}/{index}", job.dir);
    let staging = txn.staging_dir().clone();
    let blob = match source {
        DeltaSource::Remote(remote) => match remote.transfer() {
            Transfer::Http(fetcher) => fetch_part_blob(fetcher, &path, entry, &staging).await?,
            // The size of the part in the superblock caps the body.
            Transfer::Stream(stream) => {
                let body = stream.get(&path, entry.size).await?.ok_or_else(|| {
                    Error::InvalidFormat(format!(
                        "static delta {}: the remote holds no part {index}",
                        job.name
                    ))
                })?;
                decode_part_stream(body, entry, &staging)
                    .await
                    .map_err(session_error)?
            }
        },
        DeltaSource::Local(repo) => {
            let root = repo.root_dir().clone();
            let rest = path
                .strip_prefix("deltas/")
                .expect("a delta directory is below deltas/")
                .to_owned();
            let opened = ostrya_rt::unblock(move || {
                let Some(deltas) = root.open_layout(RepoLayout::Deltas).optional()? else {
                    return Ok(None);
                };
                deltas.open_regular(&rest).optional()
            })
            .await?;
            let (file, len) = opened
                .map(|opened| (opened.file, opened.stat.size))
                .ok_or_else(|| {
                    Error::InvalidFormat(format!(
                        "static delta {}: the source repository holds no part {index}",
                        job.name
                    ))
                })?;
            // If the part file is longer than the declared size, the pull
            // refuses it before any read. The async reader reads ahead of the
            // bytes that the declared-size limit lets it write.
            if len > entry.size {
                return Err(Error::InvalidFormat(format!(
                    "static delta {}: part {index} holds {len} byte(s), past the {} \
                     declared for it",
                    job.name, entry.size
                )));
            }
            let blob =
                decode_part_stream(FileReader::with_len_hint(file, len), entry, &staging).await?;
            progress.add_transferred(entry.size);
            blob
        }
    };
    progress.part_fetched(entry.size);
    apply_part(txn, blob.as_slice(), &entry.objects, &staging, checks).await
}

/// Fetches the part file at `path` into a verified, decompressed blob.
async fn fetch_part_blob(
    fetcher: &Fetcher,
    path: &str,
    entry: &DeltaPart,
    staging: &RepoDir,
) -> Result<Blob> {
    // The superblock states the size of the part file, so the fetcher refuses
    // a larger `Content-Length` before the body arrives. It also stops a body
    // that passes the size as the bytes arrive.
    // If a body fails in transit, the pull fetches it again from the start
    // into a new blob. It does so while the retry count of the fetcher has a
    // repeat left.
    let mut refetch = fetcher.refetching(FetchRequest {
        priority: Priority::High,
        max_size: Some(entry.size),
        ..FetchRequest::path(path)
    });
    loop {
        let body = match refetch.fetch().await? {
            Fetched::Body(body) => body,
            Fetched::NotModified => {
                return Err(Error::Fetch(format!(
                    "{path}: the remote answered 304 to an unconditional request"
                )));
            }
        };
        match decode_part_stream(body, entry, staging).await {
            Ok(blob) => return Ok(blob),
            Err(e) => refetch.retry(e).await?,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Ref;
    use crate::pull::TimestampBase;
    use ostrya_core::Type;

    fn checksum(byte: u8) -> Checksum {
        Checksum::from_bytes([byte; 32])
    }

    /// The digest lookup reads the `ay` in the variant, returns `None` for an
    /// absent delta, and refuses an entry of another type or of another
    /// length.
    #[test]
    fn map_digest_reads_the_advertised_ay() {
        let digest = checksum(0x33);
        let ay = Type::parse("ay").unwrap();
        let mut map = Value::Array(Vec::new());
        crate::commit::append_dict_entry(
            &mut map,
            "delta-name",
            Value::variant(ay, Value::Bytes(digest.as_bytes().to_vec())),
        )
        .unwrap();
        crate::commit::append_dict_entry(
            &mut map,
            "not-a-digest",
            Value::variant(Type::parse("s").unwrap(), Value::Str("nope".to_owned())),
        )
        .unwrap();
        for len in [31, 33] {
            crate::commit::append_dict_entry(
                &mut map,
                &format!("digest-of-{len}"),
                Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![0x33; len])),
            )
            .unwrap();
        }

        assert_eq!(map_digest(&map, "delta-name").unwrap(), Some(digest));
        assert_eq!(map_digest(&map, "absent").unwrap(), None);
        assert!(matches!(
            map_digest(&map, "not-a-digest"),
            Err(Error::InvalidFormat(_))
        ));
        for name in ["digest-of-31", "digest-of-33"] {
            assert!(
                matches!(map_digest(&map, name), Err(Error::InvalidFormat(_))),
                "{name}"
            );
        }
    }

    /// The scan for `<from>-<to>` keys finds the lowercase key to `to` alone.
    /// It skips an uppercase source, another target, the from-scratch key,
    /// and a key that is not a delta name, and these keys do not stop it.
    #[test]
    fn source_candidates_finds_the_keys_to_the_target() {
        let (from, to, other) = (checksum(0xa1), checksum(0xf0), checksum(0xb2));
        let (from_hex, to_hex) = (from.to_hex(), to.to_hex());
        let found = delta_name(Some(&from), &to);
        let mut map = Value::Array(Vec::new());
        for name in [
            format!("{}-{to_hex}", from_hex.to_uppercase()),
            delta_name(Some(&from), &other),
            delta_name(None, &to),
            format!("zz-{to_hex}"),
            found.clone(),
        ] {
            crate::commit::append_dict_entry(
                &mut map,
                &name,
                Value::variant(
                    Type::parse("ay").unwrap(),
                    Value::Bytes(name.as_bytes().to_vec()),
                ),
            )
            .unwrap();
        }

        let candidates: Vec<_> = source_candidates(&map, &to).collect();
        assert_eq!(candidates.len(), 1, "{candidates:?}");
        let (candidate, name, value) = candidates[0];
        assert_eq!((candidate, name), (from, found.as_str()));
        assert_eq!(
            value.as_variant().and_then(|(_, bytes)| bytes.as_bytes()),
            Some(found.as_bytes())
        );
    }

    /// The base64 of a 64-byte ed25519 secret key (seed, then public key).
    const SECRET_B64: &str =
        "o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
    /// The matching 32-byte ed25519 public key.
    const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";

    /// The verification of a pull that checks the commits against the
    /// ed25519 key [`PUBLIC_B64`].
    fn ed25519_verification() -> Verification {
        use crate::sign::{Ed25519Verifier, Verifier};
        let verifier = Ed25519Verifier::new(
            [ostrya_core::base64::decode(PUBLIC_B64).unwrap()],
            Vec::<Vec<u8>>::new(),
        )
        .unwrap();
        let keys = crate::verify::TrustedKeys::new(vec![
            std::sync::Arc::new(verifier) as Arc<dyn Verifier>
        ])
        .unwrap();
        Verification::from_trust(crate::verify::PullTrust::commits(keys))
    }

    fn unverified() -> Verification {
        Verification::from_trust(crate::verify::PullTrust::unverified())
    }

    /// Signs `commit` in `repo` with the key [`SECRET_B64`].
    async fn sign(repo: &Repo, commit: &Checksum) {
        let signer = crate::sign::Ed25519Signer::from_base64(SECRET_B64).unwrap();
        repo.sign_commit(commit, &signer).await.unwrap();
    }

    /// Writes a commit whose tree holds the file `f` with `content`, and
    /// returns it.
    async fn commit(repo: &Repo, parent: Option<Checksum>, content: &[u8]) -> Checksum {
        let txn = repo.transaction().await.unwrap();
        let dirmeta = ostrya_core::DirMeta {
            uid: 0,
            gid: 0,
            mode: 0o40755,
            xattrs: Default::default(),
        };
        let dirmeta = txn
            .write_metadata(ObjectType::DirMeta, None, &dirmeta.serialize().unwrap())
            .await
            .unwrap();
        let file = txn
            .write_regfile_inline(None, &crate::write::FileMeta::regular(0, 0, 0o644), content)
            .await
            .unwrap();
        let mut mtree = crate::mtree::MutableTree::new();
        mtree.set_metadata_checksum(dirmeta);
        mtree.replace_file("f", file).unwrap();
        let root = txn.write_mtree(&mut mtree).await.unwrap();
        let options = crate::commit::CommitOptions {
            parent,
            subject: None,
            body: None,
            timestamp: Some(1_700_000_000),
            metadata: None,
            related: Vec::new(),
        };
        let commit = txn.write_commit(options, &root).await.unwrap();
        txn.commit().await.unwrap();
        commit
    }

    /// A source repository with the commits `A-B-C-D` and `A-X-Y`, and a
    /// repository that holds `A` complete under the ref `main`.
    struct Fixture {
        root: std::path::PathBuf,
        src: Repo,
        dst: Repo,
        a: Checksum,
        b: Checksum,
        c: Checksum,
        d: Checksum,
        x: Checksum,
        y: Checksum,
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.root);
        }
    }

    impl Fixture {
        async fn new() -> Fixture {
            let root = std::env::temp_dir().join(format!(
                "ostrya-delta-chain-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).unwrap();
            let create = || crate::CreateOptions::new(RepoMode::Archive);
            let src = Repo::create(&root.join("src"), create()).await.unwrap();
            let dst = Repo::create(&root.join("dst"), create()).await.unwrap();
            let a = commit(&src, None, b"a").await;
            let b = commit(&src, Some(a), b"b").await;
            let c = commit(&src, Some(b), b"c").await;
            let d = commit(&src, Some(c), b"d").await;
            let x = commit(&src, Some(a), b"x").await;
            let y = commit(&src, Some(x), b"y").await;
            src.set_ref_immediate(&Ref::local("main"), Some(&a))
                .await
                .unwrap();
            let opts = PullOptions {
                refs: vec!["main".to_owned()],
                ..PullOptions::default()
            };
            dst.pull_local(&src, opts).await.unwrap();
            Fixture {
                root,
                src,
                dst,
                a,
                b,
                c,
                d,
                x,
                y,
            }
        }

        /// Generates the delta from `from` to `to` in the source, and returns
        /// its entry of a list.
        async fn delta(&self, from: Option<Checksum>, to: Checksum) -> AdvertisedDelta {
            let options = crate::DeltaOptions {
                timestamp: Some(1_700_000_000),
                ..crate::DeltaOptions::default()
            };
            self.src
                .generate_static_delta(from.as_ref(), &to, &options)
                .await
                .unwrap();
            AdvertisedDelta {
                from,
                to,
                superblock: Checksum::sha256(&std::fs::read(self.superblock(from, to)).unwrap()),
            }
        }

        /// Returns the path of the superblock of a delta in the source.
        fn superblock(&self, from: Option<Checksum>, to: Checksum) -> std::path::PathBuf {
            self.src
                .path()
                .join(delta_relative_dir(from.as_ref(), &to))
                .join(SUPERBLOCK_FILE)
        }

        /// Runs the discovery of `list` for the targets `targets`.
        async fn discover(
            &self,
            list: Vec<AdvertisedDelta>,
            targets: &[(&str, Checksum)],
            opts: &PullOptions,
            verification: &Verification,
            counters: &PullCounters,
        ) -> Result<DeltaPlan> {
            let targets: Vec<(String, Checksum)> = targets
                .iter()
                .map(|(name, commit)| ((*name).to_owned(), *commit))
                .collect();
            discover(
                &self.dst,
                &DeltaSource::Local(&self.src),
                None,
                &targets,
                opts,
                TipChecks::new(opts.flags, TimestampBase::Off, RefPlace::Heads),
                Some(Edges::new(list)?),
                verification,
                RelatedRule::default(),
                counters,
            )
            .await
        }
    }

    fn required() -> PullOptions {
        PullOptions {
            require_static_deltas: true,
            ..PullOptions::default()
        }
    }

    /// Returns the source and the target of the record of each commit.
    fn record_steps(plan: &DeltaPlan) -> HashMap<Checksum, (Option<Checksum>, Checksum)> {
        plan.records
            .iter()
            .map(|(commit, record)| (*commit, (record.delta.from, record.delta.to)))
            .collect()
    }

    /// A chain of three steps gives three records and two levels, in order.
    /// It needs no summary, also if the pull requires static deltas. The
    /// parse of a level gives the job of each of its commits.
    #[test]
    fn a_chain_of_three_steps_gives_three_records_and_two_levels() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
            ];
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list,
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert!(plan.jobs.is_empty());
            assert_eq!(plan.levels, [vec![f.b], vec![f.c]]);
            assert_eq!(
                record_steps(&plan),
                HashMap::from([
                    (f.b, (Some(f.a), f.b)),
                    (f.c, (Some(f.b), f.c)),
                    (f.d, (Some(f.c), f.d)),
                ])
            );
            assert!(plan.store.is_none());
            for commit in [f.b, f.c, f.d] {
                assert!(matches!(
                    plan.records[&commit].detached,
                    Detached::Checked { kept: None, .. }
                ));
            }
            assert_eq!(counters.metadata(), 3);

            let source = DeltaSource::Local(&f.src);
            for level in &plan.levels {
                let jobs = plan.parse_level(&f.dst, &source, level).await.unwrap();
                assert_eq!(jobs.len(), 1);
                let (commit, job) = jobs.iter().next().unwrap();
                assert_eq!(Checksum::sha256(&job.commit_bytes), *commit);
                assert_eq!(job.fetched_parts(), plan.records[commit].parts);
            }
            // The second read of a superblock counts nothing.
            assert_eq!(counters.metadata(), 3);
            let jobs = plan
                .parse_level(&f.dst, &source, &[f.d, f.a])
                .await
                .unwrap();
            assert_eq!(jobs.keys().collect::<Vec<_>>(), [&f.d]);
        });
    }

    /// A missing superblock in the middle of a chain makes discovery plan
    /// again and take the second chain. The record of the step that it
    /// fetched before the miss is dropped.
    #[test]
    fn a_missing_superblock_makes_discovery_take_another_chain() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
                f.delta(Some(f.a), f.x).await,
                f.delta(Some(f.x), f.y).await,
                f.delta(Some(f.y), f.d).await,
            ];
            std::fs::remove_file(f.superblock(Some(f.b), f.c)).unwrap();
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list,
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert_eq!(plan.levels, [vec![f.x], vec![f.y]]);
            assert_eq!(
                record_steps(&plan),
                HashMap::from([
                    (f.x, (Some(f.a), f.x)),
                    (f.y, (Some(f.x), f.y)),
                    (f.d, (Some(f.y), f.d)),
                ])
            );
            assert_eq!(counters.metadata(), 5);
        });
    }

    /// A missing superblock in the middle of the only chain gives no chain.
    /// A pull that requires static deltas then fails.
    #[test]
    fn a_missing_superblock_with_no_other_chain_gives_no_chain() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
            ];
            std::fs::remove_file(f.superblock(Some(f.b), f.c)).unwrap();
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list.clone(),
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert!(plan.records.is_empty());
            assert!(plan.levels.is_empty());
            assert!(!plan.checked(&f.d));
            assert_eq!(counters.metadata(), 2);

            let err = f
                .discover(
                    list,
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &PullCounters::new(None),
                )
                .await
                .err()
                .unwrap();
            let Error::Pull(message) = err else {
                panic!("{err:?}");
            };
            assert_eq!(
                message,
                format!("Static deltas required, but none found for main to {}", f.d)
            );
        });
    }

    /// A wrong digest gives `ChecksumMismatch`. A superblock that produces
    /// another commit than its entry fails. The parse of a level checks the
    /// superblock of a local source again.
    #[test]
    fn a_superblock_that_does_not_match_the_list_fails() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let ab = f.delta(Some(f.a), f.b).await;
            let bc = f.delta(Some(f.b), f.c).await;
            let mut cd = f.delta(Some(f.c), f.d).await;
            let run = |list: Vec<AdvertisedDelta>| async {
                f.discover(
                    list,
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &unverified(),
                    &PullCounters::new(None),
                )
                .await
            };

            let right = cd.superblock;
            cd.superblock = Checksum::from_bytes([0xee; 32]);
            let err = run(vec![ab, bc, cd]).await.err().unwrap();
            assert!(
                matches!(err, Error::ChecksumMismatch { expected, actual }
                    if expected == cd.superblock && actual == right),
                "{err:?}"
            );

            let ab_bytes = std::fs::read(f.superblock(Some(f.a), f.b)).unwrap();
            std::fs::write(f.superblock(Some(f.c), f.d), &ab_bytes).unwrap();
            cd.superblock = ab.superblock;
            let err = run(vec![ab, bc, cd]).await.err().unwrap();
            assert!(matches!(err, Error::Pull(_)), "{err:?}");

            // The parse of a level reads the superblock of the source again.
            let cd = f.delta(Some(f.c), f.d).await;
            let plan = run(vec![ab, bc, cd]).await.unwrap();
            let source = DeltaSource::Local(&f.src);
            std::fs::write(f.superblock(Some(f.b), f.c), &ab_bytes).unwrap();
            let err = plan
                .parse_level(&f.dst, &source, &plan.levels[1])
                .await
                .err()
                .unwrap();
            assert!(
                matches!(err, Error::ChecksumMismatch { expected, .. } if expected == bc.superblock),
                "{err:?}"
            );
            std::fs::remove_file(f.superblock(Some(f.b), f.c)).unwrap();
            let err = plan
                .parse_level(&f.dst, &source, &plan.levels[1])
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
        });
    }

    /// An intermediate commit with no valid signature fails discovery. With
    /// valid signatures, discovery counts the `.commitmeta` of each
    /// intermediate commit once.
    #[test]
    fn an_intermediate_commit_with_no_valid_signature_fails() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            sign(&f.src, &f.c).await;
            sign(&f.src, &f.d).await;
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
            ];
            let err = f
                .discover(
                    list.clone(),
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &ed25519_verification(),
                    &PullCounters::new(None),
                )
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::Signature(_)), "{err:?}");

            sign(&f.src, &f.b).await;
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list,
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &ed25519_verification(),
                    &counters,
                )
                .await
                .unwrap();
            assert_eq!(plan.records.len(), 3);
            assert_eq!(counters.metadata(), 5);
        });
    }

    /// A target gets its check when discovery fetches its step. A later plan
    /// that makes the target an intermediate commit keeps that check. A
    /// target that fails its check fails discovery before the next superblock
    /// request.
    #[test]
    fn a_target_that_becomes_an_intermediate_commit_keeps_its_check() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            sign(&f.src, &f.d).await;
            let list = vec![
                f.delta(Some(f.a), f.c).await,
                f.delta(Some(f.a), f.d).await,
                f.delta(Some(f.c), f.d).await,
            ];
            std::fs::remove_file(f.superblock(Some(f.a), f.d)).unwrap();
            let targets = [("main", f.c), ("other", f.d)];
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list.clone(),
                    &targets,
                    &PullOptions::default(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert_eq!(plan.levels, [vec![f.c]]);
            for commit in [f.c, f.d] {
                assert!(plan.checked(&commit), "{commit}");
            }
            assert_eq!(counters.metadata(), 3);

            let counters = PullCounters::new(None);
            let err = f
                .discover(
                    list,
                    &targets,
                    &PullOptions::default(),
                    &ed25519_verification(),
                    &counters,
                )
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::Signature(_)), "{err:?}");
            // The superblock of the step to `C` alone.
            assert_eq!(counters.metadata(), 1);
        });
    }

    /// Discovery checks the signatures of a target that has a chain. An
    /// unsigned target fails discovery. A signed target has a record that
    /// discovery checked, and a commit with no record is not checked.
    #[test]
    fn a_target_with_a_chain_is_checked_in_discovery() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            sign(&f.src, &f.b).await;
            sign(&f.src, &f.c).await;
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
            ];
            let err = f
                .discover(
                    list.clone(),
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &ed25519_verification(),
                    &PullCounters::new(None),
                )
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::Signature(_)), "{err:?}");

            sign(&f.src, &f.d).await;
            let plan = f
                .discover(
                    list,
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &ed25519_verification(),
                    &PullCounters::new(None),
                )
                .await
                .unwrap();
            for commit in [f.b, f.c, f.d] {
                assert!(plan.checked(&commit), "{commit}");
            }
            assert!(!plan.checked(&f.a));
            assert!(matches!(
                plan.commit_check(&f.d).await.unwrap(),
                CommitCheck::Checked { detached: None, .. }
            ));
        });
    }

    /// A listed delta from scratch that the scratch rule refuses meets the
    /// requirement, and discovery keeps no record for it. With no delta to
    /// the target, a pull that requires static deltas fails.
    #[test]
    fn a_refused_delta_from_scratch_meets_the_requirement() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![f.delta(None, f.d).await];
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list,
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert!(plan.records.is_empty());
            assert_eq!(counters.metadata(), 0);

            let err = f
                .discover(
                    Vec::new(),
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &PullCounters::new(None),
                )
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::Pull(_)), "{err:?}");
        });
    }

    /// A commit-only pull ignores the list and sends no request.
    #[test]
    fn a_commit_only_pull_ignores_the_list() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![f.delta(Some(f.a), f.d).await];
            let opts = PullOptions {
                flags: PullFlags::COMMIT_ONLY,
                ..required()
            };
            let counters = PullCounters::new(None);
            let plan = f
                .discover(list, &[("main", f.d)], &opts, &unverified(), &counters)
                .await
                .unwrap();
            assert!(plan.records.is_empty() && plan.jobs.is_empty());
            assert_eq!(counters.metadata(), 0);
        });
    }

    /// A superblock with the listed target and another source fails.
    #[test]
    fn a_superblock_from_another_source_fails() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let ax = f.delta(Some(f.a), f.x).await;
            let xy = f.delta(Some(f.x), f.y).await;
            f.delta(Some(f.c), f.d).await;
            let cd_bytes = std::fs::read(f.superblock(Some(f.c), f.d)).unwrap();
            let yd_path = f.superblock(Some(f.y), f.d);
            std::fs::create_dir_all(yd_path.parent().unwrap()).unwrap();
            std::fs::write(&yd_path, &cd_bytes).unwrap();
            let yd = AdvertisedDelta {
                from: Some(f.y),
                to: f.d,
                superblock: Checksum::sha256(&cd_bytes),
            };
            let err = f
                .discover(
                    vec![ax, xy, yd],
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &unverified(),
                    &PullCounters::new(None),
                )
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::Pull(_)), "{err:?}");
        });
    }

    /// An intermediate commit that a later plan makes a target alone keeps
    /// its check. Discovery does not read its `.commitmeta` again and does
    /// not count it.
    #[test]
    fn an_intermediate_commit_that_becomes_a_target_keeps_its_check() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            for commit in [f.c, f.x, f.d] {
                sign(&f.src, &commit).await;
            }
            let list = vec![
                f.delta(Some(f.a), f.c).await,
                f.delta(Some(f.c), f.d).await,
                f.delta(Some(f.a), f.x).await,
                f.delta(Some(f.x), f.d).await,
            ];
            std::fs::remove_file(f.superblock(Some(f.c), f.d)).unwrap();
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list,
                    &[("c", f.c), ("main", f.d)],
                    &PullOptions::default(),
                    &ed25519_verification(),
                    &counters,
                )
                .await
                .unwrap();
            assert_eq!(plan.levels, [vec![f.x]]);
            assert_eq!(
                record_steps(&plan),
                HashMap::from([
                    (f.c, (Some(f.a), f.c)),
                    (f.x, (Some(f.a), f.x)),
                    (f.d, (Some(f.x), f.d)),
                ])
            );
            for commit in [f.c, f.x, f.d] {
                assert!(matches!(
                    plan.records[&commit].detached,
                    Detached::Checked { kept: None, .. }
                ));
            }
            // Four superblock requests and the `.commitmeta` of `X`.
            assert_eq!(counters.metadata(), 5);
        });
    }

    /// A step from scratch to a target is allowed if the scratch rule allows
    /// it for one of the refs that name the target, in each order of the
    /// refs.
    #[test]
    fn one_ref_that_allows_a_step_from_scratch_is_sufficient() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![f.delta(None, f.d).await];
            for targets in [
                [("main", f.d), ("other", f.d)],
                [("other", f.d), ("main", f.d)],
            ] {
                let plan = f
                    .discover(
                        list.clone(),
                        &targets,
                        &required(),
                        &unverified(),
                        &PullCounters::new(None),
                    )
                    .await
                    .unwrap();
                assert_eq!(record_steps(&plan), HashMap::from([(f.d, (None, f.d))]));
            }
        });
    }

    /// Two refs that name one target give one chain. A target that this
    /// repository holds complete gives no record and no request.
    #[test]
    fn a_target_is_planned_once_and_a_complete_target_not_at_all() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
            ];
            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list.clone(),
                    &[("main", f.a), ("main", f.d), ("copy", f.d)],
                    &required(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert_eq!(plan.levels, [vec![f.b], vec![f.c]]);
            assert_eq!(plan.records.len(), 3);
            assert_eq!(counters.metadata(), 3);

            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list,
                    &[("main", f.a)],
                    &required(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert!(plan.records.is_empty() && plan.levels.is_empty());
            assert_eq!(counters.metadata(), 0);
        });
    }

    /// A local source counts the `.commitmeta` of the intermediate commits of
    /// the last plan alone. An intermediate commit that a later plan drops is
    /// not counted, also if the check read its `.commitmeta`.
    #[test]
    fn a_dropped_intermediate_commit_is_not_counted() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            for commit in [f.b, f.x, f.y, f.d] {
                sign(&f.src, &commit).await;
            }
            let list = vec![
                f.delta(Some(f.a), f.b).await,
                f.delta(Some(f.b), f.c).await,
                f.delta(Some(f.c), f.d).await,
                f.delta(Some(f.a), f.x).await,
                f.delta(Some(f.x), f.y).await,
                f.delta(Some(f.y), f.d).await,
            ];
            std::fs::remove_file(f.superblock(Some(f.b), f.c)).unwrap();
            for verification in [unverified(), ed25519_verification()] {
                let counters = PullCounters::new(None);
                let plan = f
                    .discover(
                        list.clone(),
                        &[("main", f.d)],
                        &PullOptions::default(),
                        &verification,
                        &counters,
                    )
                    .await
                    .unwrap();
                assert_eq!(plan.levels, [vec![f.x], vec![f.y]]);
                // Five superblock requests, and the `.commitmeta` of `X` and
                // `Y`. The `.commitmeta` of `B` is not counted.
                assert_eq!(counters.metadata(), 7);
            }
        });
    }

    /// Discovery plans again around a limited number of missing superblocks.
    /// After the limit, a target whose chain holds a missing delta gets no
    /// chain, and a pull that requires static deltas fails.
    #[test]
    fn discovery_plans_again_around_a_limited_number_of_missing_deltas() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let ab = f.delta(Some(f.a), f.b).await;
            let bd = f.delta(Some(f.b), f.d).await;
            let list = |missing: usize| {
                let mut list = Vec::new();
                for i in 0..missing {
                    let mut bytes = [0x80; 32];
                    bytes[..8].copy_from_slice(&(i as u64).to_be_bytes());
                    let alternative = Checksum::from_bytes(bytes);
                    list.push(AdvertisedDelta {
                        from: Some(f.a),
                        to: alternative,
                        superblock: checksum(0x11),
                    });
                    list.push(AdvertisedDelta {
                        from: Some(alternative),
                        to: f.d,
                        superblock: checksum(0x11),
                    });
                }
                list.extend([ab, bd]);
                list
            };
            let limit = super::super::chain::MAX_EXCLUDED;

            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list(limit),
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert_eq!(plan.levels, [vec![f.b]]);
            assert_eq!(plan.records.len(), 2);
            assert_eq!(counters.metadata(), limit as u32 + 2);

            let counters = PullCounters::new(None);
            let plan = f
                .discover(
                    list(limit + 1),
                    &[("main", f.d)],
                    &PullOptions::default(),
                    &unverified(),
                    &counters,
                )
                .await
                .unwrap();
            assert!(plan.records.is_empty() && plan.levels.is_empty());
            assert_eq!(counters.metadata(), limit as u32 + 1);

            let err = f
                .discover(
                    list(limit + 1),
                    &[("main", f.d)],
                    &required(),
                    &unverified(),
                    &PullCounters::new(None),
                )
                .await
                .err()
                .unwrap();
            assert!(matches!(err, Error::Pull(_)), "{err:?}");
        });
    }

    /// Returns the bytes that a server sends for the reply to `PullHello`
    /// and one found reply for each of `bodies`, in order.
    async fn served(bodies: &[&[u8]]) -> Vec<u8> {
        use crate::remote::proto::{
            FrameWriter, GetReply, Message, PULL_PROTOCOL_VERSION, PullHelloReply,
        };
        let mut writer = FrameWriter::new(futures_lite::io::Cursor::new(Vec::new()));
        writer
            .write_message(&Message::PullHelloReply(PullHelloReply {
                version: PULL_PROTOCOL_VERSION,
            }))
            .await
            .unwrap();
        for body in bodies {
            writer
                .write_message(&Message::GetReply(GetReply {
                    found: true,
                    len: Some(body.len() as u64),
                }))
                .await
                .unwrap();
            writer.write_object_data(body).await.unwrap();
            writer.end_object().await.unwrap();
        }
        writer.into_inner().into_inner()
    }

    /// Returns a remote source whose server answers with `bodies`, in order.
    async fn remote(bodies: &[&[u8]]) -> RemoteSource {
        let session = crate::remote::StreamSession::over_stream(
            futures_lite::io::Cursor::new(served(bodies).await),
            futures_lite::io::sink(),
            Default::default(),
        )
        .await
        .unwrap();
        RemoteSource::new(
            crate::remote::PullSession::Stream(session).into(),
            Vec::new(),
        )
    }

    /// From a remote, the record file keeps each superblock and the
    /// `.commitmeta` of each commit of a chain, the target included. A
    /// localcache repository that holds the `.commitmeta` comes first, and
    /// the remote does not serve it. The parse of a level reads the record
    /// file.
    #[test]
    fn a_remote_record_keeps_the_superblock_and_the_commitmeta() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            sign(&f.src, &f.b).await;
            sign(&f.src, &f.d).await;
            let list = vec![f.delta(Some(f.a), f.b).await, f.delta(Some(f.b), f.d).await];
            let ab = std::fs::read(f.superblock(Some(f.a), f.b)).unwrap();
            let bd = std::fs::read(f.superblock(Some(f.b), f.d)).unwrap();
            let meta = f
                .src
                .load_object_bytes(ObjectType::CommitMeta, &f.b)
                .await
                .unwrap();
            let meta_d = f
                .src
                .load_object_bytes(ObjectType::CommitMeta, &f.d)
                .await
                .unwrap();
            let targets = vec![("main".to_owned(), f.d)];
            for (localcache, bodies, metadata) in [
                (
                    Vec::new(),
                    vec![&ab[..], &meta[..], &bd[..], &meta_d[..]],
                    4,
                ),
                (vec![f.src.clone()], vec![&ab[..], &bd[..]], 2),
            ] {
                let source = remote(&bodies).await;
                let source = DeltaSource::Remote(&source);
                let opts = PullOptions {
                    localcache_repos: localcache,
                    ..PullOptions::default()
                };
                let counters = PullCounters::new(None);
                let mut plan = discover(
                    &f.dst,
                    &source,
                    None,
                    &targets,
                    &opts,
                    TipChecks::new(opts.flags, TimestampBase::Off, RefPlace::Heads),
                    Some(Edges::new(list.clone()).unwrap()),
                    &ed25519_verification(),
                    RelatedRule::default(),
                    &counters,
                )
                .await
                .unwrap();
                assert_eq!(counters.metadata(), metadata);
                assert_eq!(plan.levels, [vec![f.b]]);
                let store = plan.store.as_ref().unwrap();
                let b = &plan.records[&f.b];
                let Detached::Checked {
                    kept: Some(kept), ..
                } = &b.detached
                else {
                    panic!("no kept .commitmeta");
                };
                assert_eq!(store.read(kept.clone()).await.unwrap(), meta);
                for (commit, bytes) in [(f.b, &ab), (f.d, &bd)] {
                    let range = plan.records[&commit].superblock.clone().unwrap();
                    assert_eq!(&store.read(range).await.unwrap(), bytes);
                }
                let jobs = plan.parse_level(&f.dst, &source, &[f.b]).await.unwrap();
                assert_eq!(Checksum::sha256(&jobs[&f.b].commit_bytes), f.b);
                let CommitCheck::Checked {
                    detached: Some(read),
                    ..
                } = plan.commit_check(&f.b).await.unwrap()
                else {
                    panic!("no checked .commitmeta");
                };
                assert_eq!(read, meta);
                let CommitCheck::Checked {
                    detached: Some(read),
                    ..
                } = plan.commit_check(&f.d).await.unwrap()
                else {
                    panic!("no checked .commitmeta of the target");
                };
                assert_eq!(read, meta_d);
                let jobs = plan.target_jobs(&f.dst, &source).await.unwrap();
                assert_eq!(jobs.keys().copied().collect::<Vec<_>>(), [f.d]);
                assert_eq!(Checksum::sha256(&jobs[&f.d].commit_bytes), f.d);
            }
        });
    }

    /// Returns the bytes that a server sends for one found reply for each of
    /// `bodies`, in order.
    async fn replies(bodies: &[&[u8]]) -> Vec<u8> {
        use crate::remote::proto::{FrameWriter, GetReply, Message};
        let mut writer = FrameWriter::new(futures_lite::io::Cursor::new(Vec::new()));
        for body in bodies {
            writer
                .write_message(&Message::GetReply(GetReply {
                    found: true,
                    len: Some(body.len() as u64),
                }))
                .await
                .unwrap();
            writer.write_object_data(body).await.unwrap();
            writer.end_object().await.unwrap();
        }
        writer.into_inner().into_inner()
    }

    /// The request bytes that the client of a gated session wrote, and the
    /// task that waits for more of them.
    #[derive(Default)]
    struct Requests {
        written: Vec<u8>,
        waker: Option<std::task::Waker>,
    }

    impl Requests {
        /// Returns `true` if the client wrote each path of `paths`.
        fn hold(&self, paths: &[String]) -> bool {
            paths.iter().all(|path| {
                self.written
                    .windows(path.len())
                    .any(|window| window == path.as_bytes())
            })
        }
    }

    /// The output of the client of a gated session. It keeps each byte and
    /// wakes the input.
    struct GatedOutput {
        requests: Arc<std::sync::Mutex<Requests>>,
    }

    impl futures_io::AsyncWrite for GatedOutput {
        fn poll_write(
            self: std::pin::Pin<&mut Self>,
            _: &mut std::task::Context<'_>,
            buf: &[u8],
        ) -> std::task::Poll<std::io::Result<usize>> {
            let mut requests = self.requests.lock().unwrap();
            requests.written.extend_from_slice(buf);
            if let Some(waker) = requests.waker.take() {
                waker.wake();
            }
            std::task::Poll::Ready(Ok(buf.len()))
        }

        fn poll_flush(
            self: std::pin::Pin<&mut Self>,
            _: &mut std::task::Context<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            std::task::Poll::Ready(Ok(()))
        }

        fn poll_close(
            self: std::pin::Pin<&mut Self>,
            _: &mut std::task::Context<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            std::task::Poll::Ready(Ok(()))
        }
    }

    /// The input of the client of a gated session. The server sends the
    /// bytes of each step of the script in order. It holds the bytes of a
    /// step until the client wrote each path of that step.
    struct GatedInput {
        requests: Arc<std::sync::Mutex<Requests>>,
        script: std::collections::VecDeque<(Vec<String>, Vec<u8>)>,
        /// The bytes of the current step, and the position of the next read.
        current: (Vec<u8>, usize),
    }

    impl futures_io::AsyncRead for GatedInput {
        fn poll_read(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
            buf: &mut [u8],
        ) -> std::task::Poll<std::io::Result<usize>> {
            loop {
                let (bytes, at) = &mut self.current;
                if *at < bytes.len() {
                    let n = buf.len().min(bytes.len() - *at);
                    buf[..n].copy_from_slice(&bytes[*at..*at + n]);
                    *at += n;
                    return std::task::Poll::Ready(Ok(n));
                }
                let Some((paths, _)) = self.script.front() else {
                    return std::task::Poll::Ready(Ok(0));
                };
                let requests = Arc::clone(&self.requests);
                let mut requests = requests.lock().unwrap();
                if !requests.hold(paths) {
                    requests.waker = Some(cx.waker().clone());
                    return std::task::Poll::Pending;
                }
                drop(requests);
                let (_, bytes) = self.script.pop_front().unwrap();
                self.current = (bytes, 0);
            }
        }
    }

    /// Returns a remote source whose server sends the bytes of each step of
    /// `script` in order, and the requests that its client writes. A step
    /// holds the paths that the client must write before the server sends
    /// its bytes.
    async fn gated_remote(
        script: Vec<(Vec<String>, Vec<u8>)>,
    ) -> (RemoteSource, Arc<std::sync::Mutex<Requests>>) {
        let requests = Arc::new(std::sync::Mutex::new(Requests::default()));
        let mut script: std::collections::VecDeque<_> = script.into();
        script.push_front((Vec::new(), served(&[]).await));
        let input = GatedInput {
            requests: Arc::clone(&requests),
            script,
            current: (Vec::new(), 0),
        };
        let output = GatedOutput {
            requests: Arc::clone(&requests),
        };
        let session = crate::remote::StreamSession::over_stream(input, output, Default::default())
            .await
            .unwrap();
        let source = RemoteSource::new(
            crate::remote::PullSession::Stream(session).into(),
            Vec::new(),
        );
        (source, requests)
    }

    /// Over a stream session, discovery sends the superblock request and the
    /// `.commitmeta` request of each step as one pair. The server of the test
    /// holds the reply to a superblock until the request of the `.commitmeta`
    /// arrives, so a discovery that sends them one after the other does not
    /// end. A localcache repository that holds the `.commitmeta` comes first,
    /// and discovery then sends the superblock request alone. The counts and
    /// the record file are as for a discovery with no pair.
    #[test]
    fn a_stream_discovery_sends_the_superblock_and_the_commitmeta_as_a_pair() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            sign(&f.src, &f.b).await;
            sign(&f.src, &f.d).await;
            let list = vec![f.delta(Some(f.a), f.b).await, f.delta(Some(f.b), f.d).await];
            let ab = std::fs::read(f.superblock(Some(f.a), f.b)).unwrap();
            let bd = std::fs::read(f.superblock(Some(f.b), f.d)).unwrap();
            let meta_b = f
                .src
                .load_object_bytes(ObjectType::CommitMeta, &f.b)
                .await
                .unwrap();
            let meta_d = f
                .src
                .load_object_bytes(ObjectType::CommitMeta, &f.d)
                .await
                .unwrap();
            let superblock = |from: Checksum, to: Checksum| {
                format!("{}/{SUPERBLOCK_FILE}", delta_relative_dir(Some(&from), &to))
            };
            let commitmeta = |commit: &Checksum| {
                format!(
                    "objects/{}",
                    ostrya_core::loose_path(commit, ObjectType::CommitMeta, RepoMode::Archive)
                )
            };
            let paired = vec![
                (
                    vec![superblock(f.a, f.b), commitmeta(&f.b)],
                    replies(&[&ab, &meta_b]).await,
                ),
                (
                    vec![superblock(f.b, f.d), commitmeta(&f.d)],
                    replies(&[&bd, &meta_d]).await,
                ),
            ];
            let cached = vec![
                (vec![superblock(f.a, f.b)], replies(&[&ab]).await),
                (vec![superblock(f.b, f.d)], replies(&[&bd]).await),
            ];
            let targets = vec![("main".to_owned(), f.d)];
            for (localcache, script, metadata) in
                [(Vec::new(), paired, 4), (vec![f.src.clone()], cached, 2)]
            {
                let (source, requests) = gated_remote(script).await;
                let source = DeltaSource::Remote(&source);
                let opts = PullOptions {
                    localcache_repos: localcache,
                    ..PullOptions::default()
                };
                let counters = PullCounters::new(None);
                let verification = ed25519_verification();
                let discovery = discover(
                    &f.dst,
                    &source,
                    None,
                    &targets,
                    &opts,
                    TipChecks::new(opts.flags, TimestampBase::Off, RefPlace::Heads),
                    Some(Edges::new(list.clone()).unwrap()),
                    &verification,
                    RelatedRule::default(),
                    &counters,
                );
                let plan = futures_lite::future::or(discovery, async {
                    ostrya_rt::Timer::after(std::time::Duration::from_secs(10)).await;
                    panic!("discovery sent the requests of a step one after the other");
                })
                .await
                .unwrap();
                assert_eq!(counters.metadata(), metadata);
                let written = requests.lock().unwrap().written.clone();
                let position = |path: String| {
                    written
                        .windows(path.len())
                        .position(|window| window == path.as_bytes())
                };
                if opts.localcache_repos.is_empty() {
                    // The superblock request of a step comes first.
                    for (from, to) in [(f.a, f.b), (f.b, f.d)] {
                        assert!(position(superblock(from, to)) < position(commitmeta(&to)));
                    }
                } else {
                    assert_eq!(position(".commitmeta".to_owned()), None);
                }
                let store = plan.store.as_ref().unwrap();
                for (commit, meta) in [(f.b, &meta_b), (f.d, &meta_d)] {
                    let Detached::Checked {
                        kept: Some(kept), ..
                    } = &plan.records[&commit].detached
                    else {
                        panic!("no kept .commitmeta of {commit}");
                    };
                    assert_eq!(&store.read(kept.clone()).await.unwrap(), meta);
                }
                for (commit, bytes) in [(f.b, &ab), (f.d, &bd)] {
                    let range = plan.records[&commit].superblock.clone().unwrap();
                    assert_eq!(&store.read(range).await.unwrap(), bytes);
                }
            }
        });
    }

    /// Over a stream session, the remote does not hold the superblock of the
    /// first planned step, `a->d`, and serves the paired `.commitmeta` of `d`.
    /// Discovery drops that `.commitmeta`, plans again over `a->c` and `c->d`,
    /// and requests the `.commitmeta` of `d` again. The session stays usable,
    /// and the record of `d` keeps the `.commitmeta` of the second request.
    #[test]
    fn a_stream_pair_with_a_missing_superblock_plans_again() {
        ostrya_rt::block_on(async {
            use crate::remote::proto::{FrameWriter, GetReply, Message};
            let f = Fixture::new().await;
            sign(&f.src, &f.c).await;
            sign(&f.src, &f.d).await;
            let missing = AdvertisedDelta {
                from: Some(f.a),
                to: f.d,
                superblock: checksum(0x11),
            };
            let list = vec![
                missing,
                f.delta(Some(f.a), f.c).await,
                f.delta(Some(f.c), f.d).await,
            ];
            let ac = std::fs::read(f.superblock(Some(f.a), f.c)).unwrap();
            let cd = std::fs::read(f.superblock(Some(f.c), f.d)).unwrap();
            let meta_c = f
                .src
                .load_object_bytes(ObjectType::CommitMeta, &f.c)
                .await
                .unwrap();
            let meta_d = f
                .src
                .load_object_bytes(ObjectType::CommitMeta, &f.d)
                .await
                .unwrap();
            let superblock = |from: Checksum, to: Checksum| {
                format!("{}/{SUPERBLOCK_FILE}", delta_relative_dir(Some(&from), &to))
            };
            let commitmeta = |commit: &Checksum| {
                format!(
                    "objects/{}",
                    ostrya_core::loose_path(commit, ObjectType::CommitMeta, RepoMode::Archive)
                )
            };
            let mut not_found = FrameWriter::new(futures_lite::io::Cursor::new(Vec::new()));
            not_found
                .write_message(&Message::GetReply(GetReply {
                    found: false,
                    len: None,
                }))
                .await
                .unwrap();
            let mut first = not_found.into_inner().into_inner();
            first.extend(replies(&[&meta_d]).await);
            let script = vec![
                (vec![superblock(f.a, f.d), commitmeta(&f.d)], first),
                (
                    vec![superblock(f.a, f.c), commitmeta(&f.c)],
                    replies(&[&ac, &meta_c]).await,
                ),
                (vec![superblock(f.c, f.d)], replies(&[&cd, &meta_d]).await),
                (vec!["config".to_owned()], replies(&[b"after"]).await),
            ];
            let (source, requests) = gated_remote(script).await;
            let source = DeltaSource::Remote(&source);
            let counters = PullCounters::new(None);
            let targets = vec![("main".to_owned(), f.d)];
            let opts = PullOptions::default();
            let verification = ed25519_verification();
            let discovery = discover(
                &f.dst,
                &source,
                None,
                &targets,
                &opts,
                TipChecks::new(opts.flags, TimestampBase::Off, RefPlace::Heads),
                Some(Edges::new(list).unwrap()),
                &verification,
                RelatedRule::default(),
                &counters,
            );
            let plan = futures_lite::future::or(discovery, async {
                ostrya_rt::Timer::after(std::time::Duration::from_secs(10)).await;
                panic!("discovery sent the requests of a step one after the other");
            })
            .await
            .unwrap();
            // The superblock requests count three, and the `.commitmeta`
            // files that the remote serves count three: `d` twice and `c`
            // once. Over HTTP the count is 5, because the pull requests no
            // `.commitmeta` for the missing superblock.
            assert_eq!(counters.metadata(), 6);
            let written = String::from_utf8_lossy(&requests.lock().unwrap().written).into_owned();
            assert_eq!(written.matches(&commitmeta(&f.d)).count(), 2);
            assert_eq!(plan.levels, [vec![f.c]]);
            assert!(plan.checked(&f.c) && plan.checked(&f.d));
            let CommitCheck::Checked {
                detached: Some(read),
                ..
            } = plan.commit_check(&f.d).await.unwrap()
            else {
                panic!("no checked .commitmeta of the target");
            };
            assert_eq!(read, meta_d);
            let after = source
                .read("config", 1024, &PullCounters::new(None))
                .await
                .unwrap();
            assert_eq!(after.as_deref(), Some(&b"after"[..]));
        });
    }

    /// The record file keeps the raw superblock, and a record reads it back
    /// from there, also after the source drops the superblock.
    #[test]
    fn the_record_file_keeps_the_superblock() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let delta = f.delta(Some(f.a), f.b).await;
            let mut store = RecordStore::new(&f.dst);
            assert!(store.file.is_none());
            let range = store
                .append(b"padding".to_vec(), || "padding".to_owned())
                .await
                .unwrap();
            assert_eq!(range, 0..7);
            assert_eq!(store.read(range).await.unwrap(), b"padding");
            let source = DeltaSource::Local(&f.src);
            let (fetched, kept) = fetch_job(
                &source,
                delta.from,
                delta.to,
                Some(delta.superblock),
                Some(&unverified()),
                &PullCounters::new(None),
                Some(Keep::Own(&mut store)),
            )
            .await
            .unwrap()
            .unwrap();
            let len = std::fs::metadata(f.superblock(delta.from, delta.to))
                .unwrap()
                .len();
            let kept = kept.map(|kept| kept.superblock);
            assert_eq!(kept, Some(7..7 + len));
            let record = StepRecord {
                delta,
                parts: fetched.parts(),
                superblock: kept,
                detached: Detached::NotChecked,
            };
            std::fs::remove_file(f.superblock(delta.from, delta.to)).unwrap();
            let read = read_record(Some(&store), &source, &record).await.unwrap();
            assert_eq!(read.commit_bytes, fetched.commit_bytes);
            assert_eq!(Checksum::sha256(&read.commit_bytes), f.b);
            assert_eq!(read.meta_entries.len(), fetched.meta_entries.len());
        });
    }

    /// The record file takes bytes up to its limit. One more byte fails with
    /// `Error::Pull`, which names the limit, and the file stays as it was.
    #[test]
    fn the_record_file_stops_at_its_limit() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let mut store = RecordStore {
                limit: 10,
                ..RecordStore::new(&f.dst)
            };
            let range = store
                .append(vec![0x5a; 10], || "ten bytes".to_owned())
                .await
                .unwrap();
            assert_eq!(range, 0..10);
            let err = store
                .append(vec![0x5a], || "one byte".to_owned())
                .await
                .err()
                .unwrap();
            let Error::Pull(message) = &err else {
                panic!("{err:?}");
            };
            assert!(message.contains("one byte"), "{message}");
            assert!(message.contains("10 bytes"), "{message}");
            assert_eq!(store.len, 10);
            let file = store.file.as_ref().unwrap();
            assert_eq!(file.metadata().unwrap().len(), 10);
            assert_eq!(store.read(0..10).await.unwrap(), [0x5a; 10]);
        });
    }

    /// A superblock that would pass the limit of the record file fails
    /// before the file opens. The request still counts.
    #[test]
    fn a_superblock_past_the_limit_fails_before_the_write() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let delta = f.delta(Some(f.a), f.b).await;
            let len = std::fs::metadata(f.superblock(delta.from, delta.to))
                .unwrap()
                .len();
            let mut store = RecordStore {
                limit: len - 1,
                ..RecordStore::new(&f.dst)
            };
            let counters = PullCounters::new(None);
            let err = fetch_job(
                &DeltaSource::Local(&f.src),
                delta.from,
                delta.to,
                Some(delta.superblock),
                Some(&unverified()),
                &counters,
                Some(Keep::Own(&mut store)),
            )
            .await
            .err()
            .unwrap();
            let Error::Pull(message) = &err else {
                panic!("{err:?}");
            };
            assert!(
                message.contains(&delta_name(delta.from.as_ref(), &delta.to)),
                "{message}"
            );
            assert!(store.file.is_none());
            assert_eq!(store.len, 0);
            assert_eq!(counters.metadata(), 1);
        });
    }

    /// The record file of the search for the deltas of the dependencies
    /// keeps the superblock and then the commit that it carries, and opens
    /// at the first write. A superblock past the limit fails before the file
    /// opens, and a commit past the limit fails after the superblock. Each
    /// error names the limit and the dependency search.
    #[test]
    fn the_dependency_record_file_keeps_the_commit_and_stops_at_its_limit() {
        ostrya_rt::block_on(async {
            let f = Fixture::new().await;
            let delta = f.delta(Some(f.a), f.b).await;
            let len = std::fs::metadata(f.superblock(delta.from, delta.to))
                .unwrap()
                .len();
            let source = &DeltaSource::Local(&f.src);
            let fetch = |store: Arc<Mutex<RecordStore>>| async move {
                let result = fetch_job(
                    source,
                    delta.from,
                    delta.to,
                    Some(delta.superblock),
                    None,
                    &PullCounters::new(None),
                    Some(Keep::Shared(&store)),
                )
                .await;
                let store = Arc::into_inner(store).unwrap().into_inner().unwrap();
                (result, store)
            };
            let name = delta_name(delta.from.as_ref(), &delta.to);

            let store = RecordStore::for_dependencies(&f.dst);
            assert!(store.file.is_none());
            let (result, store) = fetch(Arc::new(Mutex::new(store))).await;
            let (fetched, kept) = result.unwrap().unwrap();
            let kept = kept.unwrap();
            assert_eq!(kept.superblock, 0..len);
            let commit = kept.commit.unwrap();
            assert_eq!(commit.start, len);
            assert_eq!(store.len, commit.end);
            let bytes = store.read(commit).await.unwrap();
            assert_eq!(bytes, fetched.commit_bytes);
            assert_eq!(Checksum::sha256(&bytes), f.b);

            for (limit, what, opened) in [
                (
                    len - 1,
                    format!("the superblock of static delta {name}"),
                    false,
                ),
                (len, format!("the commit of static delta {name}"), true),
            ] {
                let store = RecordStore {
                    limit,
                    ..RecordStore::for_dependencies(&f.dst)
                };
                let (result, store) = fetch(Arc::new(Mutex::new(store))).await;
                let Some(Error::Pull(message)) = result.err() else {
                    panic!("no limit error at {limit}");
                };
                assert!(
                    message.starts_with("static deltas of the dependencies: "),
                    "{message}"
                );
                assert!(message.contains(&what), "{message}");
                assert!(message.contains(&format!("{limit} bytes")), "{message}");
                assert_eq!(store.file.is_some(), opened);
                assert_eq!(store.len, if opened { len } else { 0 });
            }
        });
    }

    /// The step of the commit takes the fallbacks of the head of a
    /// dependency delta, and drops the range of its commit. A head with
    /// parts stays for the load step. A head with no part has no load step,
    /// so it goes there.
    #[test]
    fn the_step_of_the_commit_takes_the_commit_data_of_a_head() {
        let found = DependencyDeltas::default();
        let fallback = ObjectName::new(checksum(9), ObjectType::File);
        for (commit, parts) in [(checksum(1), 0), (checksum(2), 2)] {
            found.heads.lock().unwrap().insert(
                commit,
                DependencyHead {
                    from: None,
                    superblock: 0..10,
                    parts,
                    commit: Some(10..20),
                    fallbacks: vec![fallback],
                },
            );
            assert!(found.holds_commit_data(&commit));
        }

        assert_eq!(
            found.take_commit_delta(&checksum(1)),
            Some((0, vec![fallback]))
        );
        assert!(!found.has_head(&checksum(1)));

        assert_eq!(
            found.take_commit_delta(&checksum(2)),
            Some((2, vec![fallback]))
        );
        assert!(found.has_head(&checksum(2)));
        assert!(!found.holds_commit_data(&checksum(2)));

        found.release_job(&checksum(2));
        assert!(found.is_empty());
    }
}