ostrya 0.16.0

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
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
//! The pull from a remote, over HTTP or over ssh.
//!
//! [`Repo::pull`], [`Repo::pull_with_session`],
//! [`Repo::remote_fetch_summary`], and [`Repo::remote_fetch_summary_with`]
//! are the entry points. [`Repo::pull`] holds
//! the rules of the pull. [`Repo::pull`] and [`Repo::pull_with_session`] run
//! one engine.
//!
//! The loop that drives the steps owns the plan, so the plan needs no lock.
//! The pull spawns no task: the step futures borrow the repository, the
//! transaction, and the fetcher. The walk of a subpath pull obeys the rules in
//! `subpath`.
//!
//! The plan walks a dirtree when it applies the step of the dirtree, under
//! each position that reached the dirtree by then. If a later position widens
//! that scope, the plan walks the dirtree again from the transaction.
//!
//! With a list of static deltas, the loop runs the plan one time for each
//! level of intermediate commits, and then one time for the targets, in one
//! transaction. Each run starts from the objects that the earlier runs
//! queued.

use std::collections::{HashMap, HashSet, VecDeque};
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, ready};
use std::time::Instant;

use async_compression::futures::bufread::DeflateDecoder;
use futures_io::AsyncRead;
use futures_lite::{AsyncReadExt, AsyncWriteExt};
use ostrya_core::{
    Checksum, Commit, DirTree, FileHeader, ObjectName, ObjectType, Ref, RepoMode, Value, loose_path,
};

use crate::config::RepoConfig;
use crate::delta::IO_CHUNK;
use crate::endpoint::{EndpointOverrides, resolve_pull};
use crate::error::{Error, Result};
use crate::fetch::gate::Gate;
use crate::fetch::{FetchRequest, Fetched, Fetcher, Priority};
use crate::inflate::BufSource;
use crate::object::{MAX_FILE_HEADER_SIZE, MAX_METADATA_SIZE};
use crate::read::CommitState;
use crate::refs::{HEADS_DIR, MIRRORS_DIR};
use crate::related::{self, RelatedRule};
use crate::remote::{Endpoint, PullSession, StreamSessionOptions};
use crate::repo::Repo;
use crate::repo_fs::{Publish, RootFile};
use crate::summary::{COLLECTION_ID_KEY, Summary, collection_map_refs};
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::verify::PullTrust;
use crate::verify::trust::FieldGroup;
use crate::write::FileMeta;

use super::attachment;
use super::chain::Edges;
use super::delta::{
    self, AttachmentDeltas, CommitCheck, DeltaAdvert, DeltaJob, DeltaPlan, DeltaSource, PART_CAP,
};
use super::drive::Slots;
use super::source::{Connection, RemoteSource, RootFiles, Transfer, http_error, session_error};
use super::subpath::{Scope, Subpaths};
use super::verify::Verification;
use super::{
    CheckedMeta, ChecksumTargets, ModeChecks, Operand, Pinned, PullCounters, PullFlags,
    PullOptions, PullReport, PullStats, PullVerify, READ_CHUNK, RefPlace, TimestampBase, TipChecks,
    apply_durability, check_commit_operands, check_commit_signatures_filtered, check_depth,
    check_one_place, check_remote_operands, check_remote_option, check_static_deltas,
    check_tip_refs, commit_operands_alone, completes_marked, operand_collection,
    take_static_deltas,
};

/// The number of fetched content objects that stream into the object store at
/// once.
const WRITE_THROTTLE: usize = 3;

/// The cap on the repository-root files that a pull fetches (`summary`,
/// `summary.sig`, `config`). The local summary reader applies the same cap.
pub(super) const MAX_ROOT_FILE: u64 = 64 * 1024 * 1024;
/// The cap on a fetched ref file of a remote, which holds 64 hex characters
/// and a newline.
const MAX_REF_FILE: u64 = 1024;

/// The name of the config file at the repository root.
pub(super) const CONFIG_FILE: &str = "config";

/// Methods that pull from a remote over HTTP or ssh.
impl Repo {
    /// Pulls refs and their objects from a remote over HTTP or over ssh.
    ///
    /// `remote` names a `[remote "<name>"]` section of the config of this
    /// repository. The section gives the signature policy and the keys
    /// `pull-branches` and `branches`. By default, the name gives the prefix
    /// of the written refs.
    /// [`remote`](PullOptions::remote) and [`MIRROR`](PullFlags::MIRROR)
    /// change this. The section also gives the address, the TLS material, and
    /// the proxy, and [`overrides`](PullOptions::overrides) changes them. The
    /// pull fetches the objects into one transaction, publishes them, and then
    /// writes the refs. It returns the statistics of the pull.
    /// [`pull_with_report`](Repo::pull_with_report) also returns the refs that
    /// the pull changed.
    ///
    /// The module [`pull`](mod@crate::pull) states the rules of the
    /// `.commitpartial` markers. It also states the concurrency, the write
    /// permits, the memory, the connections, and the retries of this pull.
    ///
    /// [`pull_local`](Repo::pull_local) states the write order of the detached
    /// metadata and the mode checks of a content object. These rules apply to
    /// this pull too.
    ///
    /// [`PullOptions`] states which fields each pull reads, and
    /// [`PullVerify`] holds the signature policy.
    ///
    /// # Address
    ///
    /// The pull calls [`resolve_pull`] with
    /// [`overrides`](PullOptions::overrides), and reads the remote at the
    /// endpoint that it returns. `resolve_pull` reads the address from
    /// [`EndpointOverrides::url`], or else from the remote key `pull-url` or
    /// `url`, and states the rules of the address.
    ///
    /// An [`Endpoint::Http`] gives an HTTP pull through the fetcher, and an
    /// [`Endpoint::Ssh`] gives a pull over ssh. The fetcher gets each mirror
    /// as written, and it refuses a scheme other than `http` and `https`.
    /// With the `s3` feature, an `Endpoint::S3` gives an HTTP pull through a
    /// fetcher that signs each request. The module [`pull`](mod@crate::pull)
    /// states its rules in "Bucket repository".
    ///
    /// The pull reads the trust of the remote with
    /// [`PullTrust::from_remote`] before it opens the session, with the trust
    /// group of [`trust_group`](PullOptions::trust_group) if the field is set.
    /// So a refused policy starts no fetcher and no ssh client. Then the pull runs as
    /// [`pull_with_session`](Repo::pull_with_session) with that session and
    /// that trust, with the keys `pull-branches` and `branches` and the
    /// summary copy of this method.
    ///
    /// # Refs
    ///
    /// The pull resolves each requested ref against the summary of the remote.
    /// If the summary does not list the ref, or the remote serves no summary,
    /// the pull reads `refs/heads/<ref>` of the remote.
    /// [`refs`](PullOptions::refs) states what an empty list takes.
    ///
    /// If [`refs`](PullOptions::refs) is empty and
    /// [`MIRROR`](PullFlags::MIRROR) is not set, the pull reads the key
    /// `pull-branches` of the section with
    /// [`Remote::pull_branches`](crate::config::Remote::pull_branches) and
    /// the key `branches` of the section. The pull takes each ref of
    /// `branches` and each ref of the summary that `pull-branches` selects.
    /// [`Remote::pull_branches`](crate::config::Remote::pull_branches) states
    /// the rules of the two keys together. The own id of the
    /// match is the `ostree.summary.collection-id` of the summary. A ref
    /// `NAME` of field 0 of the summary is written as a requested ref
    /// `NAME` is. A ref `NAME` of the entry of `ID` in
    /// `ostree.summary.collection-map` is the ref `@ID:NAME`, and the pull
    /// writes it and checks its tip as a requested `@ID:NAME` ref. The pull
    /// parses the keys `pull-branches` and `branches` before it resolves the
    /// endpoint, and checks each name of `branches` with the ref-name rule.
    /// So a malformed value of either key stops the pull before its first
    /// request. The pull matches the refs of the summary after it reads the
    /// summary and the `config` of the remote, and before it reads a ref file
    /// or an object.
    ///
    /// [`remote`](PullOptions::remote) and [`MIRROR`](PullFlags::MIRROR)
    /// select the prefix of the written refs.
    /// [`no_ref_writes`](PullOptions::no_ref_writes) turns the ref writes off.
    ///
    /// A requested ref is a ref `NAME` or a collection ref `@ID:NAME`. One
    /// pull takes both forms, and the refs of more than one collection. The
    /// pull refuses a remote ref `REMOTE:NAME` and a `^` suffix. For an
    /// `@ID:NAME` ref:
    ///
    /// - The pull reads field 0 of the summary if the
    ///   `ostree.summary.collection-id` of the summary is `ID`, and else the
    ///   entry of `ID` of `ostree.summary.collection-map`.
    /// - If the summary does not list the ref, or the remote serves no
    ///   summary, the pull reads `refs/heads/<NAME>` of the remote if the
    ///   collection id of the remote is `ID`, and else
    ///   `refs/mirrors/<ID>/<NAME>`. The collection id of the remote is the
    ///   `[core] collection-id` of the `config` of the remote. If the remote
    ///   serves no config, or the config has no collection id, it is the
    ///   `ostree.summary.collection-id` of the summary.
    /// - The pull writes the collection ref `refs/mirrors/<ID>/<NAME>`, or
    ///   the local ref `refs/heads/<NAME>` if `ID` is the
    ///   `[core] collection-id` of this repository, whatever
    ///   [`remote`](PullOptions::remote) holds.
    /// - The `ostree.collection-binding` of the tip must state `ID`. A tip
    ///   with another binding, with no binding, or with a binding that is not
    ///   a string fails the pull with [`Error::Pull`].
    ///   [`DISABLE_VERIFY_BINDINGS`](PullFlags::DISABLE_VERIFY_BINDINGS) does
    ///   not turn this check off. Under
    ///   [`no_ref_writes`](PullOptions::no_ref_writes), the pull does not
    ///   make it.
    /// - The ref-binding check reads `NAME`.
    ///
    /// A commit operand names its commit by the checksum, 64 lowercase hex
    /// characters. The pull fetches that commit. It reads no entry of the
    /// summary and no ref file of the remote for the operand, so its ref need
    /// not be a ref of the remote. [`commit_operand`](crate::commit_operand)
    /// makes the text of the second and the third form:
    ///
    /// - `CHECKSUM` writes no ref, and the pull makes no ref-binding check of
    ///   the commit. If the section of the remote in the config of this
    ///   repository states the key `collection-id`, the
    ///   `ostree.collection-binding` of the commit must state that id, also
    ///   under [`no_ref_writes`](PullOptions::no_ref_writes). With no such
    ///   key, the pull makes no collection-binding check. The pull reads the
    ///   key for this operand form alone, before it connects. Under
    ///   [`TimestampCheck::Rev`](crate::TimestampCheck::Rev), the pull
    ///   compares the commit with the commit of the check. The pull refuses
    ///   the operand under
    ///   [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef).
    /// - `NAME@CHECKSUM` writes the ref that `NAME` writes, to the commit.
    ///   The ref-binding check reads `NAME`, and the timestamp check reads
    ///   the ref that the pull writes. The `ostree.collection-binding` of the
    ///   commit must state the `[core] collection-id` of this repository. If
    ///   this repository has no collection id, the commit must have no
    ///   `ostree.collection-binding` key.
    ///   [`DISABLE_VERIFY_BINDINGS`](PullFlags::DISABLE_VERIFY_BINDINGS) does
    ///   not turn this check off. Under
    ///   [`no_ref_writes`](PullOptions::no_ref_writes), the pull does not
    ///   make it.
    /// - `@ID:NAME@CHECKSUM` writes the ref of `@ID:NAME` to the commit, and
    ///   has the checks of an `@ID:NAME` ref.
    ///
    /// The checksum part of an operand starts after the last `@` that is not
    /// the first character. The pull refuses an operand whose checksum part
    /// is not 64 lowercase hex characters. A name of 64 hex characters that
    /// holds an uppercase character is a ref name. The `NAME` part of
    /// `NAME@CHECKSUM` can be 64 lowercase hex characters, and is then the
    /// name of the ref. If [`refs`](PullOptions::refs) holds a `CHECKSUM`
    /// operand and the operand `CHECKSUM@CHECKSUM` of the same checksum, the
    /// pull takes the second alone: it writes the ref and makes the checks of
    /// `NAME@CHECKSUM`.
    /// [`depth`](PullOptions::depth),
    /// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY),
    /// [`subpaths`](PullOptions::subpaths), the attachments, and the
    /// signature checks apply to the commit of a commit operand as to the tip
    /// of a ref.
    ///
    /// If each name of [`refs`](PullOptions::refs) is a commit operand, the
    /// pull requests no `summary` and no `summary.sig`, and the summary
    /// policy of [`PullVerify`] does not apply. A pull with at least one
    /// other name reads and verifies the summary, and a commit operand takes
    /// no ref from it.
    ///
    /// Under [`MIRROR`](PullFlags::MIRROR), a plain ref `NAME` of a remote
    /// whose summary states the `ostree.summary.collection-id` `ID` is the
    /// ref `@ID:NAME`. The pull reads it as the plain ref `NAME`: from field
    /// 0 of the summary, and else from `refs/heads/<NAME>` of the remote. It
    /// writes the ref and checks the bindings of its tip as for an `@ID:NAME`
    /// ref. A plain ref of a remote with no summary, or with a summary that
    /// states no collection id, is the local ref `refs/heads/<NAME>`. A
    /// mirror pull of every ref takes each ref of field 0 by the same rule,
    /// and each ref `NAME` of the entry of `ID` of
    /// `ostree.summary.collection-map` as the ref `@ID:NAME`. Under `MIRROR`,
    /// a `NAME@CHECKSUM` operand writes the local ref `refs/heads/<NAME>`,
    /// whatever the summary states.
    ///
    /// A name that occurs two times counts one time. Two other names that
    /// write one ref stop the pull with [`Error::Pull`], which states both
    /// names as given and the path of the ref. An example is `NAME` and
    /// `NAME@CHECKSUM`. Examples under `MIRROR` are `NAME` and `@ID:NAME`
    /// from a remote whose summary states the collection id `ID`, and `NAME`
    /// and `@OWN:NAME`, where `OWN` is the `[core] collection-id` of this
    /// repository, from a remote whose summary states no collection id. A
    /// `CHECKSUM` operand writes no ref and has no part in this check. The
    /// pull makes this check after it reads the summary and the `config` of
    /// the remote, and before it reads a ref file or an object. Under
    /// [`no_ref_writes`](PullOptions::no_ref_writes), a pull of the names in
    /// [`refs`](PullOptions::refs) does not make this check, and fetches the
    /// commit of each name.
    ///
    /// # Proxy
    ///
    /// An HTTP pull connects through the proxy of the endpoint.
    /// [`resolve_pull`] reads it from the
    /// remote key `proxy`. With the `http://`, `socks5://`, or `socks5h://`
    /// proxy URL of that key, the pull connects through the proxy for every origin, and
    /// ignores `no_proxy`. If
    /// the key is absent or empty, the pull reads the proxy environment
    /// variables.
    ///
    /// # Pull over ssh
    ///
    /// For an ssh endpoint, the pull runs the ssh client after it resolves the
    /// signature policy. The [`SshOptions`](crate::remote::SshOptions) of the
    /// endpoint give the commands of the client, by the rules of
    /// [`StreamSession::connect`](crate::remote::StreamSession::connect).
    ///
    /// `resolve_pull` reads no remote key that applies to HTTP alone for an
    /// ssh address: `contenturl`, `metalink`, `proxy`, and the `tls-*` keys.
    /// For an HTTP address, it reads neither `ssh-command` nor
    /// `send-command`.
    ///
    /// The pull reads the remote through a source: the HTTP source over the
    /// fetcher, or the stream source over a stream session.
    /// [`PullSession::over_stream`] opens a stream session over a pair of
    /// streams, for [`pull_with_session`](Repo::pull_with_session). The two
    /// sources serve the same paths under the same caps. Each rule of this
    /// method applies to both sources, with these differences:
    ///
    /// - The stream source requests a ref by its name as written, with no
    ///   percent-encoding.
    /// - The stream source never sends a request again. A failure ends its
    ///   session and the pull.
    /// - The stream source keeps the requests of `summary.sig`, `summary`, and
    ///   `config` in flight together, in the order of the HTTP source. It does
    ///   the same for a `.commitmeta` and its commit, so a parent commit costs
    ///   one round trip. It also does the same for the superblock of a step of
    ///   a [`static_deltas`](PullOptions::static_deltas) chain and the
    ///   `.commitmeta` of the commit of the step, the superblock first, as
    ///   `# Static deltas` states. The HTTP source sends these requests one at
    ///   a time, except `summary.sig` and `summary` of a bucket repository.
    ///   The module [`pull`](mod@crate::pull) states that exception in
    ///   "Bucket repository".
    /// - The stream source ends its session before the transaction commits.
    ///   It closes the input of the server and, over ssh, waits for the ssh
    ///   client.
    ///
    /// # Requests
    ///
    /// The pull first requests `summary.sig`, `summary`, and `config`, in this
    /// order, and then the objects. A remote with no summary answers 404. A
    /// pull whose names are all commit operands requests `config` alone of
    /// these three files. The
    /// HTTP source percent-encodes each byte of a ref name outside the
    /// unreserved set of RFC 3986, except `/`.
    ///
    /// The remote must be an `archive` repository. The pull requests each
    /// content object as `objects/<..>.filez`, whatever the remote stores on
    /// its disk. That is the one form of a content object that an HTTP client
    /// can read: the framed, deflated payload behind its header.
    ///
    /// The pull reads `config` before the first object request. If `config`
    /// states a different mode, the pull fails. If the remote serves no
    /// `config`, the pull reads the remote as `archive`.
    ///
    /// # Commits
    ///
    /// The pull fetches a commit object before the objects that it references,
    /// because its tree is unknown until it arrives. The pull stages the commit
    /// when it arrives, so the verification of its name fails a wrong commit
    /// before the request of its tree. Nothing of the commit stays in memory
    /// after the step.
    ///
    /// The step that fetches a commit writes its `.commitpartial` marker. The
    /// module [`pull`](mod@crate::pull) states the rules of the markers.
    ///
    /// The pull fetches each object once, also if several commits reach it.
    /// The step that fetches a commit makes the ref-binding check and the
    /// timestamp check of each requested ref that names the commit. So two
    /// refs at one commit get both checks. For a commit of a chain of a
    /// [`static_deltas`](PullOptions::static_deltas) list, discovery makes
    /// these checks before the transaction opens, as `# Static deltas`
    /// states.
    ///
    /// The pull queues no object of the tree of a commit that this repository
    /// holds complete. It follows the parent of that commit all the same, so a
    /// pull extends the history that a shallower pull left.
    ///
    /// # Attachments
    ///
    /// Field 2 of a commit names the attachments of the commit.
    /// [`read_commit_relations`](Repo::read_commit_relations) reads them. The pull
    /// takes the full set of attachments of each commit that it reads: each
    /// target, and each parent that [`depth`](PullOptions::depth) takes. It
    /// also takes the full set of attachments of a target or a parent that
    /// this repository holds complete. The full set is the attachments of the
    /// commit, the attachments of each attachment, and so on, level by level,
    /// until a level has no new attachment.
    ///
    /// - The pull fetches each attachment at depth 0, so an attachment entry
    ///   adds no parent to the pull. The pull fetches an attachment one time,
    ///   also if several commits name it.
    /// - The pull fetches the attachments one level at a time. A level holds
    ///   the attachments that the commits of the level above name and that the
    ///   pull did not reach. The first level holds the attachments of the
    ///   targets, of the parents, and of the commits of the chains of static
    ///   deltas.
    /// - The pull reads field 2 of an attachment that this repository holds
    ///   complete from the commit object of this repository, and takes each
    ///   attachment that it names, level by level. A repository that the
    ///   `ostree` command wrote can hold a commit complete with its
    ///   attachments absent. The pull reads each commit at most one time.
    /// - The pull writes no ref for an attachment.
    /// - The pull checks no signature of an attachment commit. Field 2 holds the
    ///   checksum of the attachment, and the checksum and the signatures of
    ///   the commit that names it cover field 2. The pull hashes the
    ///   attachment commit that it stores and compares the result with that
    ///   checksum. The pull makes no ref-binding check, no
    ///   collection-binding check, and no timestamp check on an attachment.
    /// - A target, a parent that [`depth`](PullOptions::depth) takes, and a
    ///   commit of a chain of static deltas keep the checks of that role,
    ///   also if a field 2 names them.
    /// - An attachment is a commit of the pull for each other rule. A
    ///   localcache repository can supply it. The pull stores the
    ///   `.commitmeta` of an attachment that it fetches, under the rule of
    ///   `[ex-ostrya] keep-detached-related`.
    /// - For an attachment that this repository holds complete, the pull
    ///   requests no `.commitmeta` and no object of its tree. So the
    ///   attachment does not get the signatures that the remote added after
    ///   this repository stored it. A pull that takes the attachment as a
    ///   target requests its `.commitmeta`. An attachment that this repository
    ///   holds partial gets its whole tree and its `.commitmeta`.
    /// - The pull fetches the attachments after the commits that name them.
    ///   It looks for a static delta of each attachment of a level after the
    ///   run of the level above, as `# Static deltas` states. An attachment
    ///   with no delta comes as loose objects.
    /// - The pull does not follow a supplement: a commit that the detached
    ///   metadata key `ostrya.related` names.
    ///
    /// A [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull and a pull with
    /// [`subpaths`](PullOptions::subpaths) fetch no attachment. They check the
    /// format of the entries of field 2 of each commit that they read all the
    /// same.
    ///
    /// These cases fail the pull, and the pull writes no object and no ref:
    ///
    /// - An entry of field 2 has an empty name or a checksum that is not 32
    ///   bytes.
    /// - Neither this repository, a localcache repository, nor the remote
    ///   holds an attachment, at any level. This is also true for a parent
    ///   that none of them holds, if a commit of the pull names that parent as
    ///   an attachment.
    ///
    /// The error of an attachment that no source holds names one commit that
    /// names the attachment. Of the commits that name it, the pull takes those
    /// of the lowest level, and of these the commit with the lowest checksum.
    /// The targets, the parents, and the commits of the chains of static
    /// deltas are level 0, and the attachments of the first level are level 1.
    /// The entry name is the name of the first entry of that commit that names
    /// the attachment. The pull gives the error when the run of the level
    /// ends. If several attachments fail in one run, the error names the
    /// attachment with the lowest checksum. So the error does not change with
    /// the order in which the fetches end.
    ///
    /// The pull makes no check of a `.commitpartial` marker on the remote. If
    /// the remote holds an attachment partial, the pull fails on the first
    /// object of the attachment that the remote does not hold.
    ///
    /// # Detached metadata
    ///
    /// The pull requests the `.commitmeta` of a commit before the commit
    /// object. It requests no `.commitmeta` of an attachment that this
    /// repository holds complete, as `# Attachments` states. It stages the
    /// `.commitmeta` in the transaction when the commit object arrives, so no
    /// `.commitmeta` stays for a parent that the remote answers 404 for.
    /// [`pull_local`](Repo::pull_local) states when the transaction writes it
    /// and what a failure leaves.
    ///
    /// If `[ex-ostrya] keep-detached-related` of this repository is `false`
    /// ([`RepoConfig::keep_detached_related`](crate::RepoConfig::keep_detached_related)),
    /// the pull drops `ostrya.related` from each `.commitmeta` that it stores,
    /// also through a static delta.
    ///
    /// # Verification
    ///
    /// The pull stores each fetched object under the name that it requested.
    /// The write path hashes what it stores and compares the result with that
    /// name. So a corrupt or substituted object fails the pull, and the pull
    /// publishes nothing. No flag turns this verification off, so the pull
    /// ignores [`UNTRUSTED`](PullFlags::UNTRUSTED).
    ///
    /// The pull makes the mode checks of
    /// [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES) and of a
    /// `bare-user-only` destination over the header of a content object.
    ///
    /// The header also declares the size of the decompressed payload. This
    /// size bounds the stream on both sides:
    ///
    /// - A payload larger than the declared size fails the pull. So a corrupt
    ///   or expanding stream writes at most the declared size before the
    ///   checksum comparison at the end of the payload.
    /// - A payload that takes more bytes off the connection than a compressed
    ///   form of that size fails the pull too. The limit is the declared size,
    ///   plus one byte for each 1024, plus 64 KiB. This limit bounds the time
    ///   and the bandwidth of a stream of empty DEFLATE blocks.
    ///
    /// # Static deltas
    ///
    /// A remote that publishes static deltas delivers a commit as one delta,
    /// with no request for each object. Before the pull requests the first
    /// object, it looks for a delta:
    ///
    /// 1. If the remote serves a summary that states `indexed-deltas` or
    ///    omits the key, the pull fetches the delta index of the target
    ///    commit, `delta-indexes/<to_b64[0:2]>/<to_b64[2:]>.index`.
    /// 2. If the remote serves no index, the pull reads the
    ///    `ostree.static-deltas` map of the summary.
    ///
    /// Both map a delta name to the SHA-256 of the `superblock` of that delta.
    /// The pull fetches no delta that the map does not name. So a client that
    /// holds a commit with no published delta from it fetches loose.
    ///
    /// If the remote serves no summary, nothing advertises a delta. The pull
    /// then requests the `superblock` of one delta by name, with no digest to
    /// verify it against. That delta is `<from>-<to>` if this repository holds
    /// the commit of the ref complete, and the from-scratch `<to>` otherwise.
    ///
    /// A pull whose names are all commit operands reads no summary. If the
    /// `config` of the remote states `[core] indexed-deltas=true`, the pull
    /// fetches the delta index of the target commit, and takes no delta that
    /// the index does not name. A remote with no `config`, a `config` with no
    /// such key, and a value that is not a boolean give one superblock
    /// request by name, as for a remote with no summary. The source commit of
    /// the delta of a `NAME@CHECKSUM` operand is the commit of the ref that
    /// the operand writes. The pull looks for no delta to the commit of a
    /// `CHECKSUM` operand, also with a list of
    /// [`static_deltas`](PullOptions::static_deltas), and fetches its objects
    /// loose. The attachments of that commit keep the search of each
    /// attachment.
    ///
    /// The pull takes at most one delta for each target commit. It takes the
    /// first of these that the map names:
    ///
    /// - `<from>-<to>`, where `from` is the commit that the pulled ref names in
    ///   this repository
    /// - `<c>-<to>`, for each other commit `c` that this repository holds
    ///   complete
    /// - the from-scratch `<to>`, if the ref names no commit
    ///
    /// A from-to delta patches against the objects of the source commit, so
    /// this repository must hold the source commit complete. A ref whose
    /// commit is absent or partial counts as a ref that names no commit.
    ///
    /// If the ref names a commit that this repository holds complete, the pull
    /// takes no from-scratch delta, which delivers each object of the target
    /// again. It fetches the missing objects loose. With a map, a ref that
    /// names the target commit, held here partial, also leaves the
    /// from-scratch delta alone. The `ostree` command does the same.
    ///
    /// The pull looks for no delta to a target commit that this repository
    /// holds complete. It looks for a delta to a target commit held partial
    /// as for a commit that it does not hold. A
    /// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull takes no delta.
    /// [`subpaths`](PullOptions::subpaths) states the delta rules of a
    /// subpath pull.
    ///
    /// If the remote advertised a digest for a superblock, the pull hashes the
    /// superblock and compares the result with the digest before the parse.
    /// So a delta swapped under a signed summary fails the pull. The parsed
    /// superblock must name the pulled commit and the source commit that the
    /// delta name states.
    ///
    /// Before any part request, the pull verifies the signatures of the delta
    /// over the raw superblock bytes, under the policy of [`PullVerify`]. The
    /// delta of an attachment is the exception, as the list below for the delta
    /// of an attachment states. Also before any part request, it verifies each
    /// inline part against the size and the checksum of its meta-entry. A
    /// superblock that the remote does not hold (a stale advertisement) is a
    /// 404, and the pull fetches the objects loose.
    ///
    /// The superblock holds the target commit, so the pull requests no
    /// `.commit`. A part that the superblock carries inline needs no request.
    /// The pull queues the objects that the delta hands over loose at once.
    /// Two part fetches run at a time, whatever the step count.
    ///
    /// The pull takes each part off the connection under the size that its
    /// meta-entry declares. It verifies the part against the checksum of that
    /// entry before decompression. So the remote puts at most the size that
    /// the superblock states onto the staging file system for one part. The
    /// pull writes each object of a part with its expected checksum asserted.
    ///
    /// The pull applies the parts of one delta in the order that they arrive.
    /// The format allows this order: a part patches against the objects of the
    /// source commit, which are present before the delta applies. A part never
    /// patches against the output of another part of the same delta.
    ///
    /// After the last part, the pull walks the tree of the commit and fetches
    /// loose each object that no part delivered. The `ostree` command takes
    /// the delta and its loose objects as the whole commit. If the delta was
    /// complete, the walk reads what the delta staged and requests nothing.
    ///
    /// Each part in flight costs one xz decoder and two blobs: the verified
    /// part body and the payload that it decompresses to. The xz decoder has a
    /// memory limit of 128 MiB, and the pull refuses a part whose xz stream
    /// states a dictionary that needs more. At most two parts are in flight
    /// at a time, so the xz decoders of a pull use at most 256 MiB. Each blob
    /// is on the heap while it is small. After a blob passes its heap
    /// threshold, it is a mapped temp file.
    ///
    /// [`static_deltas`](PullOptions::static_deltas) replaces this search with
    /// a list. The pull then reads no delta index and no `ostree.static-deltas`
    /// map, and it needs no summary for the deltas. For each target commit, it
    /// plans the chain with the fewest steps. A chain starts at a commit that
    /// this repository holds complete, or with a delta from scratch if the
    /// rules above for a map allow a from-scratch delta to the target. Of two
    /// chains with the same number of steps, the chain from a complete commit
    /// wins.
    ///
    /// Before the transaction opens, the pull fetches the superblock of each
    /// step and compares its SHA-256 with the digest in the list. It verifies
    /// the signatures and the inline parts of each superblock, as stated
    /// above, before it checks the commit of the step. For each commit of a
    /// chain, the target included, it also fetches the `.commitmeta` and
    /// checks the signatures of the commit. For each requested ref that names
    /// a commit of a chain, it makes the ref-binding check and the timestamp
    /// check, in the order of the refs. So a target that the policy, its ref
    /// binding, or the timestamp check refuses costs the superblocks that
    /// discovery fetched, and the pull requests no part.
    /// The pull does not request these files again, and does not check these
    /// commits again. A commit that has no record in the last plan gets its
    /// checks when the pull fetches it, and the pull requests its
    /// `.commitmeta` again. This is a target whose chain the pull drops, or a
    /// dropped intermediate commit that a depth walk reaches as a parent.
    ///
    /// Over a stream session, if no localcache repository holds the
    /// `.commitmeta` of the commit of a step, the pull sends the request of
    /// the superblock and the request of the `.commitmeta` as one pair. The
    /// reply of the `.commitmeta` arrives while the pull parses and verifies
    /// the superblock. So discovery then holds one superblock and one
    /// `.commitmeta` on the heap, up to 128 MiB each, and the parse of the
    /// superblock. A superblock that the remote does not hold costs its paired
    /// `.commitmeta` request. If a later plan reaches the same commit through
    /// another delta, the pull 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 superblock that the
    /// remote does not hold, if the remote holds the `.commitmeta` of its
    /// commit.
    ///
    /// The pull keeps the verified superblocks and `.commitmeta` files of
    /// discovery in one temp file in `tmp/` of this repository until it ends.
    /// The file holds at most 1 GiB, the bytes of the steps that discovery
    /// drops included. A list whose steps pass this limit fails the pull with
    /// [`Error::Pull`], and the pull does not fetch loose.
    ///
    /// The pull applies a chain one level at a time, in its one transaction. A
    /// part of a later step can patch against an object that an earlier step
    /// wrote, also an object that the earlier step hands over loose. So the
    /// parts, the loose objects, and the tree walk of one level end before the
    /// next level starts. Each intermediate commit ends complete, with no
    /// `.commitpartial` marker. The pull writes a ref for an intermediate
    /// commit only if a requested ref names it.
    ///
    /// Discovery checks only the signatures of an intermediate commit that
    /// no requested ref names. It makes no ref-binding check and no timestamp
    /// check on it, so a chain can go through a commit whose ref binding
    /// names another ref. If a requested ref names an intermediate commit,
    /// discovery makes both checks for that ref.
    ///
    /// If the remote does not hold a superblock of a chain, the pull plans
    /// again without that delta. If no chain reaches a target, the pull
    /// fetches its objects loose, or fails under `require_static_deltas`. A
    /// listed delta from scratch to the target that the rules above refuse
    /// counts as found: the pull does not fail, and fetches that target loose.
    /// A [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull ignores the list.
    ///
    /// A static delta carries its target commit alone, so each attachment
    /// gets a delta of its own. The pull takes the attachments one level at a
    /// time, as `# Attachments` states. After the run of the level above, the
    /// pull looks for a delta of each attachment of the level that this
    /// repository does not hold complete. Then it fetches the attachments of
    /// the level in one more run, at depth 0. The levels stop when a level
    /// has no new attachment. The search for the delta of an attachment is
    /// the search for the delta of a target, with these changes:
    ///
    /// - The `from` comes from the paired entries of the attachment. Each
    ///   target whose chain names the attachment gives at most one paired
    ///   entry: the entry with the same name in field 2 of the commit that the
    ///   ref of the target names in this repository before the pull. The chain
    ///   of a target is the target and the parents that
    ///   [`depth`](PullOptions::depth) takes. If the chain names the
    ///   attachment under two names, the name nearest to the tip applies.
    /// - An attachment X that no chain names, and that an attachment D of the
    ///   level above names, takes its paired entries from the `from` of the
    ///   delta of D. Each such D with a `from` gives at most one paired entry:
    ///   the entry with the name of the first entry that names X in field 2 of
    ///   D, in field 2 of the `from` of D. The paired entries follow the order
    ///   of the attachments of the level above. A D with no `from` gives X no
    ///   paired entry.
    /// - The `from` is the first paired entry, in the order of the targets or
    ///   of the attachments of the level above, that this repository holds
    ///   complete. The step `<c>-<to>` finds a delta from each other commit
    ///   held complete, the other paired entries included.
    /// - The pull takes the from-scratch delta only if this repository holds
    ///   no paired entry complete.
    /// - A target with no local ref gives no paired entry. A ref gives none if
    ///   this repository does not hold its commit, or if field 2 of that
    ///   commit does not decode or has a defective entry. If field 2 holds two
    ///   entries with one name, the first entry applies. An intermediate
    ///   commit of a chain of static deltas that the depth does not take is
    ///   not in the chain of a target, so it gives no paired entry.
    /// - With [`static_deltas`](PullOptions::static_deltas), the pull takes
    ///   one entry of the list whose target is the attachment, in the same
    ///   order. It plans no chain for an attachment, and reads no delta index
    ///   and no summary map.
    /// - With no summary, the pull requests the delta from the `from` by
    ///   name, or the from-scratch delta if it has no `from`.
    /// - The pull checks no signature of the superblock. Field 2 names the
    ///   attachment by its checksum, and the parse of the superblock compares
    ///   the checksum of the commit that the superblock carries with that
    ///   checksum. The checks of the digest, of the `from` and the `to`, and
    ///   of the inline parts stay.
    ///
    /// An attachment with no delta comes as loose objects, or fails the pull
    /// under `require_static_deltas`. An attachment that a run of the targets
    /// or of a level reaches, for example as a parent, gets no delta of its
    /// own.
    ///
    /// After its checks, the pull keeps the superblock of the delta of each
    /// attachment of a level, and the commit that it carries, in one temp
    /// file in `tmp/` of this repository until the run of the level ends. Each
    /// level has a file of its own, and the pull removes it before the search
    /// of the next level. A search holds the superblock that it
    /// fetched and the parse of it until its checks end, so during the search
    /// the heap holds at most one superblock and its parse for each search in
    /// flight. The pull reads the commit from the file in the step of the
    /// commit. It parses the superblock again from the file just before the
    /// parts of the delta, and drops the parse after the last part. So the pull
    /// requests each superblock one time, also from a remote with no summary,
    /// and the application of the parts holds the parsed deltas of at most two
    /// attachments at a time. The file holds at most 1 GiB. If the superblocks
    /// and the commits of the attachments of one level pass this limit, the
    /// pull fails with [`Error::Pull`], and does not fetch loose.
    ///
    /// [`disable_static_deltas`](PullOptions::disable_static_deltas) and
    /// [`require_static_deltas`](PullOptions::require_static_deltas) control
    /// the search, also for the attachments.
    ///
    /// # Failure
    ///
    /// The steps borrow the repository, the transaction, and the fetcher. A
    /// failure drops each step in flight, which closes its connection and
    /// releases its fetcher permit. The transaction removes its staging
    /// directory, and the pull writes no ref.
    ///
    /// # Errors
    ///
    /// These errors stop the pull before its first request:
    ///
    /// - [`Error::InvalidInput`] if [`depth`](PullOptions::depth) is below
    ///   `-1`.
    /// - [`Error::InvalidInput`] if [`remote`](PullOptions::remote) holds a
    ///   name that [`valid_remote_name`](crate::config::valid_remote_name)
    ///   refuses, also under [`MIRROR`](PullFlags::MIRROR).
    /// - [`Error::Pull`] if a subpath does not start with `/`.
    /// - [`Error::InvalidInput`] if
    ///   [`static_deltas`](PullOptions::static_deltas) holds two digests for
    ///   one delta, or is set together with
    ///   [`disable_static_deltas`](PullOptions::disable_static_deltas) or with
    ///   [`subpaths`](PullOptions::subpaths).
    /// - [`Error::InvalidRefspec`] if a name in [`refs`](PullOptions::refs) is
    ///   not a ref `NAME` or `@ID:NAME` that [`Ref`] reads, with or without a
    ///   `@CHECKSUM` part, and is not a `CHECKSUM`: a remote ref
    ///   `REMOTE:NAME`, a `^` suffix, a part that fails its rule, or a part
    ///   after the last `@` that is not 64 lowercase hex characters.
    /// - [`Error::InvalidInput`] if [`refs`](PullOptions::refs) holds a
    ///   `CHECKSUM` operand and
    ///   [`timestamp_check`](PullOptions::timestamp_check) is
    ///   [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef).
    /// - [`Error::Pull`] if
    ///   [`require_static_deltas`](PullOptions::require_static_deltas) is set
    ///   and [`refs`](PullOptions::refs) holds a `CHECKSUM` operand whose
    ///   commit this repository does not hold complete. The pull does not
    ///   make this check with
    ///   [`disable_static_deltas`](PullOptions::disable_static_deltas) or
    ///   under [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY).
    /// - [`Error::Core`] if [`refs`](PullOptions::refs) holds a `CHECKSUM`
    ///   operand and the value of the key `collection-id` of the section of
    ///   the remote holds a malformed escape sequence.
    /// - [`Error::Core`] if `[ex-ostrya] keep-detached-related` of this
    ///   repository is not a boolean.
    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` of
    ///   this repository is not a boolean.
    /// - [`Error::InvalidFormat`] if [`refs`](PullOptions::refs) is empty,
    ///   [`MIRROR`](PullFlags::MIRROR) is not set, and an entry of the key
    ///   `pull-branches` of the remote is not a valid ref pattern. Under the
    ///   same conditions, [`Error::Core`] if the value of the key
    ///   `pull-branches` or `branches` holds a malformed escape sequence, and
    ///   [`Error::InvalidRefspec`] if a name of the key `branches` is not a
    ///   valid ref name. The pull checks `pull-branches` first.
    /// - The errors of [`resolve_pull`]. Among them, [`Error::Io`] names the
    ///   key and the path of a PEM file that cannot be read, and a PEM file
    ///   over 1 MiB is [`Error::InvalidInput`].
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if the ssh
    ///   command or the send command of an [`Endpoint::Ssh`] is empty or holds
    ///   only white space.
    /// - [`Error::Unsupported`] if the scheme of a mirror is neither `http`
    ///   nor `https`, or if the fetcher refuses the proxy URL or a proxy
    ///   environment variable.
    /// - [`Error::Fetch`] if a mirror is not a valid absolute URL, if a header
    ///   is invalid, or if the TLS material does not parse.
    /// - The errors of [`PullTrust::from_remote`]. Among them,
    ///   [`Error::InvalidInput`] if
    ///   [`valid_remote_name`](crate::config::valid_remote_name) refuses
    ///   `remote`.
    /// - The errors of [`trust_group`](PullOptions::trust_group), if it is
    ///   set.
    ///
    /// These errors stop the pull before it fetches an object:
    ///
    /// - [`Error::Signature`] if the policy of
    ///   [`PullVerify`] refuses the summary.
    /// - [`Error::Unsupported`] if the `config` of the remote states a mode
    ///   other than `archive`.
    /// - [`Error::InvalidFormat`] if the `config` of the remote is not valid
    ///   UTF-8 or has no valid `[core]` group.
    /// - [`Error::InvalidFormat`] if a ref file of the remote is not valid
    ///   UTF-8.
    /// - [`Error::InvalidFormat`] if the summary holds an
    ///   `ostree.summary.collection-map` that is malformed, and the pull reads
    ///   it for an `@ID:NAME` ref, for a `MIRROR` pull of every ref, or for
    ///   the key `pull-branches`.
    /// - [`Error::Core`] if the `config` of the remote does not parse as a key
    ///   file, or if a ref file of the remote holds no checksum.
    /// - [`Error::InvalidRefspec`] if a ref of the summary under `MIRROR`, or
    ///   a ref of the summary that the key `pull-branches` selects, is not a
    ///   valid ref name.
    ///   A `MIRROR` pull of every ref
    ///   fails with this error if the summary lists one name that the ref-name
    ///   rule refuses, or one collection id that the collection-id rule
    ///   refuses. The pull does not skip the name. A `MIRROR` pull of a plain
    ///   name in [`refs`](PullOptions::refs) fails with this error if the
    ///   `ostree.summary.collection-id` of the summary fails the
    ///   collection-id rule.
    /// - [`Error::Pull`] if two names of the pull write one ref.
    /// - [`Error::RefNotFound`] if neither the summary nor the ref file of the
    ///   remote names a requested ref or a name of the key `branches`.
    /// - [`Error::Pull`] if [`refs`](PullOptions::refs) is empty and the remote
    ///   serves no summary under `MIRROR` or with the key `pull-branches`, if
    ///   no ref of the summary matches `pull-branches` and the key `branches`
    ///   holds no ref, or if the remote has no key `pull-branches` and no ref
    ///   in the key `branches`.
    /// - These errors of the commit of
    ///   [`TimestampCheck::Rev`](crate::TimestampCheck::Rev), if
    ///   [`timestamp_check`](PullOptions::timestamp_check) is that check and
    ///   the pull has at least one target. The pull reads the commit after the
    ///   ref files of the remote and before it fetches a delta index or a
    ///   static delta superblock.
    ///   - [`Error::ObjectNotFound`] if this repository does not hold the
    ///     commit.
    ///   - [`Error::InvalidFormat`] if the commit object is larger than
    ///     [`MAX_METADATA_SIZE`] or is not a regular file, or if a symlink is
    ///     on its path.
    ///   - [`Error::Io`] if a read of the commit object fails.
    ///   - [`Error::Core`] if the tuple frame, the subject, or the body of the
    ///     commit is not in normal form, or if its parent, root dirtree, or
    ///     root dirmeta checksum has a wrong length.
    /// - [`Error::Pull`] if
    ///   [`require_static_deltas`](PullOptions::require_static_deltas) is set
    ///   and the pull finds no delta, or no chain to a target under a list. A
    ///   listed delta from scratch to the target that the from-scratch rules
    ///   of `# Static deltas` refuse counts as found, and the pull fetches
    ///   that target loose.
    /// - [`Error::Pull`] if a superblock names other commits than its delta
    ///   name.
    /// - [`Error::Pull`] if the superblocks and the `.commitmeta` files of the
    ///   chains of a list pass the limit of 1 GiB.
    /// - [`Error::Signature`] if the policy refuses a commit of a chain of a
    ///   list, or the superblock of a step.
    /// - [`Error::Pull`] if a requested ref that names a commit of a chain of
    ///   a list fails the ref-binding check or the timestamp check.
    ///
    /// These errors stop the pull while it fetches:
    ///
    /// - [`Error::Signature`] if the policy refuses a commit, or the static
    ///   delta of a target.
    /// - [`Error::Pull`] if
    ///   [`require_static_deltas`](PullOptions::require_static_deltas) is set
    ///   and the pull finds no delta for an attachment, at any level. The pull
    ///   looks for it after it fetched the objects of the level above, and
    ///   publishes nothing. The search comes before the fetch of the
    ///   attachment. So an attachment with no delta that no source holds gives
    ///   this error, and not [`Error::InvalidRelations`].
    /// - [`Error::InvalidRelations`] if an entry of field 2 of a commit has an
    ///   empty name or a checksum that is not 32 bytes. If the commit is an
    ///   attachment with a delta, the pull fetches and checks the superblock
    ///   first, and the error comes when the pull reads the commit from the
    ///   superblock. Also, at each level of the attachments, if neither this
    ///   repository, a localcache repository, nor the remote holds an
    ///   attachment. The error then names a commit that names the
    ///   attachment, as `# Attachments` states.
    /// - [`Error::Pull`] if the `ostree.ref-binding` of a commit does not list
    ///   the ref, or if the `ostree.collection-binding` of the tip of an
    ///   `@ID:NAME` ref does not state `ID`. Also if the commit of a commit
    ///   operand fails its collection-binding check, as `# Refs` states.
    /// - [`Error::Pull`] if a tip is older than the
    ///   [`timestamp_check`](PullOptions::timestamp_check) allows, or if a
    ///   content object fails a mode check.
    /// - [`Error::ObjectNotFound`] if the remote does not hold a requested
    ///   commit or an object of a tree, the tree of an attachment included.
    /// - [`Error::ChecksumMismatch`] if a fetched object does not hash to its
    ///   name, or a superblock does not hash to its advertised digest.
    /// - [`Error::Core`] if a fetched commit or the header of a content object
    ///   does not parse. Also if a `.commitmeta` does not parse. If the
    ///   signature policy verifies commits, the pull parses the `.commitmeta`
    ///   of each commit that it verifies: the copy that it reads from the
    ///   remote or a localcache repository, or the copy in this repository if
    ///   no source holds one. It verifies no attachment. If
    ///   `[ex-ostrya] keep-detached-related` of this repository is `false`, the
    ///   pull parses each `.commitmeta` that it stores.
    /// - [`Error::InvalidFormat`] if a content object breaks its framing, or
    ///   passes its declared size or its compressed limit.
    /// - [`Error::InvalidFormat`] if a content object inflates to fewer bytes
    ///   than declared, or has bytes after its end. A malformed static delta,
    ///   and a delta part whose xz stream needs more than 128 MiB of decoder
    ///   memory, have the same error.
    /// - [`Error::InsufficientFreeSpace`] if a stored object needs more space
    ///   than the free-space budget of the transaction holds.
    ///
    /// These errors can stop the pull at any request or write:
    ///
    /// - [`Error::Fetch`], [`Error::HttpStatus`], [`Error::FetchTooLarge`],
    ///   [`Error::ContentEncoded`], or [`Error::RedirectLimit`] if an HTTP
    ///   request fails after its retries.
    /// - [`Error::Remote`] if the session of a pull over ssh fails, or if a
    ///   read of `summary.sig`, `summary`, or `config` from a bucket
    ///   repository fails.
    /// - [`Error::LockTimeout`] if the wait for the repository lock or the
    ///   update lock passes `[core] lock-timeout-secs`.
    /// - [`Error::InvalidFormat`] if `state` is a symlink or is not a
    ///   directory. The pull fails at the write of the marker of the first
    ///   commit that it fetches, before it stages that commit.
    /// - [`Error::Io`] with `EISDIR` if a directory is at the name of a
    ///   marker that the pull removes after its transaction commits.
    /// - [`Error::Io`] if the load of a content object of a localcache
    ///   repository fails with an error of the operating system, for example
    ///   `EACCES`. The error keeps the kind of that error, and its text is
    ///   `<path of the localcache repository>/objects/<xx>/<rest>: <reason>`.
    /// - [`Error::Io`] for an I/O error of the file system.
    ///
    /// # Examples
    ///
    /// Pull one ref from the remote `origin` of the config:
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let opts = ostrya::PullOptions {
    ///     refs: vec!["exampleos/stable".to_owned()],
    ///     ..Default::default()
    /// };
    /// let stats = repo.pull("origin", opts).await?;
    /// println!("{} content objects fetched", stats.content_fetched);
    /// # Ok(()) }
    /// ```
    pub async fn pull(&self, remote: &str, opts: PullOptions) -> Result<PullStats> {
        self.pull_remote(remote, opts, false)
            .await
            .map(|report| report.stats)
    }

    /// Pulls refs and their objects from a remote as [`pull`](Repo::pull)
    /// does, and returns the statistics and the refs that the pull changed.
    ///
    /// [`PullReport::changed_refs`] holds each ref that is new and each ref
    /// that moved, remote refs too. A ref that the pull wrote again with the
    /// commit that it named before is not in the list. A pull that fails
    /// returns the error and no list.
    ///
    /// # Errors
    ///
    /// The errors of [`pull`](Repo::pull).
    ///
    /// # Examples
    ///
    /// Pull one ref from the remote `origin` of the config, and print each
    /// ref that changed:
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let opts = ostrya::PullOptions {
    ///     refs: vec!["exampleos/stable".to_owned()],
    ///     ..Default::default()
    /// };
    /// let report = repo.pull_with_report("origin", opts).await?;
    /// for change in &report.changed_refs {
    ///     println!("{} is at {}", change.name, change.new);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn pull_with_report(&self, remote: &str, opts: PullOptions) -> Result<PullReport> {
        self.pull_remote(remote, opts, true).await
    }

    /// Runs the pull of [`pull`](Repo::pull) from the remote `remote`.
    ///
    /// If `record` is `true`, the pull reads the old commit of each ref that
    /// it writes, and the report holds each ref that the pull changed. Else
    /// the pull reads no old commit, and the list of the report is empty.
    async fn pull_remote(
        &self,
        remote: &str,
        mut opts: PullOptions,
        record: bool,
    ) -> Result<PullReport> {
        let started = Instant::now();
        // A subpath the walk cannot read is refused before anything else, so it
        // costs no request and opens no transaction.
        let subpaths = Subpaths::parse(&opts.subpaths)?;
        check_depth(opts.depth)?;
        check_remote_option(&opts)?;
        check_static_deltas(&opts)?;
        check_remote_operands(&opts)?;
        check_commit_operands(self, &opts).await?;
        // The key `collection-id` of the remote section gives the collection
        // of a commit that an operand names with no ref. The pull reads the
        // key for such an operand alone, here, so a malformed value stops
        // the pull before it resolves the endpoint and before it connects.
        let commit_collection = match self.config().remote(remote) {
            Some(section)
                if opts
                    .refs
                    .iter()
                    .any(|name| matches!(Operand::parse(name), Ok(Operand::Commit(_)))) =>
            {
                section.collection_id()?
            }
            _ => None,
        };
        // The pull reads the rule one time, here. A value that is not a
        // boolean stops the pull before its first request.
        let related = RelatedRule::of(self.config())?;
        // The writes of the transaction read these keys again. This read
        // fails a bad value before the first request.
        self.config().fsync()?;
        self.config().per_object_fsync()?;
        // A pull with no ref and no `MIRROR` takes the refs of `branches` and
        // the refs that `pull-branches` selects. A malformed value of either
        // key stops the pull here, before it resolves the endpoint and before
        // it connects. Each name of `branches` goes on the wire as a request
        // path, so it passes the ref-name rule here too.
        if opts.refs.is_empty()
            && !opts.flags.contains(PullFlags::MIRROR)
            && let Some(section) = self.config().remote(remote)
        {
            section.pull_branches()?;
            for name in section.branches()?.unwrap_or_default() {
                crate::refs::check_ref_path(&name)?;
            }
        }
        let edges = take_static_deltas(&mut opts).await?;
        // The endpoint is resolved first, so a remote the config does not
        // describe reports that before a policy is resolved for it.
        let overrides = std::mem::take(&mut opts.overrides);
        let endpoint = resolve_pull(Some(self), remote, overrides).await?;
        // The trust comes before the session, so a refused policy starts no
        // fetcher and no ssh client.
        let mut group = opts.trust_group.as_deref().map(FieldGroup::new);
        let trust = PullTrust::for_pull(self, remote, &opts.verify, group.as_mut()).await?;
        let (endpoint, stream) = session_options(endpoint, opts.max_outstanding_fetches);
        let connection = connect(endpoint, stream).await?;
        // The trust and the session now hold what these fields gave.
        opts.verify = PullVerify::default();
        opts.trust_group = None;
        opts.max_outstanding_fetches = None;
        opts.remote = opts.remote.or_else(|| Some(remote.to_owned()));
        self.run_session(
            connection,
            trust,
            related,
            opts,
            Wanted::Config {
                remote,
                commit_collection: commit_collection.as_deref(),
            },
            subpaths,
            edges,
            started,
            record,
        )
        .await
    }

    /// Pulls refs and their objects through a session that the caller opened.
    ///
    /// `session` reads the remote, and `trust` holds each key that the pull
    /// checks a signature against. The pull obeys the rules of
    /// [`pull`](Repo::pull) that do not come from the config of a remote: the
    /// transaction, the commit walk, [`depth`](PullOptions::depth), the
    /// attachments, the subpaths, the verification of signatures, the static
    /// deltas, and the statistics.
    ///
    /// The pull reads no remote section and no trust group of the config of
    /// this repository. It reads the `[core]` keys that each transaction
    /// reads, and `[ex-ostrya] keep-detached-related`.
    ///
    /// # Refs
    ///
    /// The pull takes the refs in [`refs`](PullOptions::refs) alone, and
    /// resolves each one as [`pull`](Repo::pull) does. The prefix of the
    /// written refs comes from [`remote`](PullOptions::remote):
    ///
    /// - `None` writes local refs, `refs/heads/<ref>`, as
    ///   [`pull_local`](Repo::pull_local) does.
    /// - `Some(name)` writes `refs/remotes/<name>/<ref>`.
    /// - [`MIRROR`](PullFlags::MIRROR) writes each plain ref as
    ///   [`pull`](Repo::pull) states, whatever `remote` holds: as the ref of
    ///   the collection that the summary of the remote states, or as a local
    ///   ref.
    /// - An `@ID:NAME` ref writes the collection ref, as
    ///   [`pull`](Repo::pull) states, whatever `remote` holds.
    /// - A commit operand has the rules of [`pull`](Repo::pull). A
    ///   `NAME@CHECKSUM` operand writes the ref that `NAME` writes, and a
    ///   `CHECKSUM` operand writes no ref. The pull reads no remote section,
    ///   so it makes no collection-binding check of a `CHECKSUM` operand.
    ///
    /// Two names that write one ref stop the pull, as [`pull`](Repo::pull)
    /// states.
    ///
    /// The pull does not protect the local refs of this repository. Under
    /// [`no_ref_writes`](PullOptions::no_ref_writes), the pull writes no ref,
    /// and the rules above select the ref that the pull reads for delta
    /// discovery and for
    /// [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef).
    ///
    /// A `MIRROR` pull copies no `summary` and no `summary.sig`, because the
    /// pull refuses an empty `refs`.
    ///
    /// # Session
    ///
    /// The pull keeps as many steps in flight as the session admits:
    /// [`PullSession::max_outstanding`]. It takes the session by value. A
    /// stream session ends before the transaction commits, as in
    /// [`pull`](Repo::pull).
    ///
    /// # Counters
    ///
    /// [`PullStats::elapsed`] starts at the call of this method.
    /// [`PullStats::bytes_transferred`] and [`progress`](PullOptions::progress)
    /// count as for [`pull`](Repo::pull): the count starts after the
    /// `summary`, the `config`, and the ref files of the remote.
    ///
    /// The caller can attach its own counters to the fetcher of an
    /// [`Http`](PullSession::Http) session with
    /// [`Fetcher::counted`](crate::fetch::Fetcher::counted). Those counters
    /// get the bytes of each body that the fetcher reads, the `summary`, the
    /// `config`, and the ref files included. So their count can be larger
    /// than `bytes_transferred`.
    ///
    /// # Errors
    ///
    /// These errors stop the pull before its first request, before the
    /// transaction opens, and before the pull counts into
    /// [`progress`](PullOptions::progress). The pull writes no object and no
    /// ref. It calls [`PullSession::finish`] before it returns the error, and
    /// ignores the result of that call.
    ///
    /// - [`Error::Core`] if `[ex-ostrya] keep-detached-related` of this
    ///   repository is not a boolean.
    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` of
    ///   this repository is not a boolean.
    /// - [`Error::Pull`] if a subpath does not start with `/`.
    /// - [`Error::InvalidInput`] if [`depth`](PullOptions::depth) is below
    ///   `-1`.
    /// - [`Error::InvalidInput`] if [`remote`](PullOptions::remote) holds a
    ///   name that [`valid_remote_name`](crate::config::valid_remote_name)
    ///   refuses, also under `MIRROR`.
    /// - [`Error::InvalidInput`] if
    ///   [`static_deltas`](PullOptions::static_deltas) holds two digests for
    ///   one delta, or is set together with
    ///   [`disable_static_deltas`](PullOptions::disable_static_deltas) or with
    ///   [`subpaths`](PullOptions::subpaths).
    /// - [`Error::InvalidInput`] if [`refs`](PullOptions::refs) is empty, also
    ///   under `MIRROR`.
    /// - [`Error::InvalidRefspec`] if a name in [`refs`](PullOptions::refs) is
    ///   not a ref `NAME` or `@ID:NAME` or a commit operand, as for
    ///   [`pull`](Repo::pull).
    /// - The errors of [`pull`](Repo::pull) for a `CHECKSUM` operand under
    ///   [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef) and
    ///   under [`require_static_deltas`](PullOptions::require_static_deltas).
    /// - [`Error::InvalidInput`] if [`verify`](PullOptions::verify) is not the
    ///   default, or if [`trust_group`](PullOptions::trust_group) is set.
    ///   `trust` holds the keys.
    /// - [`Error::InvalidInput`] if
    ///   [`max_outstanding_fetches`](PullOptions::max_outstanding_fetches) is
    ///   set. The limit of the session applies.
    /// - [`Error::InvalidInput`] if [`overrides`](PullOptions::overrides) is
    ///   not the default. The session selects the server.
    ///
    /// After these checks, the pull has the errors of [`pull`](Repo::pull)
    /// that stop it before it fetches an object, while it fetches, and at any
    /// request or write. A stream session that fails is [`Error::Remote`].
    ///
    /// # Examples
    ///
    /// Pull one ref over HTTP with no check of signatures, into the local ref
    /// `exampleos/stable`:
    ///
    /// ```no_run
    /// use ostrya::fetch::{Fetcher, FetcherOptions};
    /// use ostrya::remote::PullSession;
    /// use ostrya::verify::PullTrust;
    ///
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
    /// let opts = ostrya::PullOptions {
    ///     refs: vec!["exampleos/stable".to_owned()],
    ///     ..Default::default()
    /// };
    /// let stats = repo
    ///     .pull_with_session(PullSession::Http(fetcher), PullTrust::unverified(), opts)
    ///     .await?;
    /// println!("{} content objects fetched", stats.content_fetched);
    /// # Ok(()) }
    /// ```
    pub async fn pull_with_session(
        &self,
        session: PullSession,
        trust: PullTrust,
        mut opts: PullOptions,
    ) -> Result<PullStats> {
        let started = Instant::now();
        let checked = match RelatedRule::of(self.config())
            .and_then(|related| self.config().fsync().map(|_| related))
            .and_then(|related| self.config().per_object_fsync().map(|_| related))
        {
            Ok(related) => match check_session_pull(&mut opts).await {
                Ok(checked) => check_commit_operands(self, &opts)
                    .await
                    .map(|()| (related, checked)),
                Err(e) => Err(e),
            },
            Err(e) => Err(e),
        };
        let (related, (subpaths, edges)) = match checked {
            Ok(checked) => checked,
            Err(e) => {
                // The refusal comes before the first request. The result of
                // the session end does not change it.
                let _ = session.finish().await;
                return Err(e);
            }
        };
        self.run_session(
            session.into(),
            trust,
            related,
            opts,
            Wanted::Named,
            subpaths,
            edges,
            started,
            false,
        )
        .await
        .map(|report| report.stats)
    }

    /// Runs a pull through the session of `connection` to its end, under
    /// `trust`.
    ///
    /// The caller made each check of `opts` that applies to its entry.
    /// [`remote`](PullOptions::remote) gives the prefix of the written refs,
    /// and the session gives the number of steps in flight. `edges` is the
    /// index of the list of static deltas that the caller took out of `opts`.
    /// `started` is the start of [`PullStats::elapsed`]. If `record` is
    /// `true`, the report holds each ref that the pull changed, else no ref.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn run_session(
        &self,
        connection: Connection,
        trust: PullTrust,
        related: RelatedRule,
        opts: PullOptions,
        wanted: Wanted<'_>,
        subpaths: Option<Subpaths>,
        edges: Option<Edges>,
        started: Instant,
        record: bool,
    ) -> Result<PullReport> {
        let counters = PullCounters::new(opts.progress.as_ref());
        let source = RemoteSource::new(connection, counters.transferred_sinks());
        let verification = Verification::from_trust(trust);
        // The state of `pull_from` is on the heap, which keeps the future of
        // each entry small.
        Box::pin(self.pull_from(
            wanted,
            source,
            &opts,
            &verification,
            related,
            subpaths,
            edges,
            &counters,
            started,
            record,
        ))
        .await
    }

    /// Runs a pull from `source` to its end: fetches what the refs reach into
    /// a transaction, ends the source, commits the transaction, and writes the
    /// refs. If `record` is `true`, the report holds each ref that the commit
    /// changed, else no ref.
    #[allow(clippy::too_many_arguments)]
    async fn pull_from(
        &self,
        wanted: Wanted<'_>,
        source: RemoteSource,
        opts: &PullOptions,
        verification: &Verification,
        related: RelatedRule,
        subpaths: Option<Subpaths>,
        edges: Option<Edges>,
        counters: &PullCounters,
        started: Instant,
        record: bool,
    ) -> Result<PullReport> {
        let mirror = opts.flags.contains(PullFlags::MIRROR);
        // A mirror pull writes a plain name as a local ref. Its targets name
        // the ref of a collection as `@ID:NAME`.
        let place = match wanted {
            Wanted::Pinned(pinned) => pinned.place,
            _ => RefPlace::Operands {
                remote: opts.remote.as_deref().filter(|_| !mirror),
                own: self.config().collection_id(),
            },
        };

        // The markers that the pull writes, and the `fsync` rule of the
        // transaction for them. They stay outside the span that writes them,
        // so a failure in that span clears the markers it left.
        let mut marked = Vec::new();
        let mut marker_fsync = false;
        let fetched = self
            .fetch_from(
                &source,
                wanted,
                opts,
                place,
                verification,
                related,
                subpaths,
                edges,
                counters,
                &mut marked,
                &mut marker_fsync,
            )
            .await;
        // The source ends before the transaction commits. The stream source
        // closes the input of the server and, over ssh, waits for the ssh
        // client. As a result, a failure of the session fails the pull before
        // anything publishes.
        let fetched = source.finish(fetched).await;
        let published = match fetched {
            Ok(fetched) => {
                let FetchedPull {
                    txn,
                    targets,
                    summary,
                    signature,
                } = fetched;
                if !opts.no_ref_writes {
                    for (name, tip) in &targets {
                        place.queue(&txn, name, tip);
                    }
                }
                txn.commit_reporting(record)
                    .await
                    .map(|(stats, changed)| (stats, changed, summary, signature))
            }
            Err(e) => Err(e),
        };
        let (stats, changed_refs, summary_bytes, signature) = match published {
            Ok(published) => published,
            Err(e) => {
                self.clear_markers_for_absent_commits(&marked, marker_fsync)
                    .await;
                return Err(e);
            }
        };

        // The content that a marker guarded is published. A commit-only pull
        // keeps its markers, because it fetched no tree. A pull with subpaths
        // keeps them too, because it fetched part of each tree.
        if completes_marked(opts) {
            self.clear_markers(std::mem::take(&mut marked), marker_fsync)
                .await?;
        }

        // A mirror pull of every ref holds all that the remote publishes, so
        // the summary of the remote also describes this repository. The pull
        // copies it byte for byte. A mirror pull of named refs holds part of
        // it and writes no summary. A pull that writes no ref writes no
        // summary, because the summary lists refs that the pull did not write.
        if mirror
            && opts.refs.is_empty()
            && !opts.no_ref_writes
            && let Some(bytes) = summary_bytes
        {
            // The early read before the first request checked the value.
            let fsync = self.config().fsync()? && !opts.disable_fsync;
            // The pull writes both files under one hold of the update lock. It
            // takes the lock after the transaction commit released its own
            // hold, so no other writer of the summary lands between the files.
            // The hold can time out after the transaction commit wrote the
            // refs and the `.commitmeta` files. The pull then fails with those
            // files in place and the summary as it was.
            self.write_locked(move |repo| {
                let root = repo.root_dir();
                let temp = root.stage_root_file(&RootFile::Summary, &bytes, fsync)?;
                temp.publish(root, RootFile::Summary.name(), Publish::Replace, false)?;
                // The signature covers those bytes, so the pull copies it with
                // them. A client that pulls from this repository with
                // `gpg-verify-summary=true` reads the pair. If the remote holds
                // no `summary.sig`, the file of this repository stays as it
                // is. The `ostree` command does the same.
                if let Some(sig) = signature {
                    let temp = root.stage_root_file(&RootFile::SummarySig, &sig, fsync)?;
                    temp.publish(root, RootFile::SummarySig.name(), Publish::Replace, false)?;
                }
                // One sync of the root directory makes both renames durable.
                if fsync {
                    root.sync()?;
                }
                Ok(())
            })
            .await?;
        }

        Ok(PullReport {
            stats: PullStats {
                metadata_imported: stats.metadata_written,
                content_imported: stats.content_written,
                content_bytes_written: stats.content_bytes_written,
                content_bytes_unpacked: stats.content_bytes_unpacked,
                metadata_fetched: counters.metadata(),
                content_fetched: counters.content(),
                delta_parts: counters.parts(),
                bytes_transferred: counters.bytes(),
                elapsed: started.elapsed(),
            },
            changed_refs,
        })
    }

    /// Fetches what a pull from `source` reaches into a new transaction: the
    /// summary and its checks, the refs, the deltas, and then the plan, to
    /// its end. With a list of static deltas, the plan runs one time for each
    /// level of intermediate commits, and then one time for the targets. A
    /// pull that follows attachments then runs the plan one time for each
    /// level of attachments that no run reached: it looks for the deltas of
    /// the level, and fetches them, until a level has no new attachment. The
    /// commits whose `.commitpartial` marker the pull wrote go into
    /// `marked`. The `fsync` rule of the transaction for the markers goes
    /// into `marker_fsync` when the transaction starts.
    #[allow(clippy::too_many_arguments)]
    async fn fetch_from(
        &self,
        source: &RemoteSource,
        wanted: Wanted<'_>,
        opts: &PullOptions,
        place: RefPlace<'_>,
        verification: &Verification,
        related: RelatedRule,
        subpaths: Option<Subpaths>,
        edges: Option<Edges>,
        counters: &PullCounters,
        marked: &mut Vec<Checksum>,
        marker_fsync: &mut bool,
    ) -> Result<FetchedPull> {
        let mut root;
        // The probe of a collection pull read this summary and checked it
        // under the trust of this pull, so the pull does not fetch it again.
        // The pull takes the bytes, so they drop after the parse.
        let probed = match wanted {
            Wanted::Pinned(pinned) => pinned
                .summary
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .take(),
            _ => None,
        };
        // A commit operand names its commit, so the pull takes no ref of it
        // from the summary. If each operand names its commit, the pull reads
        // no summary and no `summary.sig`, and makes no check of them.
        let by_checksum_only = match wanted {
            Wanted::Pinned(pinned) => pinned.commits_alone,
            _ => commit_operands_alone(&opts.refs),
        };
        let summary = if let Some(bytes) = probed {
            // The parse runs on the blocking pool, as below.
            root = RootFiles::default();
            Some(ostrya_rt::unblock(move || Summary::parse(&bytes)).await?)
        } else if by_checksum_only {
            root = RootFiles::default();
            None
        } else {
            root = source.root_files().await?;
            // A mirror pull of every ref that writes refs copies the `summary`
            // and the `summary.sig` of the remote. Each other pull drops the
            // bytes after their checks.
            let copies_summary = opts.flags.contains(PullFlags::MIRROR)
                && opts.refs.is_empty()
                && !opts.no_ref_writes;
            // The pull checks the summary before it reads it. The pull acts on
            // the refs that the summary resolves and the deltas that it
            // advertises. As a result, a summary that the policy refuses stops
            // the pull before its first object request.
            let summary = root.summary.take().map(Arc::new);
            root.signature = verification
                .check_summary(summary.as_ref(), root.signature.take())
                .await?
                .filter(|_| copies_summary);
            // A summary can be as large as its read cap, so the parse runs on
            // the blocking pool. The bytes come back only for the write of a
            // mirror pull, and else drop there. The check is done, so the job
            // holds the one `Arc` of the bytes, and the unwrap makes no copy.
            match summary {
                Some(bytes) => {
                    let (parsed, bytes) = ostrya_rt::unblock(move || {
                        let parsed = Summary::parse(&bytes);
                        (parsed, copies_summary.then(|| Arc::unwrap_or_clone(bytes)))
                    })
                    .await;
                    root.summary = bytes;
                    Some(parsed?)
                }
                None => None,
            }
        };
        let remote_config = check_remote_mode(root.config(source).await?)?;
        let (targets, mut by_checksum) = self
            .remote_targets(
                wanted,
                opts,
                place,
                summary.as_ref(),
                remote_config.collection_id.as_deref(),
                source,
            )
            .await?;
        by_checksum.all = by_checksum_only;
        // Discovery reads two values of the summary alone. The pull keeps
        // them for the deltas of the attachments, and drops the rest of the
        // summary here. A pull that read no summary, because each operand
        // names its commit, requests the delta index of a commit if the
        // `config` of the remote states `indexed-deltas=true`. Else it
        // requests a superblock by name.
        let advert = match summary {
            Some(summary) => Some(DeltaAdvert::from_summary(summary)),
            None if by_checksum_only && remote_config.indexed_deltas => {
                Some(DeltaAdvert::index_alone())
            }
            None => None,
        };
        // The transferred count starts after the summary, the config, and the
        // ref files that a pull reads from a remote with no summary. The
        // `ostree` command reports the same count.
        counters.restart_transferred();

        // The timestamp check reads a commit that it names one time, before
        // discovery. A commit that this repository does not hold stops the
        // pull before its first superblock request. A pull with no target
        // checks no timestamp, so it reads no commit.
        let timestamp = if targets.is_empty() {
            TimestampBase::Off
        } else {
            TimestampBase::resolve(self, &opts.timestamp_check).await?
        };
        // The checks of each requested ref. A collection pull adds the check
        // of the collection binding and of the timestamp that the remote
        // listed. Each other pull checks the collection binding of each
        // `@ID:NAME` name, unless it writes no ref. Each pull makes the
        // checks of its commit operands.
        let tip_checks = match wanted {
            Wanted::Pinned(pinned) => TipChecks {
                collection: Some(pinned.collection),
                allow_unbound: pinned.allow_unbound,
                listed: Some(&pinned.listed),
                by_checksum: Some(&by_checksum),
                ..TipChecks::new(opts.flags, timestamp, place)
            },
            _ => TipChecks {
                operand_collections: !opts.no_ref_writes,
                by_checksum: Some(&by_checksum),
                ..TipChecks::new(opts.flags, timestamp, place)
            },
        };

        // The deltas that can deliver these commits, found before the first
        // object request. A commit that a delta carries has no `.commit`
        // request of its own.
        let delta_source = DeltaSource::Remote(source);
        let mut deltas = delta::discover(
            self,
            &delta_source,
            advert.as_ref(),
            &targets,
            opts,
            tip_checks,
            edges,
            verification,
            related,
            counters,
        )
        .await?;
        deltas.plan_parts(counters);
        // A commit-only pull and a pull with subpaths follow no attachment.
        // The search for the deltas of the attachments reads the list of
        // static deltas, else the summary values, after the run of the
        // targets. The pull keeps neither if it does not read it. The search
        // of each level of attachments reads it, so the parse stays in memory
        // until the run of the last level ends.
        let follows = !opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty();
        let looks = follows && !opts.disable_static_deltas;
        let edges = deltas.take_edges().filter(|_| looks);
        let advert = advert.filter(|_| looks && edges.is_none());

        let mut txn = self.transaction().await?;
        apply_durability(&mut txn, opts);
        *marker_fsync = txn.fsync_flags()?.0;
        // A part of a later step of a chain can patch against an object that
        // an earlier step wrote. So the run of each level of intermediate
        // commits ends before the next run starts. The jobs of a level live
        // for its run alone.
        let none = HashMap::new();
        let mut done = HashSet::new();
        let mut carry = Carry::default();
        // A pull that looks for no delta of an attachment pairs no attachment
        // with a target, so it keeps no entry of field 2.
        carry.attachments.inner = attachment::Attachments::new(!looks);
        for level in deltas.levels() {
            let jobs = deltas.parse_level(self, &delta_source, level).await?;
            let phase = Phase {
                roots: level,
                tips: &none,
                depth: 0,
                subpaths: None,
                deltas: RunDeltas::Ready(&jobs),
                done: &done,
                last: false,
                attachment_run: false,
            };
            self.drive(
                &txn,
                source,
                opts,
                tip_checks,
                phase,
                &deltas,
                verification,
                related,
                counters,
                &mut carry,
                marked,
                *marker_fsync,
            )
            .await?;
            drop(jobs);
            done.extend(level.iter().copied());
        }
        let jobs = deltas.target_jobs(self, &delta_source).await?;
        // The refs of each requested tip. The binding check and the timestamp
        // check apply to each ref. The plan fetches a commit once, whatever the
        // number of refs that name it. So the step that fetches a commit runs
        // the checks of every ref in its entry here.
        let mut tips: HashMap<Checksum, Vec<String>> = HashMap::new();
        for (name, tip) in &targets {
            tips.entry(*tip).or_default().push(name.clone());
        }
        let roots: Vec<Checksum> = targets.iter().map(|(_, tip)| *tip).collect();
        let phase = Phase {
            roots: &roots,
            tips: &tips,
            depth: opts.depth,
            subpaths,
            deltas: RunDeltas::Ready(&jobs),
            done: &done,
            last: !follows,
            attachment_run: false,
        };
        self.drive(
            &txn,
            source,
            opts,
            tip_checks,
            phase,
            &deltas,
            verification,
            related,
            counters,
            &mut carry,
            marked,
            *marker_fsync,
        )
        .await?;
        drop(jobs);
        // The runs of the attachments read no record of a chain: each commit
        // with a record is a commit that a run reached.
        drop(deltas);
        if follows {
            // The attachments that no run reached, one level at a time. The
            // first level holds the attachments of the commits of the earlier
            // runs. Each later level holds the attachments that the run of the
            // level above recorded. The search for the deltas of a level runs
            // after the run of the level above, and the run of the level
            // fetches its attachments at depth 0. An attachment with no delta
            // is fetched object by object. Each commit of these runs is an
            // attachment alone, so the runs check no signature. The search for
            // the deltas checks no signature of a superblock. The levels stop
            // when a level records no new attachment. The record of the
            // attachments adds each attachment one time, and field 2 cannot
            // make a cycle, so the number of levels is finite.
            //
            // `start` is the position in the record of the first attachment of
            // the next level. `above` holds each attachment of the level above,
            // in the order of the roots of that level, with the `from` of its
            // delta, if it has one. It is `None` for the first level.
            //
            // The scanning state of the pull stays on through the runs of all
            // levels, and ends one time after the last level.
            let mut start = 0;
            let mut above: Option<Vec<(Checksum, Option<Checksum>)>> = None;
            loop {
                let order = carry.attachments.inner.order();
                let mut pending: Vec<Checksum> = order[start..]
                    .iter()
                    .filter(|attachment| !carry.parents.contains_key(*attachment))
                    .copied()
                    .collect();
                start = order.len();
                if pending.is_empty() {
                    break;
                }
                pending.sort_unstable();
                let (roots, found) = if looks {
                    let level = match &above {
                        None => attachment::Level::First,
                        Some(above) => attachment::Level::Later(above),
                    };
                    let named = attachment::pair_targets(
                        &targets,
                        opts.depth,
                        &carry.parents,
                        carry.attachments.inner.naming(),
                        &level,
                        pending,
                    );
                    let roots: Vec<Checksum> = named.iter().map(|named| named.checksum).collect();
                    let (lookups, known) =
                        attachment::lookups(self, &targets, place, named, HashMap::new()).await?;
                    let froms: HashMap<Checksum, Checksum> = lookups
                        .iter()
                        .filter_map(|lookup| lookup.from.map(|from| (lookup.checksum, from)))
                        .collect();
                    above = Some(
                        roots
                            .iter()
                            .map(|root| (*root, froms.get(root).copied()))
                            .collect(),
                    );
                    // Each level gets a new record file.
                    let found = delta::discover_attachments(
                        self,
                        &delta_source,
                        advert.as_ref(),
                        edges.as_ref(),
                        lookups,
                        &known,
                        opts,
                        counters,
                    )
                    .await?;
                    (roots, found)
                } else {
                    (pending, AttachmentDeltas::default())
                };
                let phase = Phase {
                    roots: &roots,
                    tips: &none,
                    depth: 0,
                    subpaths: None,
                    deltas: RunDeltas::Lazy(&found),
                    done: &done,
                    last: false,
                    attachment_run: true,
                };
                self.drive(
                    &txn,
                    source,
                    opts,
                    tip_checks,
                    phase,
                    &DeltaPlan::default(),
                    verification,
                    related,
                    counters,
                    &mut carry,
                    marked,
                    *marker_fsync,
                )
                .await?;
                // The record file of the level goes away here, before the
                // search of the next level. The next level reads field 2 of
                // each attachment of this level from the step that staged it,
                // and reads no record of this file.
                drop(found);
            }
            // No run follows. Each run ends with an empty queue, so the total
            // is the units of work that the runs started.
            counters.report(u32::try_from(carry.started).unwrap_or(u32::MAX), false);
        }
        // A commit operand with no ref writes no ref.
        let mut targets = targets;
        targets.retain(|(name, commit)| !by_checksum.is_bare(name, commit));
        Ok(FetchedPull {
            txn,
            targets,
            summary: root.summary,
            signature: root.signature,
        })
    }

    /// Fetches the `summary` and `summary.sig` files of a remote, as
    /// [`remote_fetch_summary_with`](Repo::remote_fetch_summary_with) does
    /// with the default overrides.
    ///
    /// The default overrides do not set `allow_cleartext_credentials`, so the
    /// call refuses an `http://` S3 endpoint.
    ///
    /// # Errors
    ///
    /// The errors of
    /// [`remote_fetch_summary_with`](Repo::remote_fetch_summary_with).
    pub async fn remote_fetch_summary(
        &self,
        remote: &str,
    ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
        self.remote_fetch_summary_with(remote, EndpointOverrides::default())
            .await
    }

    /// Fetches the `summary` and `summary.sig` files of a remote, with the
    /// overrides `overrides` of the caller.
    ///
    /// Returns the bytes of `summary` and of `summary.sig`, in this order. A
    /// file that the remote does not serve is `None`. Each file has a cap of
    /// 64 MiB.
    ///
    /// The call reaches the remote as [`pull`](Repo::pull) does. It resolves
    /// the endpoint of `remote` with [`resolve_pull`] and `overrides`. The
    /// address is [`EndpointOverrides::url`], else `pull-url`, else `url`.
    /// Over HTTP, the call uses the TLS material and the proxy of the remote.
    /// Over ssh, the remote keys `ssh-command` and `send-command` give the
    /// commands. The `OSTRYA_SSH_COMMAND` environment variable has precedence
    /// over `ssh-command`. For an `s3://` address, the S3 fields of
    /// `overrides` win over the S3 keys of the remote, and
    /// `allow_cleartext_credentials` permits an `http://` S3 endpoint.
    ///
    /// Over HTTP, the call requests `summary.sig` and then `summary`. Over
    /// ssh, the two requests are in flight together, and the session ends
    /// before the call returns. For an `s3://` address, the bucket client
    /// reads the two files with signed requests. It asks for `summary.sig`
    /// first. If the fetcher admits two requests at once, the two requests
    /// are in flight together.
    ///
    /// # Errors
    ///
    /// - The errors of [`resolve_pull`].
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if the ssh
    ///   command or the send command of an [`Endpoint::Ssh`] is empty or holds
    ///   only white space.
    /// - [`Error::Unsupported`] if the scheme of a mirror is neither `http`
    ///   nor `https`, or if the fetcher refuses the proxy URL or a proxy
    ///   environment variable.
    /// - [`Error::FetchTooLarge`] if an HTTP response declares a file larger
    ///   than 64 MiB.
    /// - [`Error::Fetch`], [`Error::HttpStatus`] other than 404,
    ///   [`Error::ContentEncoded`], or [`Error::RedirectLimit`] if an HTTP
    ///   request fails after its retries.
    /// - [`Error::Remote`] if the ssh session fails, or if a read from a
    ///   bucket repository fails.
    pub async fn remote_fetch_summary_with(
        &self,
        remote: &str,
        overrides: EndpointOverrides,
    ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
        let endpoint = resolve_pull(Some(self), remote, overrides).await?;
        let connection = connect(endpoint, StreamSessionOptions::default()).await?;
        let source = RemoteSource::new(connection, Vec::new());
        let read = source.summary_files().await;
        source.finish(read).await
    }

    /// Resolves what to pull: the requested refs, the summary refs of the
    /// remote under [`MIRROR`](PullFlags::MIRROR), or the refs of the
    /// `branches` key of the remote that `wanted` names and the summary refs
    /// that the `pull-branches` key of that remote selects.
    ///
    /// `remote_id` is the `[core] collection-id` of the `config` of the
    /// remote. The target of an `@ID:NAME` name keeps the name as given.
    /// Under `MIRROR`, the target of a plain name is `@ID:NAME` if the
    /// summary states the collection id `ID`. Names that are the same text
    /// count one time. Two other names that write one ref at `place` stop the
    /// pull before it reads a ref file, unless the pull writes no ref.
    ///
    /// A commit operand gives its commit with no read of the summary or of a
    /// ref file. The target of `REF@CHECKSUM` is `REF` as given, also under
    /// `MIRROR`. The target of `CHECKSUM` is the hex form of the commit. The
    /// second value of the result holds these targets. For
    /// [`Wanted::Config`], it also holds the key `collection-id` of the
    /// remote section of this repository that `wanted` gives, for the
    /// collection-binding check of a commit with no ref.
    async fn remote_targets(
        &self,
        wanted: Wanted<'_>,
        opts: &PullOptions,
        place: RefPlace<'_>,
        summary: Option<&Summary>,
        remote_id: Option<&str>,
        source: &RemoteSource,
    ) -> Result<(Vec<(String, Checksum)>, ChecksumTargets)> {
        let mut by_checksum = ChecksumTargets::default();
        if let Wanted::Pinned(pinned) = wanted {
            by_checksum.bare.clone_from(&pinned.bare);
            return Ok((pinned.targets.clone(), by_checksum));
        }
        let mirror = opts.flags.contains(PullFlags::MIRROR);
        // Under `MIRROR`, a plain name and each ref of field 0 of the summary
        // are refs of the collection that the summary states.
        let summary_collection_id = summary
            .and_then(|summary| summary.metadata_value(COLLECTION_ID_KEY))
            .and_then(Value::as_str);
        let summary_id = summary_collection_id.filter(|_| mirror);
        let (names, mut selected) = if !opts.refs.is_empty() {
            (opts.refs.clone(), Vec::new())
        } else if mirror {
            let Some(summary) = summary else {
                return Err(Error::Pull(
                    "fetching all refs was requested in mirror mode, but the remote \
                     repository does not have a summary"
                        .into(),
                ));
            };
            let targets = summary_targets(summary, summary_id, |_| true)?;
            check_one_place(
                place,
                targets
                    .iter()
                    .map(|(text, _)| (text.as_str(), text.as_str())),
            )?;
            return Ok((targets, by_checksum));
        } else {
            let Wanted::Config { remote, .. } = wanted else {
                return Err(no_refs());
            };
            let section = self.config().remote(remote);
            // The pull takes each ref of `branches` and each ref of the
            // summary that `pull-branches` selects. The key `pull-branches`
            // selects refs of the summary, so a remote with no summary fails
            // the pull before its first object request, also when `branches`
            // holds refs. `Repo::pull` parsed both keys, and checked each name
            // of `branches` with the ref-name rule, before it connected. So a
            // malformed value of either key does not fail these reads.
            let pull_branches = match &section {
                Some(section) => section.pull_branches()?,
                None => None,
            };
            let selected = match pull_branches {
                Some(selector) => {
                    let Some(summary) = summary else {
                        return Err(Error::Pull(format!(
                            "[remote \"{remote}\"] pull-branches selects refs of the summary, \
                             but the remote repository does not have a summary"
                        )));
                    };
                    // A ref of field 0 stays the target `NAME`, and the pull
                    // writes it under the prefix of `place`. The check of
                    // `place` below covers these targets.
                    Some(summary_targets(summary, None, |r| {
                        selector.matches(r, summary_collection_id)
                    })?)
                }
                None => None,
            };
            let branches = match section {
                Some(section) => section.branches()?.unwrap_or_default(),
                None => Vec::new(),
            };
            if branches.is_empty() {
                match &selected {
                    None => {
                        return Err(Error::Pull(format!(
                            "no configured branches for remote {remote}"
                        )));
                    }
                    Some(targets) if targets.is_empty() => {
                        return Err(Error::Pull(format!(
                            "no ref of the summary matches [remote \"{remote}\"] pull-branches"
                        )));
                    }
                    Some(_) => {}
                }
            }
            (branches, selected.unwrap_or_default())
        };

        // The entry checked each name of `refs`, so an `@ID:NAME` name holds a
        // valid id and a valid name, and each commit operand parses. A name
        // of the `branches` key is a plain name, and the ref-name rule below
        // refuses each other name.
        let operands = !opts.refs.is_empty();
        let mut seen = HashSet::new();
        let mut wanted_refs = Vec::with_capacity(names.len());
        // The commit of each `REF@CHECKSUM` operand whose `REF` is the hex
        // form of that commit.
        let mut own_name = HashSet::new();
        for name in names {
            if !seen.insert(name.clone()) {
                continue;
            }
            let parsed = if operands {
                Operand::parse(&name)?
            } else {
                Operand::Name(&name)
            };
            let (ref_text, commit) = match parsed {
                // The commit has no ref, so it has no place to check.
                Operand::Commit(commit) => {
                    by_checksum.bare.insert(commit);
                    wanted_refs.push((name, commit.to_hex(), Resolved::Bare(commit)));
                    continue;
                }
                Operand::NameAt { name: r, commit } => (r, Some(commit)),
                Operand::Name(r) => (r, None),
            };
            let operand = operand_collection(ref_text)
                .filter(|_| operands)
                .map(|(id, ref_name)| (id.to_owned(), ref_name.to_owned()));
            let target = match (&operand, commit) {
                (Some(_), _) => ref_text.to_owned(),
                (None, commit) => {
                    // The name goes on the wire as a request path, so the pull
                    // checks it against the rule of the ref store. A component
                    // that the rule refuses, such as a traversal, can ask the
                    // server for a resource that the ref does not name. The
                    // name of a commit operand is the name of the ref that
                    // the pull writes, and passes the same rule.
                    crate::refs::check_ref_path(ref_text)?;
                    match (summary_id, commit) {
                        (Some(id), None) => Ref::collection(id, ref_text).to_string(),
                        (_, Some(commit)) => {
                            if Checksum::from_hex_lower(ref_text) == Ok(commit) {
                                own_name.insert(commit);
                            }
                            by_checksum.named.insert(ref_text.to_owned());
                            ref_text.to_owned()
                        }
                        (None, None) => ref_text.to_owned(),
                    }
                }
            };
            let resolved = match commit {
                Some(commit) => Resolved::At(commit),
                None => Resolved::Lookup(operand),
            };
            wanted_refs.push((name, target, resolved));
        }
        // The operands `<C>` and `<C>@<C>` give one target: the name `<C>` at
        // the commit C. The operand that writes a ref wins, so the pull
        // takes the target one time, writes the ref, and makes the checks of
        // `REF@CHECKSUM`.
        if !own_name.is_empty() {
            by_checksum.bare.retain(|commit| !own_name.contains(commit));
            wanted_refs.retain(|(_, _, resolved)| {
                !matches!(resolved, Resolved::Bare(commit) if own_name.contains(commit))
            });
        }
        if let Wanted::Config {
            commit_collection, ..
        } = wanted
        {
            by_checksum.bare_collection = commit_collection.map(str::to_owned);
        }
        // A name of `branches` is its own target, and a ref of field 0 that
        // `pull-branches` selects is the target `NAME`. So a ref that both
        // keys give is one target, and the pull takes it one time.
        selected.retain(|(target, _)| !seen.contains(target));
        // The check names each operand as given. A pull of operands that
        // writes no ref has no place to check.
        if !(operands && opts.no_ref_writes) {
            check_one_place(
                place,
                wanted_refs
                    .iter()
                    .filter(|(_, _, resolved)| !matches!(resolved, Resolved::Bare(_)))
                    .map(|(name, target, _)| (name.as_str(), target.as_str()))
                    .chain(
                        selected
                            .iter()
                            .map(|(target, _)| (target.as_str(), target.as_str())),
                    ),
            )?;
        }

        let mut listed = HashMap::new();
        let mut out = Vec::with_capacity(wanted_refs.len() + selected.len());
        for (name, target, resolved) in wanted_refs {
            let checksum = match resolved {
                Resolved::Bare(commit) | Resolved::At(commit) => Some(commit),
                Resolved::Lookup(Some((id, ref_name))) => {
                    remote_collection_ref(
                        summary,
                        summary_collection_id,
                        &mut listed,
                        remote_id,
                        &id,
                        &ref_name,
                        source,
                    )
                    .await?
                }
                Resolved::Lookup(None) => match summary.and_then(|summary| summary.lookup(&name)) {
                    Some(checksum) => Some(checksum),
                    None => fetch_remote_ref(source, HEADS_DIR, &name).await?,
                },
            };
            let checksum = checksum.ok_or_else(|| Error::RefNotFound(name.clone()))?;
            out.push((target, checksum));
        }
        out.extend(selected);
        Ok((out, by_checksum))
    }

    /// Runs one run of the plan to its end, from the roots of `phase`. The
    /// commits whose `.commitpartial` marker this pull wrote, and must clear,
    /// go into `marked`.
    ///
    /// The run starts from the objects that the earlier runs of this pull
    /// queued, and gives them back in `carry` when it ends. So the pull
    /// fetches an object once over all runs. `carry` also keeps a running
    /// count of the units of work, for the progress total. `delta_plan` holds
    /// the checks that discovery made on the commits of the chains.
    ///
    /// `marked` is an argument, so the caller holds the written markers when a
    /// step fails.
    ///
    /// `marker_fsync` is the `fsync` rule of the transaction for the markers,
    /// which the caller reads one time.
    #[allow(clippy::too_many_arguments)]
    async fn drive(
        &self,
        txn: &Transaction,
        source: &RemoteSource,
        opts: &PullOptions,
        tip_checks: TipChecks<'_>,
        phase: Phase<'_>,
        delta_plan: &DeltaPlan,
        verification: &Verification,
        related: RelatedRule,
        progress: &PullCounters,
        carry: &mut Carry,
        marked: &mut Vec<Checksum>,
        marker_fsync: bool,
    ) -> Result<()> {
        // A commit-only pull and a pull with subpaths take part of each commit.
        // They follow no attachment.
        let whole = !opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty();
        let ctx = StepCtx {
            txn,
            source,
            writes: Arc::new(Gate::new(WRITE_THROTTLE)),
            sources: &opts.localcache_repos,
            flags: opts.flags,
            checks: ModeChecks::new(opts.flags, self.mode()),
            tip_checks,
            tips: phase.tips,
            deltas: phase.deltas,
            done: phase.done,
            delta_plan,
            verification,
            related,
            attachments: whole,
            attachment_run: phase.attachment_run,
            marking: Mutex::new(Vec::new()),
            marker_fsync,
            progress,
        };
        let mut plan = Plan::new(phase.subpaths);
        plan.queued = std::mem::take(&mut carry.queued);
        plan.attachments = std::mem::take(&mut carry.attachments);
        // Each run of the attachments is one level more. An attachment that
        // no source holds ends as an absent commit, and the plan gives the
        // error that names a commit that names it at the end of the run.
        if phase.attachment_run {
            plan.attachments.level += 1;
        }
        for root in phase.roots {
            plan.push_commit(CommitItem {
                checksum: *root,
                depth: phase.depth,
                optional: phase.attachment_run,
            });
        }

        // The pull keeps as many steps in flight as the session admits.
        let mut slots = Slots::new(source.max_outstanding());
        // The read buffers for content objects, from each source. A localcache
        // import verifies its payload through one, and a fetched payload
        // streams into the object store through one. A step takes a buffer at
        // its start and gives it back with its outcome. So a pull holds one
        // buffer for each slot, whatever the number of objects it stores. A
        // step that fails takes its buffer with it, and the failure ends the
        // pull.
        let mut buffers: Vec<Vec<u8>> = Vec::new();
        // The units of work given to a slot by this pull, for the progress
        // total.
        let mut started = carry.started;
        let earlier = marked.len();
        let ran = async {
            loop {
                while slots.has_room()
                    && let Some(item) = plan.next()
                {
                    // The load of a job is no unit of work of the progress.
                    let counted = !matches!(item, Item::Load(_));
                    let buffer = buffers.pop().unwrap_or_default();
                    slots.push(self.step(&ctx, item, buffer));
                    started += usize::from(counted);
                }
                plan.report(progress, started, !phase.last);
                let Some(outcome) = slots.next_ready().await else {
                    return plan.check_attachments();
                };
                let (step, buffer) = outcome?;
                buffers.push(buffer);
                if !matches!(step, Step::Loaded(_)) {
                    progress.object_done();
                }
                let part = match step {
                    Step::Part(commit) => Some(commit),
                    _ => None,
                };
                plan.apply(step, marked);
                // After the last part of a delta, the plan counts no part of
                // it, and the run releases the job of an attachment.
                if let Some(commit) = part
                    && !plan.delta_parts.contains_key(&commit)
                {
                    ctx.deltas.release(&commit);
                }
            }
        }
        .await;
        if let Err(e) = ran {
            // The steps that are still in flight end here. A blocking job of a
            // dropped step continues, so the run waits for each tracked job
            // that a dropped step left. The cleanup then sees each marker that
            // the run wrote. `marked` takes each such marker, whether or not
            // its step reached the plan.
            drop(slots);
            ctx.txn.settle().await;
            let marking = ctx
                .marking
                .into_inner()
                .unwrap_or_else(PoisonError::into_inner);
            marked.truncate(earlier);
            marked.extend(marking);
            return Err(e);
        }
        carry.queued = plan.queued;
        carry.attachments = plan.attachments;
        // The parents tell which commits a run reached, and give the chains
        // of the targets. A pull that follows no attachment reads neither.
        if whole {
            if carry.parents.is_empty() {
                carry.parents = plan.parents;
            } else {
                carry.parents.extend(plan.parents);
            }
        }
        carry.started = started;
        Ok(())
    }

    /// Runs one unit of work: fetches an object and stores it.
    ///
    /// `read_buf` is the read buffer of the slot. The step returns it with the
    /// outcome, for the next step in that slot. A content object reads through
    /// it: the payload of an object from the remote, and the verification of
    /// an object from a localcache repository.
    async fn step(
        &self,
        ctx: &StepCtx<'_>,
        item: Item,
        mut read_buf: Vec<u8>,
    ) -> Result<(Step, Vec<u8>)> {
        let step = match item {
            Item::Commit(commit) => self.fetch_commit(ctx, commit).await?,
            Item::Object(name) if name.ty == ObjectType::File => {
                self.fetch_content(ctx, name, &mut read_buf).await?
            }
            Item::Object(name) => self.fetch_metadata(ctx, name).await?,
            Item::Load(commit) => {
                if let RunDeltas::Lazy(found) = ctx.deltas {
                    found.load_job(self, &commit).await?;
                }
                Step::Loaded(commit)
            }
            Item::Part(part) => {
                // A load step loaded the job of an attachment before the plan
                // queued its parts. The step holds the job until it ends.
                let loaded;
                let job = match ctx.deltas {
                    RunDeltas::Ready(jobs) => jobs.get(&part.commit),
                    RunDeltas::Lazy(found) => {
                        loaded = found.live_job(&part.commit);
                        loaded.as_deref()
                    }
                }
                .expect("a queued part belongs to a delta this pull found");
                delta::apply_job_part(
                    ctx.txn,
                    &DeltaSource::Remote(ctx.source),
                    job,
                    part.index,
                    ctx.checks,
                    ctx.progress,
                )
                .await?;
                Step::Part(part.commit)
            }
        };
        Ok((step, read_buf))
    }

    /// Fetches one commit: its detached metadata, then the object, then the
    /// checks of each requested ref that names it. The step stages the
    /// detached metadata when the commit object is here.
    ///
    /// In a run of the attachments, the step checks no signature. For an
    /// attachment that this repository holds complete, it requests no
    /// detached metadata and no object. It reads the commit object of this
    /// repository, and gives the attachments that field 2 of it names. An
    /// attachment that no source holds gives [`Step::Absent`].
    async fn fetch_commit(&self, ctx: &StepCtx<'_>, item: CommitItem) -> Result<Step> {
        let checksum = item.checksum;
        let name = ObjectName::new(checksum, ObjectType::Commit);
        if ctx.done.contains(&checksum) {
            // The commit needs no delta. The head of the delta of an
            // attachment goes here.
            ctx.deltas.release(&checksum);
            return self.done_commit(ctx, checksum).await;
        }
        // Discovery checked the signatures of each commit of a chain, and kept
        // the verified `.commitmeta`: the result of the rule if the check
        // parsed it, else the bytes of the source. The step stages these bytes
        // and does not request them again.
        let (prechecked, filtered, mut known) = match ctx.delta_plan.commit_check(&checksum).await?
        {
            CommitCheck::NotChecked => (false, false, None),
            CommitCheck::Checked { detached, filtered } => (true, filtered, Some(detached)),
        };

        // The two probes of this repository, and the read of a commit that
        // it holds, run in one call on the blocking pool.
        let repo = self.clone();
        let held = ostrya_rt::unblock(move || {
            if !repo.has_object_blocking(ObjectType::Commit, &checksum)? {
                return Ok::<_, Error>(None);
            }
            let complete = repo.commit_state_blocking(&checksum)? == CommitState::Normal;
            let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &checksum)?;
            Ok(Some((complete, bytes)))
        })
        .await?;
        let complete = held.as_ref().is_some_and(|(complete, _)| *complete);
        // How the commit object reaches the object store, after the checks
        // pass. A commit that this repository holds is there already.
        let mut staging = CommitStaging::Held;
        // Detached metadata goes with its commit, and the pull fetches it
        // before the commit. The `ostree` command was observed to request the
        // pair in this order. The pull holds the bytes until the commit object
        // is here, so a commit that the remote does not hold leaves none.
        //
        // The commit bytes are shared, so the bytes of a delta job need no
        // copy.
        let (detached, bytes) = if let Some((_, bytes)) = held {
            let detached = match known.take() {
                Some(detached) => detached,
                // The pull checks no signature of an attachment, and the
                // attachment keeps the detached metadata of this repository.
                None if ctx.attachment_run && complete => None,
                None => {
                    fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
                        .await?
                }
            };
            (detached, Arc::new(bytes))
        } else if let Some(src) = cached_source(ctx.sources, name).await? {
            // A localcache source holds the object. The pull reads the bytes
            // from there one time. The checks read these bytes, and the write
            // after the checks hashes and stages them, in the order of the
            // fetched branches.
            let detached = match known.take() {
                Some(detached) => detached,
                None => {
                    fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
                        .await?
                }
            };
            let bytes = Arc::new(src.load_object_bytes(ObjectType::Commit, &checksum).await?);
            #[cfg(test)]
            super::import_seam::run(self.repo_fd());
            staging = CommitStaging::Write(Arc::clone(&bytes));
            (detached, bytes)
        } else if let Some(commit_bytes) = ctx.deltas.commit_bytes(&checksum).await? {
            // A delta carries the target commit in its superblock, and these
            // bytes come from there. The parse of the superblock verified that
            // they hash to this checksum. For an attachment, discovery wrote
            // them to its record file after that parse, and the step reads
            // them back. The write at staging verifies the checksum again.
            staging = CommitStaging::Write(Arc::clone(&commit_bytes));
            let detached = match known.take() {
                Some(detached) => detached,
                None => {
                    fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
                        .await?
                }
            };
            (detached, commit_bytes)
        } else {
            match self.fetch_remote_commit(ctx, &checksum).await? {
                (detached, Some(bytes)) => {
                    ctx.progress.metadata_fetched();
                    let bytes = Arc::new(bytes);
                    staging = CommitStaging::Write(Arc::clone(&bytes));
                    (detached, bytes)
                }
                // A parent that the remote does not hold ends that chain, as a
                // source with truncated history does for a local pull. The pull
                // drops its detached metadata: this repository holds no commit
                // for it. The plan fails the pull at the end of the run if a
                // commit names the parent as an attachment. A root of a run of
                // the attachments ends here too, and the plan gives the error
                // that names a commit that names it at the end of the run.
                (_, None) if item.optional => return Ok(Step::Absent(checksum)),
                (_, None) => {
                    return Err(Error::ObjectNotFound {
                        checksum,
                        ty: ObjectType::Commit,
                    });
                }
            }
        };

        // A commit object can be as large as `MAX_METADATA_SIZE`, so the parse
        // and the format check of field 2 run on the blocking pool. The check
        // takes the entries out of the parse. The format of field 2 is checked
        // for each commit that the pull reads, also for a pull that follows no
        // attachment. A defective entry fails the pull after the checks of the
        // signatures and of the refs, and before the marker and the staging of
        // the commit. The rule also applies to an attachment that this
        // repository holds complete: a repository that the `ostree` command
        // wrote can hold a commit complete with its attachments absent. So
        // the run reads field 2 of such an attachment from the commit object
        // of this repository, and the next level takes each attachment that
        // it names.
        let shared = Arc::clone(&bytes);
        let (commit, attachments) = ostrya_rt::unblock(move || {
            let mut commit = Commit::parse(&shared)?;
            let related = std::mem::take(&mut commit.related);
            let attachments = related::checked_attachments(&checksum, related);
            Ok::<_, Error>((commit, attachments))
        })
        .await?;
        // The signature verification runs before the pull stages the commit
        // and requests its tree, so a commit that the policy refuses costs no
        // fetch of its own objects. Discovery checked each commit of a chain
        // before the transaction opened: its signatures, and the checks of
        // each requested ref that names it. The step does not check that
        // commit again. The verification reads the detached metadata that
        // this pull puts in place. That is the copy of the remote if it served
        // one, else the copy of this repository. A later verification of the
        // stored commit reads the same metadata.
        // If the verification parses the metadata, the rule of `[ex-ostrya]
        // keep-detached-related` reads that parse right after the
        // verification, and the step keeps only its result. The bytes that
        // the rule of discovery read pass as they are. The step applies the
        // rule to the other bytes that discovery kept, and to a `.commitmeta`
        // that it fetched itself.
        let detached = if prechecked {
            match known {
                None if filtered => Some(CheckedMeta::Filtered(detached)),
                _ => detached.map(CheckedMeta::Source),
            }
        } else if ctx.attachment_run {
            // The pull checks no signature of an attachment. Field 2 of the
            // commit that names the attachment holds its checksum, and the
            // checksum and the signatures of that commit cover field 2. A
            // commit that this repository does not hold is hashed against that
            // checksum when the step below stages it. A commit that this
            // repository holds was hashed when the repository stored it. A
            // target, a parent, and a commit of a chain are not in this run,
            // so each keeps the check of its role. This run has no requested
            // ref.
            detached.map(CheckedMeta::Source)
        } else {
            let detached = check_commit_signatures_filtered(
                self,
                ctx.verification,
                ctx.related,
                &checksum,
                (&bytes).into(),
                detached,
            )
            .await?;
            self.check_tips(ctx, &checksum, &commit).await?;
            detached
        };
        let attachments = attachments?;
        // The checks are the last readers of these bytes. A write keeps its
        // own reference in `staging`, so the other stagings drop the bytes
        // here.
        drop(bytes);

        // The pull writes no partial marker for a commit that this repository
        // holds complete: a pull that fails elsewhere must not demote it.
        if !complete {
            ctx.marking
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .push(checksum);
            ctx.txn
                .track(self.partial_marker_job(&checksum, ctx.marker_fsync))
                .await?;
        }
        // The pull stages the commit here, after its marker and before its
        // tree. The write hashes the bytes that the checks read and compares
        // the result with the requested name. So a commit stored under a wrong
        // name fails here, before the pull fetches its tree, and nothing stays
        // after the step. The marker guards a reader against a commit whose
        // tree is not yet complete. The pull clears the marker after the
        // transaction publishes.
        match staging {
            CommitStaging::Held => {}
            CommitStaging::Write(bytes) => match Arc::try_unwrap(bytes) {
                Ok(bytes) => {
                    ctx.txn
                        .write_metadata_owned(ObjectType::Commit, Some(&checksum), bytes)
                        .await?;
                }
                Err(bytes) => {
                    ctx.txn
                        .write_metadata(ObjectType::Commit, Some(&checksum), &bytes)
                        .await?;
                }
            },
        }
        // The commit object is here, so the pull stages its detached metadata
        // now. The transaction commit writes it before the ref that names the
        // commit. A verifier that reads the signatures with the commit needs
        // this order. For a commit that this repository already holds, the
        // copy of the remote replaces the copy here. That is the purpose of a
        // new read of a mutable file on each pull. An attachment that this
        // repository holds complete is the exception: the step requests no
        // copy, and the copy here stays as it is.
        //
        // The rule runs after the checks read the metadata as the remote
        // holds it: here, after the verification that parsed it, or in
        // discovery after the verification of a commit of a chain that parsed
        // it. So the rule drops `ostrya.related` from what the pull stores,
        // and the verified metadata stays whole. A dict of which the rule
        // keeps no property stages nothing, and the copy of this repository
        // stays as it is.
        if let Some(meta) = detached
            && let Some(meta) = meta.filtered(ctx.related, &checksum).await?
        {
            ctx.txn.stage_commit_detached_bytes(&checksum, meta).await?;
        }
        // Where the objects of the commit come from. A commit that is complete
        // here needs none of them: what it references is present. Its parent
        // is a different case. The depth of an earlier pull can be smaller
        // than the depth of this pull. So the chain walks on, and the step of
        // the parent decides what it needs.
        let tree = vec![
            ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta),
            ObjectName::new(commit.root_dirtree, ObjectType::DirTree),
        ];
        let next = if complete || ctx.flags.contains(PullFlags::COMMIT_ONLY) {
            // The head of the delta of an attachment goes here.
            ctx.deltas.release(&checksum);
            CommitNext::Nothing
        } else {
            // A delta delivers the tree: its parts, and the objects that it
            // names and hands over loose. The tree walk comes after the last
            // part. It finds each object that no part delivered and fetches it
            // loose. The head of the delta of an attachment drops the range of
            // its commit and its fallbacks here.
            ctx.deltas.commit_next(&checksum, tree)
        };
        Ok(Step::Commit(CommitOutcome {
            checksum,
            next,
            parent: commit.parent,
            attachments: if ctx.attachments {
                attachments
            } else {
                Vec::new()
            },
            marked: !complete,
        }))
    }

    /// Makes the ref-binding check and the timestamp check of each requested
    /// ref that names `checksum`.
    ///
    /// The plan fetches a commit once, so a second ref at the same commit has
    /// no step of its own for its checks.
    async fn check_tips(
        &self,
        ctx: &StepCtx<'_>,
        checksum: &Checksum,
        commit: &Commit,
    ) -> Result<()> {
        let refs: Vec<&str> = ctx
            .tips
            .get(checksum)
            .into_iter()
            .flatten()
            .map(String::as_str)
            .collect();
        check_tip_refs(self, ctx.tip_checks, checksum, commit, &refs).await
    }

    /// Runs the step of a commit that an earlier run of this pull made
    /// complete in the transaction.
    ///
    /// The step reads and parses the commit from the transaction in one call
    /// on the blocking pool. It then makes the checks of each requested ref
    /// that names the commit, unless discovery made them. It checks no
    /// signature, requests nothing, and stages nothing. The plan follows the
    /// parent of the commit under `depth`, and its attachments.
    async fn done_commit(&self, ctx: &StepCtx<'_>, checksum: Checksum) -> Result<Step> {
        let mut commit = ctx.txn.load_commit_staged_first(&checksum).await?;
        if !ctx.delta_plan.checked(&checksum) {
            self.check_tips(ctx, &checksum, &commit).await?;
        }
        // Field 2 can hold many entries, so the check runs on the blocking
        // pool.
        let related = std::mem::take(&mut commit.related);
        let attachments =
            ostrya_rt::unblock(move || related::checked_attachments(&checksum, related)).await?;
        Ok(Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Nothing,
            parent: commit.parent,
            attachments: if ctx.attachments {
                attachments
            } else {
                Vec::new()
            },
            marked: false,
        }))
    }

    /// Fetches a commit that only the remote can give, with its detached
    /// metadata. The `.commitmeta` comes from the first localcache source that
    /// holds it, else from the remote. The commit object comes after it.
    /// `None` in either place is a file that the remote does not serve.
    ///
    /// From the stream source, the two remote requests are in flight together,
    /// in the order of an HTTP pull, so the pair costs one round trip. From the
    /// HTTP source, the pull requests the commit after the `.commitmeta`
    /// arrives.
    async fn fetch_remote_commit(
        &self,
        ctx: &StepCtx<'_>,
        commit: &Checksum,
    ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
        let path = object_path(commit, ObjectType::Commit);
        let fetch = || {
            ctx.source
                .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
        };
        match cached_detached_metadata(ctx.sources, commit).await? {
            Some(detached) => Ok((Some(detached), fetch().await?)),
            None if matches!(ctx.source.transfer(), Transfer::Stream(_)) => {
                let (detached, fetched) = futures_lite::future::zip(
                    fetch_remote_detached(ctx.source, ctx.progress, commit),
                    fetch(),
                )
                .await;
                Ok((detached?, fetched?))
            }
            None => {
                let detached = fetch_remote_detached(ctx.source, ctx.progress, commit).await?;
                Ok((detached, fetch().await?))
            }
        }
    }

    /// Fetches one dirtree or dirmeta object and stores it. A dirtree also
    /// reports what it references, for the scan to walk on from.
    async fn fetch_metadata(&self, ctx: &StepCtx<'_>, name: ObjectName) -> Result<Step> {
        // The pull does not fetch an object that is here. It still reads a
        // dirtree: an object that it references can be missing, and the walk
        // finds that.
        if ctx.txn.is_staged(&name.checksum, name.ty)
            || self.has_object(name.ty, &name.checksum).await?
        {
            // An object that this transaction staged stays in the staging
            // directory until the transaction publishes. So the read looks in
            // the staged set before `objects/`.
            return self
                .walked(name, || ctx.txn.load_dirtree_staged_first(&name.checksum))
                .await;
        }
        if let Some(src) = cached_source(ctx.sources, name).await? {
            // The pull reads the object from the localcache source one time.
            // The write hashes these bytes and compares the result with the
            // requested name, and the walk reads the same bytes. So a source
            // that changes after the read cannot pass the hash or change the
            // walk.
            let bytes = src.load_object_bytes(name.ty, &name.checksum).await?;
            #[cfg(test)]
            super::import_seam::run(self.repo_fd());
            ctx.txn
                .write_metadata(name.ty, Some(&name.checksum), &bytes)
                .await?;
            return match name.ty {
                ObjectType::DirTree => Ok(Step::DirTree(name.checksum, DirTree::parse(&bytes)?)),
                _ => Ok(Step::Done),
            };
        }
        let path = object_path(&name.checksum, name.ty);
        let bytes = ctx
            .source
            .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
            .await?
            .ok_or(Error::ObjectNotFound {
                checksum: name.checksum,
                ty: name.ty,
            })?;
        // The write path hashes the bytes and compares the result with the
        // requested name, so a substituted object fails here.
        ctx.txn
            .write_metadata(name.ty, Some(&name.checksum), &bytes)
            .await?;
        ctx.progress.metadata_fetched();
        match name.ty {
            ObjectType::DirTree => Ok(Step::DirTree(name.checksum, DirTree::parse(&bytes)?)),
            _ => Ok(Step::Done),
        }
    }

    /// Returns the step of a stored metadata object. A dirtree reports itself,
    /// for the plan to walk on from. Any other object is a leaf, so the method
    /// calls `load` only for a dirtree.
    async fn walked<F>(&self, name: ObjectName, load: impl FnOnce() -> F) -> Result<Step>
    where
        F: Future<Output = Result<DirTree>>,
    {
        if name.ty != ObjectType::DirTree {
            return Ok(Step::Done);
        }
        Ok(Step::DirTree(name.checksum, load().await?))
    }

    /// Fetches one content object and stores it.
    async fn fetch_content(
        &self,
        ctx: &StepCtx<'_>,
        name: ObjectName,
        read_buf: &mut Vec<u8>,
    ) -> Result<Step> {
        if ctx.txn.is_staged(&name.checksum, ObjectType::File)
            || self.has_object(ObjectType::File, &name.checksum).await?
        {
            return Ok(Step::Done);
        }
        if let Some(src) = cached_source(ctx.sources, name).await? {
            self.import_from(
                ctx.txn,
                src,
                name,
                ctx.flags | PullFlags::UNTRUSTED,
                read_buf,
            )
            .await?;
            return Ok(Step::Done);
        }
        // The pull requests a content object as `.filez`, whatever the remote
        // stores on its disk. The framed, deflated form is the one form that an
        // HTTP client can read.
        let path = object_path(&name.checksum, ObjectType::File);
        let fetcher = match ctx.source.transfer() {
            Transfer::Http(fetcher) => fetcher,
            Transfer::Stream(stream) => {
                // A `.filez` has no whole read. The header read caps its header,
                // and the size that the header declares caps its payload.
                let body = stream
                    .get(&path, u64::MAX)
                    .await?
                    .ok_or(Error::ObjectNotFound {
                        checksum: name.checksum,
                        ty: name.ty,
                    })?;
                // The stream source takes no write permit. The session streams
                // one body at a time, and the depth of the pipeline bounds the
                // stores that finish after the end of their body. If the step
                // took a permit here, the permit holds the one reader of the
                // session while other stores finish.
                self.store_content(ctx, &name.checksum, body, read_buf)
                    .await
                    .map_err(session_error)?;
                ctx.progress.content_fetched();
                return Ok(Step::Done);
            }
        };
        // If a body fails in transit, the pull fetches it again from the
        // start, and the retry count of the fetcher pays for it. The write that
        // failed with it stages nothing, because an object is staged only
        // after the checksum comparison. The write removes its temp file when
        // it fails.
        let mut refetch = fetcher.refetching(FetchRequest {
            priority: Priority::Low,
            ..FetchRequest::path(&path)
        });
        loop {
            let body = match refetch.fetch().await {
                Ok(Fetched::Body(body)) => body,
                Ok(Fetched::NotModified) => {
                    return Err(Error::Fetch(format!(
                        "{path}: the remote answered 304 to an unconditional request"
                    )));
                }
                Err(e) => return Err(object_not_found(e.into(), name)),
            };
            // The step takes the write permit before it reads the body. A step
            // that waits for a permit did not ask the connection for bytes yet,
            // so the progress window of the fetcher does not run against it.
            // The permit covers the whole body: the header read, the payload,
            // and the end-of-stream read. The step releases it before a refetch
            // waits for its delay.
            let permit = ctx.writes.acquire(Priority::Normal).await;
            let stored = self
                .store_content(ctx, &name.checksum, body, read_buf)
                .await;
            drop(permit);
            match stored {
                Ok(()) => {
                    ctx.progress.content_fetched();
                    return Ok(Step::Done);
                }
                Err(e) => refetch.retry(e).await?,
            }
        }
    }

    /// Stores one fetched content object under the requested name.
    ///
    /// The payload streams through `read_buf`, the buffer of the slot, so the
    /// objects that a slot stores share one allocation.
    async fn store_content<R: AsyncRead + Unpin>(
        &self,
        ctx: &StepCtx<'_>,
        expected: &Checksum,
        body: R,
        read_buf: &mut Vec<u8>,
    ) -> Result<()> {
        let (header, declared, framed_header, body) = read_archive_header(body).await?;
        let FileHeader {
            uid,
            gid,
            mode,
            symlink_target: _,
            xattrs,
        } = header.clone();
        let meta = FileMeta {
            uid,
            gid,
            mode,
            xattrs,
        };
        // The mode checks of a local pull, over the metadata in the header that
        // arrives with the object.
        ctx.checks.check(expected, &meta)?;
        store_filez_payload(
            ctx.txn,
            expected,
            &header,
            &meta,
            declared,
            &framed_header,
            body,
            read_buf,
        )
        .await
    }
}

/// What a pull fetched into its transaction, for the transaction commit.
struct FetchedPull {
    txn: Transaction,
    /// The refs to write, and the commit each names.
    targets: Vec<(String, Checksum)>,
    /// The `summary` and `summary.sig` of the remote, which a mirror pull of
    /// every ref copies. Each other pull keeps neither.
    summary: Option<Vec<u8>>,
    signature: Option<Vec<u8>>,
}

/// Returns `endpoint` with the request limit `max_outstanding` of the caller,
/// and the options of a stream session to it.
///
/// A limit of the caller replaces the limit of the endpoint. The pull keeps as
/// many steps in flight as the session admits.
pub(super) fn session_options(
    endpoint: Endpoint,
    max_outstanding: Option<usize>,
) -> (Endpoint, StreamSessionOptions) {
    match endpoint {
        Endpoint::Http(mut http) => {
            if let Some(n) = max_outstanding {
                http.max_outstanding = n;
            }
            (Endpoint::Http(http), StreamSessionOptions::default())
        }
        ssh @ Endpoint::Ssh { .. } => (
            ssh,
            StreamSessionOptions {
                agent: None,
                max_outstanding,
            },
        ),
        #[cfg(feature = "s3")]
        Endpoint::S3(mut s3) => {
            if let Some(n) = max_outstanding {
                s3.http.max_outstanding = n;
            }
            (Endpoint::S3(s3), StreamSessionOptions::default())
        }
        // `connect` refuses each other endpoint.
        other => (other, StreamSessionOptions::default()),
    }
}

/// Opens the session of a pull to `endpoint`.
///
/// Over ssh, the session takes the options `stream`. Over HTTP, the options
/// of the endpoint give the request limit, and `stream` must be the default.
///
/// An S3 endpoint gives an HTTP session whose fetcher signs each request,
/// and the bucket client of the repository over the same fetcher, which
/// reads the files at its root. An S3 endpoint has the rules of an HTTP
/// endpoint for `stream`.
pub(super) async fn connect(
    endpoint: Endpoint,
    stream: StreamSessionOptions,
) -> Result<Connection> {
    match endpoint {
        Endpoint::Http(http) => PullSession::connect(Endpoint::Http(http), stream)
            .await
            .map(Connection::from)
            .map_err(http_error),
        ssh @ Endpoint::Ssh { .. } => Ok(PullSession::connect(ssh, stream).await?.into()),
        #[cfg(feature = "s3")]
        Endpoint::S3(s3) => {
            let fetcher = s3_fetcher(&s3, stream).await?;
            // The bucket client shares the fetcher of the session, so the
            // pull builds one fetcher.
            let bucket = crate::remote::s3::Bucket::from_fetcher(&s3, fetcher.clone());
            Ok(Connection {
                session: PullSession::Http(fetcher),
                bucket: Some(bucket),
            })
        }
        _ => Err(crate::endpoint::neither_ssh_nor_http("a pull")),
    }
}

/// Builds the signed fetcher of a pull from the bucket repository of `s3`.
///
/// The fetcher takes the options that `S3Endpoint::pull_options` gives, and
/// `stream` has the rules of an HTTP endpoint. The fetcher is the fetcher
/// that [`PullSession::connect`] builds for an S3 endpoint. The call sends no
/// request.
#[cfg(feature = "s3")]
pub(super) async fn s3_fetcher(
    s3: &crate::remote::s3::S3Endpoint,
    stream: StreamSessionOptions,
) -> Result<Fetcher> {
    let options = s3.pull_options().map_err(http_error)?;
    // The future is boxed, so that the future of an ssh connect does not
    // hold the construction of the fetcher.
    let session = Box::pin(PullSession::connect(Endpoint::Http(options), stream))
        .await
        .map_err(http_error)?;
    let PullSession::Http(fetcher) = session else {
        unreachable!("an HTTP endpoint opens an HTTP session");
    };
    Ok(fetcher)
}

/// Makes the checks of [`Repo::pull_with_session`] over `opts`, and returns
/// the parsed subpaths and the index of the list of static deltas.
///
/// Each check reads `opts` alone, so a refusal sends no request and opens no
/// transaction. The call takes the list out of `opts`, as
/// [`take_static_deltas`] states.
async fn check_session_pull(opts: &mut PullOptions) -> Result<(Option<Subpaths>, Option<Edges>)> {
    let subpaths = Subpaths::parse(&opts.subpaths)?;
    check_depth(opts.depth)?;
    check_remote_option(opts)?;
    check_static_deltas(opts)?;
    if opts.refs.is_empty() {
        return Err(no_refs());
    }
    check_remote_operands(opts)?;
    if opts.verify != PullVerify::default() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its signature policy from its trust, and \
             takes no verify option"
                .into(),
        ));
    }
    if opts.trust_group.is_some() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its signature policy from its trust, and \
             takes no trust group"
                .into(),
        ));
    }
    if opts.max_outstanding_fetches.is_some() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its request limit from the session, and \
             takes no max_outstanding_fetches option"
                .into(),
        ));
    }
    if opts.overrides != EndpointOverrides::default() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its server from the session, and takes \
             no endpoint overrides"
                .into(),
        ));
    }
    let edges = take_static_deltas(opts).await?;
    Ok((subpaths, edges))
}

/// Returns the refusal of a pull with a session that names no ref.
fn no_refs() -> Error {
    Error::InvalidInput("a pull with a session needs at least one ref name".into())
}

/// How a pull from a remote gets the commit of one name.
enum Resolved {
    /// From the summary, else from a ref file of the remote. The value is
    /// the collection id and the ref name of an `@ID:NAME` operand.
    Lookup(Option<(String, String)>),
    /// From a `REF@CHECKSUM` operand.
    At(Checksum),
    /// From a `CHECKSUM` operand, which has no ref.
    Bare(Checksum),
}

/// The refs that a pull from a remote takes if
/// [`refs`](PullOptions::refs) is empty, or the refs of a collection pull.
#[derive(Clone, Copy)]
pub(super) enum Wanted<'a> {
    /// No other ref. [`Repo::pull_with_session`] refuses an empty list.
    Named,
    /// Under [`MIRROR`](PullFlags::MIRROR), each ref of the summary of the
    /// remote. Otherwise, the refs of the `branches` key of the remote
    /// section of this name and the refs of the summary that the
    /// `pull-branches` key of that section selects.
    Config {
        /// The name of the remote.
        remote: &'a str,
        /// The key `collection-id` of the remote section, for the
        /// collection-binding check of a commit that an operand names with
        /// no ref. `None` for a section with no such key, and for a pull
        /// with no such operand.
        commit_collection: Option<&'a str>,
    },
    /// The refs of a collection pull, each at the commit that the pull
    /// selected. The pull reads no ref of the remote, and does not read
    /// [`refs`](PullOptions::refs).
    Pinned(&'a Pinned<'a>),
}

/// The state that every step of one pull shares.
struct StepCtx<'a> {
    txn: &'a Transaction,
    source: &'a RemoteSource,
    /// The write throttle: the number of fetched content objects that stream
    /// into the object store at once.
    writes: Arc<Gate>,
    /// The repositories that the pull reads for an object before the network,
    /// in order.
    sources: &'a [Repo],
    flags: PullFlags,
    /// The mode checks for each content object that this pull writes, on each
    /// path: a loose fetch, a localcache import, or the parts of a static
    /// delta.
    checks: ModeChecks,
    /// The checks of each requested ref: the ref-binding check, the timestamp
    /// check that the pull resolved before discovery, and the place of the
    /// pulled refs, where the timestamp check reads the current tip of a ref.
    tip_checks: TipChecks<'a>,
    /// The requested refs of each tip commit, for the binding check and the
    /// timestamp check. A commit with no entry is a parent under `depth`,
    /// which no ref names. The map is empty in the run of a level of
    /// intermediate commits.
    tips: &'a HashMap<Checksum, Vec<String>>,
    /// The static delta that delivers each commit of this run, if the remote
    /// publishes one. The pull fetches a commit with no entry object by
    /// object.
    deltas: RunDeltas<'a>,
    /// The commits that an earlier run of this pull made complete in the
    /// transaction. The step stages nothing for them and checks no signature
    /// again.
    done: &'a HashSet<Checksum>,
    /// The checks that discovery made on the commit of each step of a chain.
    delta_plan: &'a DeltaPlan,
    /// The signature policy of this pull. The pull verifies each commit of a
    /// step before it stages its bytes, except in the run of the
    /// attachments.
    verification: &'a Verification,
    /// The rule of `[ex-ostrya] keep-detached-related` of this repository. It
    /// applies to the detached metadata that this pull stores, after the
    /// checks of the commit pass.
    related: RelatedRule,
    /// `true` if the pull follows the attachments of each commit that it
    /// reads: a pull that is not commit-only and has no subpath.
    attachments: bool,
    /// `true` for a run of the attachments, one for each level. Each commit
    /// of that run is an attachment alone, and the step checks no signature
    /// of it.
    attachment_run: bool,
    /// The commits whose `.commitpartial` marker a step of this run writes. A
    /// step adds the commit before it starts the write of the marker, and the
    /// write is a tracked job of the transaction. A failed run waits for the
    /// tracked jobs of its dropped steps before it reads the list. So it
    /// hands each marker that it wrote to the cleanup, also the marker of a
    /// step that failed or that the run dropped in flight.
    marking: Mutex<Vec<Checksum>>,
    /// The `fsync` rule of the transaction for the markers that a step
    /// writes.
    marker_fsync: bool,
    /// The live counters of the pull.
    progress: &'a PullCounters,
}

/// The commits of one run of the plan, and how the pull fetches them.
struct Phase<'a> {
    /// The commits that the run starts from.
    roots: &'a [Checksum],
    /// The requested refs of each tip commit, as [`StepCtx`] holds them.
    tips: &'a HashMap<Checksum, Vec<String>>,
    /// The number of parents to follow from each root, `-1` for all of them.
    depth: i32,
    /// The subpaths of the walk. `None` walks every tree whole.
    subpaths: Option<Subpaths>,
    /// The static delta of each commit of this run.
    deltas: RunDeltas<'a>,
    /// The commits that an earlier run made complete in the transaction.
    done: &'a HashSet<Checksum>,
    /// `true` for the last run of the pull. The scanning state of the pull
    /// ends with that run. A pull that follows attachments has no such run:
    /// a run of the attachments does not know if a level follows it, so the
    /// pull ends the scanning state after the last level.
    last: bool,
    /// `true` for a run of the attachments, as [`StepCtx`] holds it.
    attachment_run: bool,
}

/// The static deltas of one run of the plan.
#[derive(Clone, Copy)]
enum RunDeltas<'a> {
    /// The jobs that the pull parsed before the run: the jobs of a level of
    /// intermediate commits, or of the targets. They live for the run.
    Ready(&'a HashMap<Checksum, DeltaJob>),
    /// The deltas of the attachments of one level. The step of a commit
    /// reads the head of its delta. A load step parses the job just before
    /// the parts, and the run releases the job after the last part. The plan
    /// loads at most [`PART_CAP`] jobs at a time.
    Lazy(&'a AttachmentDeltas),
}

impl RunDeltas<'_> {
    /// Returns the commit bytes that the delta of `commit` carries, or `None`
    /// if the commit has no delta. For an attachment, the call reads them from
    /// the record file of the search.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if the record file cannot be read.
    async fn commit_bytes(self, commit: &Checksum) -> Result<Option<Arc<Vec<u8>>>> {
        match self {
            RunDeltas::Ready(jobs) => Ok(jobs.get(commit).map(|job| Arc::clone(&job.commit_bytes))),
            RunDeltas::Lazy(found) => Ok(found.commit_bytes(commit).await?.map(Arc::new)),
        }
    }

    /// Returns how the objects of `commit` reach this repository: by its
    /// delta, or by the walk from `tree` if the commit has no delta. For an
    /// attachment, the head of the delta then drops the range of its commit
    /// and its fallbacks, and a delta with no part drops its head.
    fn commit_next(self, commit: &Checksum, tree: Vec<ObjectName>) -> CommitNext {
        let delta = match self {
            RunDeltas::Ready(jobs) => jobs
                .get(commit)
                .map(|job| (job.parts(), job.fallbacks(), false)),
            RunDeltas::Lazy(found) => found
                .take_commit_delta(commit)
                .map(|(parts, fallbacks)| (parts, fallbacks, true)),
        };
        match delta {
            Some((parts, fallbacks, lazy)) => CommitNext::Delta {
                parts,
                fallbacks,
                tree,
                lazy,
            },
            None => CommitNext::Scan(tree),
        }
    }

    /// Releases the job and the head of the delta of `commit`: after its last
    /// part, or in the step of a commit that needs no delta. The call does
    /// nothing for a job that the pull parsed before the run.
    fn release(self, commit: &Checksum) {
        if let RunDeltas::Lazy(found) = self {
            found.release_job(commit);
        }
    }
}

/// What one run of the plan leaves for the next run.
#[derive(Default)]
struct Carry {
    /// The objects that the runs queued, so that the pull fetches an object
    /// once over all runs.
    queued: HashSet<ObjectName>,
    /// The units of work that the runs gave to a slot, for the progress total.
    started: usize,
    /// The attachments that the runs met, so that the checks of an
    /// attachment span all runs.
    attachments: PlanAttachments,
    /// The parent that each commit of the runs named. A commit is here if a
    /// run reached it, an attachment of a level included. A pull that follows
    /// no attachment keeps no parent.
    parents: HashMap<Checksum, Option<Checksum>>,
}

/// One commit to fetch.
struct CommitItem {
    checksum: Checksum,
    /// The number of parents to follow from here, `-1` for all of them.
    depth: i32,
    /// `true` if the step gives [`Step::Absent`] when no source holds this
    /// commit, and `false` if the step fails. A parent under `depth` and a
    /// root of a run of the attachments have the value `true`. A parent that
    /// no source holds ends its chain, and the pull goes on. The plan fails
    /// the pull at the end of the run if a commit of the pull names an absent
    /// commit as an attachment.
    optional: bool,
}

/// One part of the delta of one commit.
struct PartItem {
    /// The commit that the delta produces, which is the key of the job.
    commit: Checksum,
    /// The index of the part. It is the position of the part in the entry
    /// list of the superblock, and its file name on the remote.
    index: usize,
}

/// One unit of work that a slot runs.
enum Item {
    Commit(CommitItem),
    Object(ObjectName),
    /// The load of the job of the delta of an attachment, before its parts.
    /// The value is the commit of the delta.
    Load(Checksum),
    Part(PartItem),
}

/// The outcome of one step.
enum Step {
    /// A commit object arrived, or was already here.
    Commit(CommitOutcome),
    /// A dirtree is stored: its checksum and its entries, which the plan walks
    /// on from.
    DirTree(Checksum, DirTree),
    /// The job of the delta of an attachment is loaded. The value is the
    /// commit of the delta.
    Loaded(Checksum),
    /// A delta part is applied. The value is the commit of the part.
    Part(Checksum),
    /// Nothing follows: a dirmeta or content object is stored.
    Done,
    /// No source holds a commit of an optional item: a parent, which ends
    /// its chain, or an attachment. The value is the commit.
    Absent(Checksum),
}

/// What a commit adds to the plan.
struct CommitOutcome {
    checksum: Checksum,
    /// How the pull fetches the objects of the commit.
    next: CommitNext,
    /// The parent to follow under `depth`.
    parent: Option<Checksum>,
    /// The name and the checksum of each attachment to follow, in the order
    /// of field 2. The list is empty if the pull follows no attachment.
    attachments: Vec<(String, Checksum)>,
    /// `true` if this pull wrote the `.commitpartial` marker of the commit.
    marked: bool,
}

/// How a commit object reaches the object store, after the commit passes the
/// checks of its step.
enum CommitStaging {
    /// This repository holds it.
    Held,
    /// Its bytes are in memory, and the pull writes them into the transaction.
    Write(Arc<Vec<u8>>),
}

/// How the objects of a commit reach this repository.
enum CommitNext {
    /// Object by object: the root dirmeta and dirtree of the commit, and the
    /// walk from there.
    Scan(Vec<ObjectName>),
    /// By static delta: the parts of the delta, the objects that it hands over
    /// loose, and the tree walk after the last part.
    Delta {
        parts: usize,
        fallbacks: Vec<ObjectName>,
        tree: Vec<ObjectName>,
        /// `true` if a load step loads the job of the delta before the parts,
        /// as [`RunDeltas::Lazy`] states.
        lazy: bool,
    },
    /// Nothing: the commit is complete here, or the pull is commit-only.
    Nothing,
}

/// The work that the pull must still do, and the work that it did.
///
/// The loop owns the plan, so nothing here is shared or locked.
#[derive(Default)]
struct Plan {
    /// The commits, drained first and fetched at high priority.
    commits: VecDeque<CommitItem>,
    /// The delta parts, drained second and fetched at high priority. At most
    /// [`PART_CAP`] are in flight, whatever the slot count of the pull.
    parts: VecDeque<PartItem>,
    /// The number of part fetches in flight.
    parts_in_flight: usize,
    /// The commits whose job of a delta waits for its load step, drained
    /// after the parts and fetched at high priority.
    loads: VecDeque<Checksum>,
    /// The commits whose job a load step loads, or loaded, until the last
    /// part of the delta. The plan gives out no load step while
    /// [`PART_CAP`] commits are here, so at most [`PART_CAP`] jobs are loaded
    /// at once.
    loaded: HashSet<Checksum>,
    /// The number of parts of the deltas whose load step did not queue them
    /// yet. The progress total counts them, as it counts queued parts.
    waiting_parts: usize,
    /// The number of parts of the delta of each commit that are not applied
    /// yet. When that count is zero, the plan queues the tree walk that
    /// `delta_trees` holds.
    delta_parts: HashMap<Checksum, usize>,
    delta_trees: HashMap<Checksum, Vec<ObjectName>>,
    /// The dirtree and dirmeta objects that the walk waits for, drained third
    /// and fetched at high priority.
    scan: VecDeque<ObjectName>,
    /// The content objects, drained fourth and fetched at low priority.
    content: VecDeque<ObjectName>,
    /// The objects that this pull queued, so that the pull fetches an object
    /// once, also if several commits reach it.
    queued: HashSet<ObjectName>,
    /// The subpaths of the walk. `None` walks every tree whole.
    subpaths: Option<Subpaths>,
    /// The scope of the walk of the root dirtree of each commit.
    root: Scope,
    /// The dirtrees queued under a scope smaller than the whole tree. Each
    /// entry holds the scope of the walk, and a flag that tells if the plan
    /// applied that walk.
    ///
    /// If the plan reaches a dirtree again under a scope that its scope does
    /// not cover, the plan widens its scope. A dirtree that is still queued or
    /// in flight gets the walk under the wider scope when the plan applies its
    /// step. The plan queues a walked dirtree again, and that second step reads
    /// the dirtree that this pull stored.
    partial_trees: HashMap<Checksum, PartialTree>,
    /// The remaining depth at which the plan reached each commit. It decides
    /// if a chain that reaches the commit again walks on from it.
    seen: HashMap<Checksum, i32>,
    /// The parent that each fetched commit named. A chain that reaches the
    /// commit again, with more depth, resumes at the parent and does not fetch
    /// the commit again.
    parents: HashMap<Checksum, Option<Checksum>>,
    /// The attachments that the plan met, and the commits that it checks
    /// them against.
    attachments: PlanAttachments,
}

/// The state of the checks of the attachments of one pull.
///
/// The checks do not depend on the order in which the steps end. A commit
/// that a commit of the pull names as an attachment, and that no source
/// holds, fails the pull at the end of the run, whichever of the two facts
/// the plan learns first. The error names a commit that names the
/// attachment: of the commits of the lowest level that name it, the commit
/// with the lowest checksum. The entry name is the name of the first entry
/// of that commit that names the attachment. The commits of the runs of the
/// chains and of the targets are level 0, and the attachments of level `k`
/// are level `k`. If several attachments fail in one run, the error names
/// the attachment with the lowest checksum.
#[derive(Default)]
struct PlanAttachments {
    /// The attachments, and the commits that name them. A pull that looks
    /// for no delta of an attachment keeps no entry of field 2.
    inner: attachment::Attachments,
    /// The commits that no source holds: the parents under `depth`, and the
    /// roots of the runs of the attachments.
    absent: HashSet<Checksum>,
    /// The level of the commits of the current run.
    level: usize,
}

/// A dirtree walked under a scope smaller than the whole tree.
struct PartialTree {
    scope: Scope,
    walked: bool,
}

impl Plan {
    /// Creates a plan whose walk keeps to `subpaths`.
    fn new(subpaths: Option<Subpaths>) -> Plan {
        Plan {
            root: subpaths.as_ref().map(Subpaths::root).unwrap_or_default(),
            subpaths,
            ..Plan::default()
        }
    }

    /// Queues a commit, unless the plan reached it at this depth or deeper.
    ///
    /// The plan does not fetch again a commit that it reaches again with more
    /// depth: the walk resumes at the parent that the commit named. A commit
    /// still in flight named no parent yet. Its own outcome follows the parent
    /// to the depth recorded here.
    fn push_commit(&mut self, mut item: CommitItem) {
        loop {
            if let Some(&prev) = self.seen.get(&item.checksum)
                && reaches_at_least(prev, item.depth)
            {
                return;
            }
            let depth = item.depth;
            if self.seen.insert(item.checksum, depth).is_none() {
                self.commits.push_back(item);
                return;
            }
            if depth == 0 {
                return;
            }
            let Some(Some(parent)) = self.parents.get(&item.checksum).copied() else {
                return;
            };
            item = CommitItem {
                checksum: parent,
                depth: one_less(depth),
                optional: true,
            };
        }
    }

    /// Queues an object that this pull did not queue yet, and a dirtree that it
    /// queued under a scope that does not cover `scope`.
    fn push_object(&mut self, name: ObjectName, scope: Scope) {
        if self.queued.insert(name) {
            if name.ty == ObjectType::DirTree && scope != Scope::All {
                self.partial_trees.insert(
                    name.checksum,
                    PartialTree {
                        scope,
                        walked: false,
                    },
                );
            }
            match name.ty {
                ObjectType::File => self.content.push_back(name),
                _ => self.scan.push_back(name),
            }
            return;
        }
        if name.ty != ObjectType::DirTree {
            return;
        }
        // A dirtree with no entry here was queued whole.
        let Some(tree) = self.partial_trees.get_mut(&name.checksum) else {
            return;
        };
        if tree.scope.covers(&scope) {
            return;
        }
        tree.scope.widen(&scope);
        if tree.walked {
            tree.walked = false;
            self.scan.push_back(name);
        }
    }

    /// Queues one object of the tree of a commit: the root dirtree under the
    /// root scope, or the root dirmeta.
    fn push_root(&mut self, name: ObjectName) {
        let scope = if name.ty == ObjectType::DirTree {
            self.root.clone()
        } else {
            Scope::All
        };
        self.push_object(name, scope);
    }

    /// Queues the objects that a stored dirtree references, under the scope of
    /// its walk.
    fn apply_dirtree(&mut self, checksum: Checksum, dirtree: &DirTree) {
        let Some(subpaths) = &self.subpaths else {
            for name in children_of(dirtree) {
                self.push_object(name, Scope::All);
            }
            return;
        };
        let scope = match self.partial_trees.get_mut(&checksum) {
            Some(tree) => {
                tree.walked = true;
                tree.scope.clone()
            }
            None => Scope::All,
        };
        for (name, scope) in subpaths.children(dirtree, &scope) {
            self.push_object(name, scope);
        }
    }

    /// Returns the next unit of work: the commits, then the delta parts, then
    /// the loads of the jobs, then the scan, then the content.
    ///
    /// The plan holds back a queued part while [`PART_CAP`] parts are in
    /// flight. A pull with more slots spends the other slots on the scan and
    /// the content. The loop can run out of work while parts are queued. This
    /// is safe: the plan holds back a part only while a part is in flight, in a
    /// slot that the loop waits on.
    ///
    /// The plan also holds back a load while [`PART_CAP`] jobs are loaded and
    /// have parts to apply. This is safe for the same reason: each of these
    /// jobs has a load step or a part in flight, or a queued part that the
    /// plan gives out.
    fn next(&mut self) -> Option<Item> {
        if let Some(commit) = self.commits.pop_front() {
            return Some(Item::Commit(commit));
        }
        if self.parts_in_flight < PART_CAP
            && let Some(part) = self.parts.pop_front()
        {
            self.parts_in_flight += 1;
            return Some(Item::Part(part));
        }
        if self.loaded.len() < PART_CAP
            && let Some(commit) = self.loads.pop_front()
        {
            self.loaded.insert(commit);
            return Some(Item::Load(commit));
        }
        if let Some(name) = self.scan.pop_front() {
            return Some(Item::Object(name));
        }
        self.content.pop_front().map(Item::Object)
    }

    /// Stores the progress total and the scan state: the `started` units of
    /// work given to a slot, and the queued work. `more` is `true` if a later
    /// run of the plan follows this run. The pull then still scans.
    fn report(&self, progress: &PullCounters, started: usize, more: bool) {
        let queued = self.commits.len()
            + self.parts.len()
            + self.waiting_parts
            + self.scan.len()
            + self.content.len();
        let total = u32::try_from(started + queued).unwrap_or(u32::MAX);
        progress.report(
            total,
            more || !self.commits.is_empty() || !self.scan.is_empty(),
        );
    }

    /// Adds the outcome of one step to the plan.
    fn apply(&mut self, step: Step, marked: &mut Vec<Checksum>) {
        match step {
            Step::Commit(outcome) => self.apply_commit(outcome, marked),
            Step::DirTree(checksum, dirtree) => self.apply_dirtree(checksum, &dirtree),
            Step::Loaded(commit) => self.apply_load(commit),
            Step::Part(commit) => self.apply_part(commit),
            Step::Absent(commit) => self.apply_absent(commit),
            Step::Done => {}
        }
    }

    /// Checks the attachments at the end of a run, when each step of the run
    /// reached the plan.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidRelations`] if a commit of the pull names as an
    /// attachment a commit that no source holds. The error names the commit
    /// and the entry, as [`PlanAttachments`] states.
    fn check_attachments(&self) -> Result<()> {
        let unheld = self
            .attachments
            .absent
            .iter()
            .filter(|commit| self.attachments.inner.named(commit).is_some())
            .min();
        match unheld.and_then(|commit| {
            self.attachments
                .inner
                .named_error(commit, related::UNHELD_REASON)
        }) {
            Some(err) => Err(err),
            None => Ok(()),
        }
    }

    /// Records a loaded job of a delta, and queues its parts.
    fn apply_load(&mut self, commit: Checksum) {
        let parts = *self
            .delta_parts
            .get(&commit)
            .expect("a loaded job belongs to a commit whose delta is counted");
        self.waiting_parts -= parts;
        for index in 0..parts {
            self.parts.push_back(PartItem { commit, index });
        }
    }

    /// Records an applied delta part. After the last part of the delta, queues
    /// the tree walk of its commit, and the plan no longer counts its job as
    /// loaded. The caller then releases the job.
    fn apply_part(&mut self, commit: Checksum) {
        self.parts_in_flight -= 1;
        let left = self
            .delta_parts
            .get_mut(&commit)
            .expect("an applied part belongs to a commit whose delta is counted");
        *left -= 1;
        if *left > 0 {
            return;
        }
        self.delta_parts.remove(&commit);
        self.loaded.remove(&commit);
        // Each object of the delta is staged now. The walk reads what is here,
        // and requests from the network only what the delta left out.
        for name in self.delta_trees.remove(&commit).unwrap_or_default() {
            self.push_root(name);
        }
    }

    /// Records a commit and queues what it needs: its objects and its parent
    /// under `depth`. The call records the attachments of the commit and does
    /// not queue them. The pull fetches them in a later run, at depth 0, so it
    /// follows no parent of an attachment. The commit can itself be an
    /// attachment, and its attachments then go into the next level. The marker
    /// of the commit goes into `marked` first, so the caller clears it if the
    /// run fails.
    fn apply_commit(&mut self, outcome: CommitOutcome, marked: &mut Vec<Checksum>) {
        if outcome.marked {
            marked.push(outcome.checksum);
        }
        self.parents.insert(outcome.checksum, outcome.parent);
        match outcome.next {
            CommitNext::Nothing => {}
            CommitNext::Scan(tree) => {
                for name in tree {
                    self.push_root(name);
                }
            }
            CommitNext::Delta {
                parts,
                fallbacks,
                tree,
                lazy,
            } => {
                // The plan queues the objects that the delta hands over loose at
                // once, so they travel together with the parts.
                for name in fallbacks {
                    self.push_object(name, Scope::All);
                }
                if parts == 0 {
                    // A delta of fallbacks alone has no part to wait for.
                    for name in tree {
                        self.push_root(name);
                    }
                } else if lazy {
                    // The job of the delta is not loaded yet. The load step
                    // queues the parts.
                    self.delta_parts.insert(outcome.checksum, parts);
                    self.delta_trees.insert(outcome.checksum, tree);
                    self.loads.push_back(outcome.checksum);
                    self.waiting_parts += parts;
                } else {
                    self.delta_parts.insert(outcome.checksum, parts);
                    self.delta_trees.insert(outcome.checksum, tree);
                    for index in 0..parts {
                        self.parts.push_back(PartItem {
                            commit: outcome.checksum,
                            index,
                        });
                    }
                }
            }
        }
        // The depth comes from the plan. A later chain can reach this commit
        // with more depth while the commit is in flight.
        let depth = self.seen.get(&outcome.checksum).copied().unwrap_or(0);
        if depth != 0
            && let Some(parent) = outcome.parent
        {
            self.push_commit(CommitItem {
                checksum: parent,
                depth: one_less(depth),
                optional: true,
            });
        }
        self.apply_attachments(outcome.checksum, outcome.attachments);
    }

    /// Records the attachments of `commit`, a commit of the level of the
    /// run, for the checks and for the run that fetches them.
    fn apply_attachments(&mut self, commit: Checksum, attachments: Vec<(String, Checksum)>) {
        let level = self.attachments.level;
        self.attachments.inner.record_at(level, commit, attachments);
    }

    /// Records a commit that no source holds: a parent under `depth`, or an
    /// attachment. [`check_attachments`](Plan::check_attachments) fails the
    /// pull at the end of the run if a commit of the pull names it as an
    /// attachment.
    fn apply_absent(&mut self, commit: Checksum) {
        self.attachments.absent.insert(commit);
    }
}

/// Returns the depth after one parent: a finite depth counts down, and `-1`
/// stays `-1`.
fn one_less(depth: i32) -> i32 {
    if depth > 0 { depth - 1 } else { depth }
}

/// Returns the objects that a dirtree references: its files, and the dirmeta
/// and dirtree of each subdirectory.
fn children_of(dirtree: &DirTree) -> Vec<ObjectName> {
    let mut out = Vec::with_capacity(dirtree.files.len() + 2 * dirtree.dirs.len());
    for (_, file) in &dirtree.files {
        out.push(ObjectName::new(*file, ObjectType::File));
    }
    for (_, subtree, submeta) in &dirtree.dirs {
        out.push(ObjectName::new(*submeta, ObjectType::DirMeta));
        out.push(ObjectName::new(*subtree, ObjectType::DirTree));
    }
    out
}

/// Returns the request path of a loose object. The remote is an archive
/// repository, so a content object has the name `.filez` there, whatever this
/// repository stores.
pub(super) fn object_path(checksum: &Checksum, ty: ObjectType) -> String {
    format!("objects/{}", loose_path(checksum, ty, RepoMode::Archive))
}

/// Reads the `.commitmeta` of a commit from the first localcache source in
/// `sources` that holds it, else from `source`, the remote.
///
/// The caller writes the bytes when the commit object is here. A 404 means
/// that the commit has none, and the copy of this repository stays as it is.
pub(super) async fn fetch_detached_metadata(
    source: &RemoteSource,
    sources: &[Repo],
    progress: &PullCounters,
    commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
    if let Some(bytes) = cached_detached_metadata(sources, commit).await? {
        return Ok(Some(bytes));
    }
    fetch_remote_detached(source, progress, commit).await
}

/// Fetches the `.commitmeta` of a commit from the remote, or `None` if the
/// remote serves none. A file that the remote serves adds one to the metadata
/// count in `progress`.
pub(super) async fn fetch_remote_detached(
    source: &RemoteSource,
    progress: &PullCounters,
    commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
    let path = object_path(commit, ObjectType::CommitMeta);
    let fetched = source
        .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
        .await?;
    if fetched.is_some() {
        progress.metadata_fetched();
    }
    Ok(fetched)
}

/// Returns the `.commitmeta` of a commit from the first localcache repository
/// that holds it.
async fn cached_detached_metadata(sources: &[Repo], commit: &Checksum) -> Result<Option<Vec<u8>>> {
    for src in sources {
        if let Some(bytes) = src
            .held_object_bytes(ObjectType::CommitMeta, commit)
            .await?
        {
            return Ok(Some(bytes));
        }
    }
    Ok(None)
}

/// Returns the first localcache repository that holds `name`.
pub(super) async fn cached_source(sources: &[Repo], name: ObjectName) -> Result<Option<&Repo>> {
    for src in sources {
        if src.has_object(name.ty, &name.checksum).await? {
            return Ok(Some(src));
        }
    }
    Ok(None)
}

/// Maps a 404 for an object to [`Error::ObjectNotFound`]. Any other error
/// stays as it is.
fn object_not_found(error: Error, name: ObjectName) -> Error {
    match error {
        Error::HttpStatus { status: 404, .. } => Error::ObjectNotFound {
            checksum: name.checksum,
            ty: name.ty,
        },
        other => other,
    }
}

/// What a pull reads of the `config` of its remote.
#[derive(Default)]
struct RemoteConfig {
    /// The `[core] collection-id` of the remote.
    collection_id: Option<String>,
    /// `true` if the `config` states `[core] indexed-deltas=true`. A remote
    /// with no `config`, a `config` with no such key, and a value that is
    /// not a boolean give `false`.
    indexed_deltas: bool,
}

/// Refuses a remote whose `[core] mode` is not archive, from the bytes of its
/// `config`, and returns what the pull reads of that `config`.
fn check_remote_mode(config: Option<Vec<u8>>) -> Result<RemoteConfig> {
    let Some(bytes) = config else {
        // The pull reads a remote that serves no config as an archive,
        // because the remote serves `.filez` objects.
        return Ok(RemoteConfig::default());
    };
    let text = String::from_utf8(bytes)
        .map_err(|_| Error::InvalidFormat("the remote config is not valid utf-8".into()))?;
    let config = RepoConfig::parse(&text)?;
    if config.mode().is_archive() {
        return Ok(RemoteConfig {
            collection_id: config.collection_id().map(str::to_owned),
            indexed_deltas: matches!(
                config.keyfile().get_bool("core", "indexed-deltas"),
                Ok(Some(true))
            ),
        });
    }
    Err(Error::Unsupported(format!(
        "can't pull from a remote in mode {}: an http pull reads an archive \
         repository, whose content objects are served in the framed, deflated \
         form a client can store",
        config.mode().as_mode_str()
    )))
}

/// Returns the targets of each ref that `summary` lists and `keep` keeps: the
/// targets of a [`MIRROR`](PullFlags::MIRROR) pull of every ref, or of the
/// key `pull-branches`.
///
/// A ref of field 0 is the target `@ID:NAME` if `summary_id` is `ID`, and
/// else the target `NAME`. A ref of the entry of `ID` in
/// `ostree.summary.collection-map` is the target `@ID:NAME`. `keep` gets the
/// ref of each target. If the summary lists one target two times, the first
/// ref counts. The caller checks that no two targets write one ref.
///
/// # Errors
///
/// - [`Error::InvalidFormat`] if the collection map is malformed.
/// - [`Error::InvalidRefspec`] if a target that `keep` keeps fails the rule
///   of [`Ref::validate`].
fn summary_targets(
    summary: &Summary,
    summary_id: Option<&str>,
    keep: impl Fn(&Ref) -> bool,
) -> Result<Vec<(String, Checksum)>> {
    let mut refs = Vec::with_capacity(summary.refs.len());
    for entry in &summary.refs {
        let r = match summary_id {
            Some(id) => Ref::collection(id, entry.name.as_str()),
            None => Ref::local(entry.name.as_str()),
        };
        if keep(&r) {
            refs.push((r, entry.commit));
        }
    }
    for (id, entries) in summary.collection_map()? {
        for entry in entries {
            let r = Ref::collection(id.as_str(), entry.name);
            if keep(&r) {
                refs.push((r, entry.commit));
            }
        }
    }
    // A target becomes a ref that this pull writes. The pull checks it
    // against the rule of the ref store here, before the first object
    // request. Without this check, the first check comes when the
    // transaction resolves the ref at publication.
    let mut seen = HashSet::new();
    let mut out = Vec::with_capacity(refs.len());
    for (r, commit) in refs {
        r.validate()?;
        let text = r.to_string();
        if seen.insert(text.clone()) {
            out.push((text, commit));
        }
    }
    Ok(out)
}

/// Returns the commit of the ref `name` of the collection `id` on the remote,
/// or `None` if the remote names no such commit.
///
/// The ref of the collection that the `ostree.summary.collection-id` of
/// `summary` states is in field 0 of the summary. The ref of each other
/// collection is in the entry of `id` of `ostree.summary.collection-map`. If
/// the summary does not list the ref, or the remote serves no summary, the
/// call reads the ref file of the remote: `refs/heads/<name>` if the
/// collection id of the remote is `id`, else `refs/mirrors/<id>/<name>`. The
/// collection id of the remote is `remote_id`, the `[core] collection-id` of
/// the remote, or `summary_id` if `remote_id` is `None`.
///
/// `summary_id` is the `ostree.summary.collection-id` of `summary`, or `None`
/// if the summary states none.
///
/// `listed` holds the refs of each collection whose entry of the collection
/// map an earlier call parsed, by collection id and then by name. The call
/// parses the entry of `id` only if `listed` does not hold `id`, and then
/// adds it. If the entry holds a name two times, the first ref counts.
///
/// # Errors
///
/// - [`Error::InvalidFormat`] if the collection map of the summary is
///   malformed.
/// - The errors of [`fetch_remote_ref`].
async fn remote_collection_ref(
    summary: Option<&Summary>,
    summary_id: Option<&str>,
    listed: &mut HashMap<String, HashMap<String, Checksum>>,
    remote_id: Option<&str>,
    id: &str,
    name: &str,
    source: &RemoteSource,
) -> Result<Option<Checksum>> {
    if let Some(summary) = summary {
        let commit = if summary_id == Some(id) {
            summary.lookup(name)
        } else {
            let refs = match listed.get(id) {
                Some(refs) => refs,
                None => {
                    let mut refs = HashMap::new();
                    for entry in collection_map_refs(&summary.metadata, id)? {
                        refs.entry(entry.name).or_insert(entry.commit);
                    }
                    listed.entry(id.to_owned()).or_insert(refs)
                }
            };
            refs.get(name).copied()
        };
        if commit.is_some() {
            return Ok(commit);
        }
    }
    if remote_id.or(summary_id) == Some(id) {
        fetch_remote_ref(source, HEADS_DIR, name).await
    } else {
        fetch_remote_ref(source, &format!("{MIRRORS_DIR}/{id}"), name).await
    }
}

/// Returns the commit that the ref file `<dir>/<name>` of the remote names,
/// or `None` if the remote serves no such ref.
async fn fetch_remote_ref(
    source: &RemoteSource,
    dir: &str,
    name: &str,
) -> Result<Option<Checksum>> {
    let path = source.ref_path(dir, name);
    let Some(bytes) = source
        .read_optional(&path, Priority::High, MAX_REF_FILE)
        .await?
    else {
        return Ok(None);
    };
    let text = std::str::from_utf8(&bytes)
        .map_err(|_| Error::InvalidFormat(format!("the remote ref {name} is not valid utf-8")))?;
    Ok(Some(Checksum::from_hex(text.trim())?))
}

/// Returns the request path of the remote ref `name` in the ref directory
/// `dir`: `dir`, a `/`, and the percent-encoded name.
///
/// A request path goes on the wire as written, so this function encodes the
/// name. It encodes each byte outside the unreserved set of RFC 3986: the
/// ASCII letters and digits, `-`, `.`, `_`, and `~`. It keeps `/`, which
/// separates the components of the name and of the path.
///
/// A `?`, `#`, or `%` in a name is so part of the ref name. The server cannot
/// read it as a query, a fragment, or an escape that decodes into a different
/// name.
pub(super) fn ref_request_path(dir: &str, name: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut out = format!("{dir}/");
    for byte in name.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
                out.push(char::from(byte));
            }
            other => {
                out.push('%');
                out.push(char::from(HEX[usize::from(other >> 4)]));
                out.push(char::from(HEX[usize::from(other & 0x0f)]));
            }
        }
    }
    out
}

/// Fetches a path whole, or returns `None` if the remote answers 404.
pub(crate) async fn fetch_optional(
    fetcher: &Fetcher,
    path: &str,
    priority: Priority,
    max_size: u64,
) -> Result<Option<Vec<u8>>> {
    match fetch_whole(fetcher, path, priority, max_size).await {
        Ok(bytes) => Ok(Some(bytes)),
        Err(Error::HttpStatus { status: 404, .. }) => Ok(None),
        Err(e) => Err(e),
    }
}

/// Fetches a path whole, under a size cap.
///
/// The fetcher refuses a declared `Content-Length` above the cap before it
/// reads the body. It stops a body that passes the cap when the bytes arrive.
/// Each fetch in flight has one buffer, so the cap of the caller bounds the
/// memory of one step:
///
/// - [`MAX_METADATA_SIZE`] for a metadata object
/// - [`MAX_ROOT_FILE`] for a repository-root file
/// - [`MAX_REF_FILE`] for a ref file
///
/// The size of the buffer comes from the declared length, which the fetcher
/// held to the cap. The body so goes into one allocation of its own size, and
/// the resident peak is the cap. Each read goes into a chunk of at most
/// 128 KiB, and the function appends the chunk to the buffer.
///
/// No read touches the rest of the buffer, also if the body arrives slowly and
/// a read waits many times. The final read, which finds the end of the stream,
/// goes into the chunk, so a buffer filled to its declared length does not
/// grow. If the remote declares no length, the buffer grows as the function
/// reads, under the same cap.
///
/// If a body fails in transit, the function fetches it again from the start,
/// into a new buffer. It does so while the retry count of the fetcher has a
/// repeat left.
async fn fetch_whole(
    fetcher: &Fetcher,
    path: &str,
    priority: Priority,
    max_size: u64,
) -> Result<Vec<u8>> {
    let mut refetch = fetcher.refetching(FetchRequest {
        priority,
        max_size: Some(max_size),
        ..FetchRequest::path(path)
    });
    loop {
        let Fetched::Body(body) = refetch.fetch().await? else {
            return Err(Error::Fetch(format!(
                "{path}: the remote answered 304 to an unconditional request"
            )));
        };
        let declared = body.content_length();
        match read_whole(body, declared, max_size).await {
            Ok(out) => return Ok(out),
            Err(e) => refetch.retry(Error::from(e)).await?,
        }
    }
}

/// Reads `body` to its end into one buffer. The size of the buffer comes from
/// `declared`, the declared length, which the source held to `max_size`. Each
/// read goes into a bounded chunk, also the read that finds the end of the
/// body. So a buffer filled to its declared length does not grow.
pub(super) async fn read_whole<R: AsyncRead + Unpin>(
    mut body: R,
    declared: Option<u64>,
    max_size: u64,
) -> std::io::Result<Vec<u8>> {
    let declared = usize::try_from(declared.unwrap_or(0).min(max_size)).unwrap_or(0);
    let mut out = Vec::with_capacity(declared);
    let mut chunk = vec![0u8; declared.saturating_add(1).clamp(4096, IO_CHUNK)];
    loop {
        let n = body.read(&mut chunk).await?;
        if n == 0 {
            return Ok(out);
        }
        out.extend_from_slice(&chunk[..n]);
    }
}

/// Reads the archive framing off the front of the stream of a content object.
///
/// The framing is a four-byte big-endian header length, four zero bytes, and
/// then the header. The rest of the stream is the raw-DEFLATE payload.
///
/// The function also returns the size that the header declares for the
/// payload. This size bounds the decompressed payload. The function also
/// returns the raw framed bytes: the length prefix and the header variant, as
/// the remote sent them. A caller can store these bytes as they are, with no
/// new serialization of the parsed header.
///
/// The remote states the header length and supplies the bytes after it. So the
/// function refuses a length above [`MAX_FILE_HEADER_SIZE`] before it
/// allocates the buffer. That bound holds for each fetch in flight, because
/// each content object has one header.
pub(crate) async fn read_archive_header<R: AsyncRead + Unpin>(
    mut stream: R,
) -> Result<(FileHeader, u64, Vec<u8>, R)> {
    let mut prefix = [0u8; 8];
    stream.read_exact(&mut prefix).await?;
    if prefix[4..] != [0u8; 4] {
        return Err(Error::InvalidFormat(
            "content framing padding is not zero".into(),
        ));
    }
    let header_len =
        u32::from_be_bytes(prefix[..4].try_into().expect("four bytes of a length")) as u64;
    if header_len > MAX_FILE_HEADER_SIZE {
        return Err(Error::InvalidFormat(
            "content header exceeds the size cap".into(),
        ));
    }
    let mut bytes = vec![0u8; header_len as usize];
    stream.read_exact(&mut bytes).await?;
    let (header, uncompressed) = FileHeader::parse_archive(&bytes)?;
    let mut framed = prefix.to_vec();
    framed.extend_from_slice(&bytes);
    Ok((header, uncompressed, framed, stream))
}

/// Stores one content object in the archive wire form, from the stream after
/// its framed header.
///
/// `header` and `declared` come from [`read_archive_header`], and
/// `framed_header` is the framing that it read. `meta` is the logical metadata
/// of `header`, which the caller checked against the destination mode.
///
/// A symlink carries no payload, so its stream must end after the header. An
/// archive destination stores the compressed bytes as they arrive. Each other
/// mode inflates them into a content writer. Both sides of the payload are
/// held to `declared`.
///
/// On each of the three paths, the function reads the stream to its end
/// before it stores the object. Each destination refuses a payload that
/// inflates to fewer bytes than `declared`.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn store_filez_payload<R: AsyncRead + Unpin>(
    txn: &Transaction,
    expected: &Checksum,
    header: &FileHeader,
    meta: &FileMeta,
    declared: u64,
    framed_header: &[u8],
    mut body: R,
    read_buf: &mut Vec<u8>,
) -> Result<()> {
    if header.is_symlink() {
        check_stream_end(expected, "symlink header", &mut body).await?;
        txn.write_symlink(&header.symlink_target, meta, Some(expected))
            .await?;
        return Ok(());
    }
    // The declared size bounds both sides of the payload: the decompressed
    // size, and the bytes that come off the connection to produce it.
    let source = BoundedInput::new(body, *expected, compressed_bound(declared));
    if txn.repo().mode().is_archive() {
        // The remote stores this object deflated, in the wire form that this
        // destination writes. So the fetched bytes go to disk as they are,
        // with no inflate and no new compression.
        txn.write_archive_payload(expected, header, framed_header, declared, source, read_buf)
            .await
            .map_err(payload_refusal)?;
        return Ok(());
    }
    let mut writer = txn.content_writer(Some(expected), meta).await?;
    let mut payload = DeflateDecoder::new(BufSource::new(source));
    let short = copy_bounded(&mut payload, &mut writer, read_buf, expected, declared)
        .await
        .map_err(payload_refusal)?;
    if short != 0 {
        return Err(Error::InvalidFormat(format!(
            "content object {expected}: the payload inflates to {} byte(s), not the \
             {declared} its header declares",
            declared - short
        )));
    }
    // The decoder stops at the DEFLATE end-of-stream marker and asks its
    // input for no more bytes. So the function must read the stream to its
    // end here. That read returns the connection to the pool for the next
    // object, and moves a stream session to its next reply. It comes before
    // the finish of the writer, so the next reply arrives while this object
    // is stored.
    check_stream_end(expected, "deflated payload", payload.into_inner())
        .await
        .map_err(payload_refusal)?;
    writer.finish().await?;
    Ok(())
}

/// Streams the payload of a content object into `writer`, and stops if the
/// payload grows past the size that its header declared. Returns the number of
/// declared bytes that the payload did not hold.
///
/// A correct object decompresses to exactly `declared`. A stream that passes
/// it is corrupt or built to expand, so the rest of it has no value. The
/// checksum of the object covers the declared size only at the comparison at
/// the end of the payload. This bound limits the bytes written before that
/// comparison.
///
/// Each read is clamped to the bytes left plus the one byte that decides the
/// result. So at most one byte past the declaration is stored before the
/// refusal.
///
/// `buf` is the read buffer of the slot. It grows to [`READ_CHUNK`] on its
/// first use, and each later object of that slot uses it again.
///
/// [`BoundedInput`], under the decoder, bounds the compressed side of the same
/// declaration.
async fn copy_bounded<R, W>(
    mut reader: R,
    writer: &mut W,
    buf: &mut Vec<u8>,
    expected: &Checksum,
    declared: u64,
) -> Result<u64>
where
    R: AsyncRead + Unpin,
    W: futures_io::AsyncWrite + Unpin,
{
    if buf.len() < READ_CHUNK {
        buf.resize(READ_CHUNK, 0);
    }
    let mut left = declared;
    loop {
        let window = buf.len().min(
            usize::try_from(left)
                .unwrap_or(usize::MAX)
                .saturating_add(1),
        );
        let n = reader.read(&mut buf[..window]).await?;
        if n == 0 {
            return Ok(left);
        }
        if n as u64 > left {
            return Err(Error::InvalidFormat(format!(
                "content object {expected}: the payload outgrew the {declared} \
                 byte(s) its header declares"
            )));
        }
        left -= n as u64;
        writer.write_all(&buf[..n]).await?;
    }
}

/// Returns the number of bytes that a payload of `declared` uncompressed bytes
/// can take off the connection.
///
/// A DEFLATE compressor uses a stored block for data that it cannot shrink:
/// five bytes of framing for each 65535 bytes of input. That is one part in
/// thirteen thousand, and one part in 1024 covers it with a margin. The fixed
/// 64 KiB covers a small object, whose framing is larger than its content. A
/// stream past this bound is not a compressed form of the declared size,
/// whatever it decompresses to.
pub(crate) fn compressed_bound(declared: u64) -> u64 {
    declared
        .saturating_add(declared / 1024)
        .saturating_add(64 * 1024)
}

/// The compressed stream of a content object, bounded by the size that its
/// header declares.
///
/// [`copy_bounded`] bounds the decompressed payload. That bound does not limit
/// the compressed bytes that produce it. An empty non-final DEFLATE block is
/// five bytes that decompress to nothing. A stream of these blocks
/// decompresses to nothing for as long as the remote sends it.
///
/// Memory and disk then stay bounded, and time and bandwidth do not. The
/// decoder does not return to its caller while its input gives bytes. So the
/// bound on that input must be in the read of the decoder, which is this read.
///
/// The refusal is an [`Error::InvalidFormat`] in the `io::Error` that the
/// decoder passes up. [`payload_refusal`] takes it back out. The bound comes
/// from the declaration of the object, so the refusal names the object, as the
/// refusal of the decompressed size does.
pub(crate) struct BoundedInput<R> {
    inner: R,
    /// The object of the bound.
    checksum: Checksum,
    bound: u64,
    /// The bytes taken from `inner`. This count passes the bound by at most the
    /// one read that trips it.
    taken: u64,
}

impl<R> BoundedInput<R> {
    pub(crate) fn new(inner: R, checksum: Checksum, bound: u64) -> BoundedInput<R> {
        BoundedInput {
            inner,
            checksum,
            bound,
            taken: 0,
        }
    }
}

impl<R: AsyncRead + Unpin> AsyncRead for BoundedInput<R> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<std::io::Result<usize>> {
        let me = self.get_mut();
        let n = ready!(Pin::new(&mut me.inner).poll_read(cx, buf))?;
        me.taken += n as u64;
        if me.taken > me.bound {
            return Poll::Ready(Err(std::io::Error::other(Error::InvalidFormat(format!(
                "content object {}: the compressed payload passed the {} byte(s) \
                 its declared size allows",
                me.checksum, me.bound
            )))));
        }
        Poll::Ready(Ok(n))
    }
}

/// Takes back the refusal that a bounded read reported.
///
/// The decoder returns the failure of its input as its own failure. So a
/// refusal of [`BoundedInput`] arrives here in an `io::Error`. The unwrap gives
/// that refusal the same form as a refusal of [`copy_bounded`]. Any other error
/// stays as it is.
pub(crate) fn payload_refusal(error: Error) -> Error {
    match error {
        Error::Io(io) => io.downcast::<Error>().unwrap_or_else(Error::Io),
        other => other,
    }
}

/// Checks that the stream of a content object ends after `after`, and reads to
/// that end.
///
/// One byte decides it. The remote sends the framing that selects the check of
/// the caller. If bytes follow, the remote chose their length, and a read of
/// all of them holds all of them. If the object ends at the correct point,
/// this read reaches the end of its response. The read then returns the
/// connection to the pool for the next object.
///
/// The stream of the payload is the input buffer of the decoder. It gives back
/// the read-ahead that the decoder left before it asks the body for more
/// bytes. A correct object leaves none: nothing follows its final DEFLATE
/// block.
pub(crate) async fn check_stream_end<R: AsyncRead + Unpin>(
    expected: &Checksum,
    after: &str,
    mut stream: R,
) -> Result<()> {
    let mut byte = [0u8; 1];
    if stream.read(&mut byte).await? != 0 {
        return Err(Error::InvalidFormat(format!(
            "content object {expected}: bytes follow the {after}"
        )));
    }
    Ok(())
}

/// A compile-time check that the future of a pull is `Send`: from a remote,
/// through a session of the caller, and from a local repository.
const _: fn() = || {
    fn assert_send<T: Send>(_: &T) {}
    let _ = |repo: &Repo| assert_send(&repo.pull("origin", PullOptions::default()));
    let _ = |repo: &Repo| assert_send(&repo.pull_with_report("origin", PullOptions::default()));
    let _ = |repo: &Repo, session: PullSession| {
        assert_send(&repo.pull_with_session(
            session,
            PullTrust::unverified(),
            PullOptions::default(),
        ))
    };
    let _ = |repo: &Repo, src: &Repo| assert_send(&repo.pull_local(src, PullOptions::default()));
    let _ = |repo: &Repo, src: &Repo| {
        assert_send(&repo.pull_local_with_report(src, PullOptions::default()))
    };
};

/// The in-process byte pipe of the integration tests, for the unit tests of a
/// pull through a stream session.
#[cfg(test)]
#[path = "../../tests/common/pipe.rs"]
mod test_pipe;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Ref;
    use async_compression::futures::bufread::DeflateEncoder;
    use futures_lite::io::Cursor;
    use ostrya_core::Xattrs;
    use ostrya_rt::block_on;
    use std::pin::Pin;
    use std::task::{Context, Poll};

    /// Returns the archive stored form of a content object: the framed header,
    /// then the payload that the caller supplies.
    fn framed(header: &FileHeader, uncompressed: u64, payload: &[u8]) -> Vec<u8> {
        let bytes = header.serialize_archive(uncompressed).unwrap();
        let mut out = Vec::new();
        out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
        out.extend_from_slice(&[0u8; 4]);
        out.extend_from_slice(&bytes);
        out.extend_from_slice(payload);
        out
    }

    fn regular_header() -> FileHeader {
        FileHeader {
            uid: 0,
            gid: 0,
            mode: 0o100644,
            symlink_target: String::new(),
            xattrs: Xattrs::default(),
        }
    }

    /// The header comes off the front of the stream, and the rest is the
    /// payload, which goes to the decoder.
    #[test]
    fn the_header_is_read_off_the_front_and_the_payload_is_left() {
        block_on(async {
            let stored = framed(&regular_header(), 4, b"payload bytes");
            let (header, declared, raw, mut rest) =
                read_archive_header(Cursor::new(stored.clone()))
                    .await
                    .unwrap();
            assert_eq!(header, regular_header());
            assert_eq!(declared, 4);
            assert_eq!(raw, stored[..stored.len() - b"payload bytes".len()]);
            let mut payload = Vec::new();
            rest.read_to_end(&mut payload).await.unwrap();
            assert_eq!(payload, b"payload bytes");
        });
    }

    /// The header of a symlink names its target, and its stored form carries no
    /// payload.
    #[test]
    fn a_symlink_header_names_its_target() {
        block_on(async {
            let header = FileHeader {
                uid: 0,
                gid: 0,
                mode: 0o120777,
                symlink_target: "hello.txt".to_owned(),
                xattrs: Xattrs::default(),
            };
            let stored = framed(&header, 0, b"");
            let (parsed, _declared, _raw, mut rest) =
                read_archive_header(Cursor::new(stored)).await.unwrap();
            assert!(parsed.is_symlink());
            assert_eq!(parsed.symlink_target, "hello.txt");
            let mut payload = Vec::new();
            rest.read_to_end(&mut payload).await.unwrap();
            assert!(payload.is_empty());
        });
    }

    /// The four bytes after the length are padding and must be zero. Other
    /// bytes are not the framing that this reader reads.
    #[test]
    fn nonzero_framing_padding_is_rejected() {
        block_on(async {
            let mut stored = framed(&regular_header(), 0, b"");
            stored[5] = 1;
            let err = read_archive_header(Cursor::new(stored)).await.unwrap_err();
            assert!(err.to_string().contains("padding"), "{err}");
        });
    }

    /// A stream that ends inside the framing is a truncated object, and the
    /// read fails.
    #[test]
    fn a_truncated_stream_fails_rather_than_ending() {
        block_on(async {
            let stored = framed(&regular_header(), 0, b"");
            for cut in [4, 8, stored.len() - 1] {
                let err = read_archive_header(Cursor::new(stored[..cut].to_vec()))
                    .await
                    .unwrap_err();
                assert!(matches!(err, Error::Io(_)), "cut at {cut}: {err}");
            }
        });
    }

    /// A stream that never ends. Past a small budget it fails. So a check that
    /// reads to an end fails this test, and the process does not run out of
    /// memory.
    struct Endless {
        handed_out: usize,
    }

    impl AsyncRead for Endless {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<std::io::Result<usize>> {
            if self.handed_out >= 4096 {
                return Poll::Ready(Err(std::io::Error::other("the check read past the header")));
            }
            buf.fill(0);
            self.handed_out += buf.len();
            Poll::Ready(Ok(buf.len()))
        }
    }

    /// A symlink whose stored form carries a payload is refused. The refusal
    /// reads one byte of the payload, and holds none of the length that the
    /// remote chose to send.
    #[test]
    fn a_symlink_payload_is_refused_without_reading_it() {
        block_on(async {
            let mut stream = Endless { handed_out: 0 };
            let err = check_stream_end(&csum(1), "symlink header", &mut stream)
                .await
                .unwrap_err();
            assert!(err.to_string().contains("bytes follow"), "{err}");
            assert_eq!(stream.handed_out, 1);
        });
    }

    /// The decoder stops at the end of the DEFLATE stream and does not read the
    /// bytes after it. So the end-of-stream check runs over the input buffer of
    /// the decoder. A payload that ends the stream passes the check, and the
    /// check refuses trailing bytes that the decoder did not consume.
    #[test]
    fn the_check_sees_what_the_decoder_left_behind() {
        block_on(async {
            let mut encoder = DeflateEncoder::new(Cursor::new(b"hello ostree\n".to_vec()));
            let mut compressed = Vec::new();
            encoder.read_to_end(&mut compressed).await.unwrap();

            for (trailing, expect_end) in [(&b""[..], true), (b"junk", false)] {
                let mut stored = compressed.clone();
                stored.extend_from_slice(trailing);
                let mut decoder = DeflateDecoder::new(BufSource::new(Cursor::new(stored)));
                let mut out = Vec::new();
                copy_bounded(&mut decoder, &mut out, &mut Vec::new(), &csum(1), 13)
                    .await
                    .unwrap();
                assert_eq!(out, b"hello ostree\n");
                let result =
                    check_stream_end(&csum(1), "deflated payload", decoder.into_inner()).await;
                assert_eq!(
                    result.is_ok(),
                    expect_end,
                    "trailing {trailing:?}: {result:?}"
                );
            }
        });
    }

    /// A payload that decompresses past the size that its header declares is
    /// refused. The refusal reads one byte past the declaration, and no more of
    /// a stream that never ends.
    #[test]
    fn a_payload_outgrowing_its_declared_size_is_refused() {
        block_on(async {
            let mut stream = Endless { handed_out: 0 };
            let mut out = Vec::new();
            let err = copy_bounded(&mut stream, &mut out, &mut Vec::new(), &csum(1), 4)
                .await
                .unwrap_err();
            assert!(err.to_string().contains("outgrew the 4 byte"), "{err}");
            assert_eq!(stream.handed_out, 5);
        });
    }

    /// A stream of empty non-final DEFLATE blocks: five bytes that decompress
    /// to nothing, repeated. Past a budget well above the bound under test it
    /// fails. So an unbounded compressed stream fails this test, and the
    /// process does not run out of memory.
    struct EmptyBlocks {
        handed_out: usize,
    }

    impl AsyncRead for EmptyBlocks {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<std::io::Result<usize>> {
            const BLOCK: [u8; 5] = [0x00, 0x00, 0x00, 0xff, 0xff];
            if self.handed_out >= 1024 * 1024 {
                return Poll::Ready(Err(std::io::Error::other(
                    "the payload read past its compressed bound",
                )));
            }
            let base = self.handed_out;
            for (i, byte) in buf.iter_mut().enumerate() {
                *byte = BLOCK[(base + i) % BLOCK.len()];
            }
            self.handed_out += buf.len();
            Poll::Ready(Ok(buf.len()))
        }
    }

    /// A payload that decompresses to nothing for as long as it is sent is
    /// refused against the bound that its declared size sets. The decompressed
    /// bound never trips against it. The refusal reaches the caller as the
    /// refusal that it is. The stream delivered the bound plus the one read
    /// that tripped it.
    #[test]
    fn a_compressed_payload_passing_its_bound_is_refused() {
        block_on(async {
            let mut source = EmptyBlocks { handed_out: 0 };
            let mut out = Vec::new();
            let bound = compressed_bound(13);
            let err = {
                let source = BoundedInput::new(&mut source, csum(1), bound);
                let mut payload = DeflateDecoder::new(BufSource::new(source));
                copy_bounded(&mut payload, &mut out, &mut Vec::new(), &csum(1), 13)
                    .await
                    .unwrap_err()
            };
            let err = payload_refusal(err);
            assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
            assert!(
                err.to_string()
                    .contains(&format!("passed the {bound} byte")),
                "{err}"
            );
            assert!(out.is_empty());
            assert!(
                source.handed_out <= bound as usize + 16 * 1024,
                "{} bytes taken for a {bound}-byte bound",
                source.handed_out
            );
        });
    }

    /// The bound refuses no object of the size that it is stated for. Data that
    /// a compressor cannot shrink is the worst case, and its compressed form is
    /// inside the bound that its uncompressed size sets.
    #[test]
    fn the_compressed_bound_holds_incompressible_data() {
        block_on(async {
            // A linear congruential sequence, which DEFLATE cannot shrink.
            let mut state = 1u32;
            let data: Vec<u8> = (0..200_000)
                .map(|_| {
                    state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                    (state >> 24) as u8
                })
                .collect();
            let mut encoder = DeflateEncoder::new(Cursor::new(data.clone()));
            let mut compressed = Vec::new();
            encoder.read_to_end(&mut compressed).await.unwrap();
            let declared = data.len() as u64;
            let bound = compressed_bound(declared);
            assert!(
                compressed.len() as u64 <= bound,
                "{} compressed bytes for a {bound}-byte bound",
                compressed.len()
            );

            let source = BoundedInput::new(Cursor::new(compressed), csum(1), bound);
            let mut payload = DeflateDecoder::new(BufSource::new(source));
            let mut out = Vec::new();
            copy_bounded(&mut payload, &mut out, &mut Vec::new(), &csum(1), declared)
                .await
                .unwrap();
            assert_eq!(out, data);
        });
    }

    /// The declaration is a ceiling. A payload that reaches it is stored
    /// whole, and the checksum comparison decides a shorter one.
    #[test]
    fn a_payload_within_its_declared_size_is_stored() {
        block_on(async {
            // One buffer serves both objects, as the buffer of a slot does.
            let mut buf = Vec::new();
            for payload in [&b"four"[..], b"two"] {
                let mut out = Vec::new();
                copy_bounded(
                    Cursor::new(payload.to_vec()),
                    &mut out,
                    &mut buf,
                    &csum(1),
                    4,
                )
                .await
                .unwrap();
                assert_eq!(out, payload);
            }
            // The second object reads through the buffer that the first object
            // grew, and that buffer is the read chunk of the slot.
            assert_eq!(buf.len(), READ_CHUNK);
        });
    }

    /// A declared header length past the header cap is refused before the
    /// buffer is allocated. So a remote controls at most that cap for each
    /// fetch in flight. The test refuses the first byte past the cap and the
    /// largest length that the four-byte field holds.
    #[test]
    fn an_oversized_header_length_is_refused() {
        block_on(async {
            for header_len in [MAX_FILE_HEADER_SIZE as u32 + 1, u32::MAX] {
                let mut stored = Vec::new();
                stored.extend_from_slice(&header_len.to_be_bytes());
                stored.extend_from_slice(&[0u8; 4]);
                let err = read_archive_header(Cursor::new(stored)).await.unwrap_err();
                assert!(err.to_string().contains("size cap"), "{header_len}: {err}");
            }
        });
    }

    /// A ref name goes on the wire encoded. Its `/` separators stay, and each
    /// character that names something else in a URL is encoded.
    #[test]
    fn a_ref_request_path_encodes_the_name() {
        let heads = |name| ref_request_path("refs/heads", name);
        assert_eq!(heads("test/main"), "refs/heads/test/main");
        // The unreserved set passes through as itself.
        assert_eq!(heads("a-b.c_d~e"), "refs/heads/a-b.c_d~e");
        // A query, a fragment, and an escape name the ref, not a request target.
        assert_eq!(heads("a?b"), "refs/heads/a%3Fb");
        assert_eq!(heads("a#b"), "refs/heads/a%23b");
        assert_eq!(heads("a%2fb"), "refs/heads/a%252fb");
        // A space and a CRLF are bytes of the name.
        assert_eq!(heads("a b\r\n"), "refs/heads/a%20b%0D%0A");
        // A non-ASCII name is encoded as its UTF-8 bytes.
        assert_eq!(heads("é"), "refs/heads/%C3%A9");
        // The directory of a collection ref stays as given.
        assert_eq!(
            ref_request_path("refs/mirrors/org.example.Os", "a b"),
            "refs/mirrors/org.example.Os/a%20b"
        );
    }

    // --- the plan ---------------------------------------------------------

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

    fn object(byte: u8, ty: ObjectType) -> ObjectName {
        ObjectName::new(csum(byte), ty)
    }

    /// Returns the outcome of a fetched commit that holds `tree`.
    fn fetched(checksum: Checksum, tree: Vec<ObjectName>, parent: Option<Checksum>) -> Step {
        Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Scan(tree),
            parent,
            attachments: Vec::new(),
            marked: true,
        })
    }

    /// Returns the outcome of a commit that a delta delivers.
    fn by_delta(
        checksum: Checksum,
        parts: usize,
        fallbacks: Vec<ObjectName>,
        tree: Vec<ObjectName>,
    ) -> Step {
        delta_outcome(checksum, parts, fallbacks, tree, false)
    }

    /// Returns the outcome of a commit that the delta of an attachment
    /// delivers. A load step loads the job of the delta.
    fn by_attachment_delta(checksum: Checksum, parts: usize, tree: Vec<ObjectName>) -> Step {
        delta_outcome(checksum, parts, Vec::new(), tree, true)
    }

    /// Returns the outcome of a commit that a delta delivers, with `lazy` as
    /// the load rule of its job.
    fn delta_outcome(
        checksum: Checksum,
        parts: usize,
        fallbacks: Vec<ObjectName>,
        tree: Vec<ObjectName>,
        lazy: bool,
    ) -> Step {
        Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Delta {
                parts,
                fallbacks,
                tree,
                lazy,
            },
            parent: None,
            attachments: Vec::new(),
            marked: true,
        })
    }

    /// Drains the plan: applies a stored outcome for each queued object. The
    /// dirtrees reference no more objects.
    fn drain(plan: &mut Plan, marked: &mut Vec<Checksum>) {
        while let Some(item) = plan.next() {
            let step = match item {
                Item::Object(name) if name.ty == ObjectType::DirTree => {
                    Step::DirTree(name.checksum, DirTree::default())
                }
                Item::Object(_) => Step::Done,
                Item::Load(commit) => Step::Loaded(commit),
                Item::Part(part) => Step::Part(part.commit),
                Item::Commit(_) => panic!("the test queues no further commits"),
            };
            plan.apply(step, marked);
        }
    }

    /// A commit queues the objects that it references, and reports that this
    /// pull marked it partial.
    #[test]
    fn a_commit_queues_the_objects_it_references() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.push_commit(CommitItem {
            checksum: csum(1),
            depth: 0,
            optional: false,
        });
        assert!(matches!(plan.next(), Some(Item::Commit(_))));
        plan.apply(
            fetched(
                csum(1),
                vec![
                    object(2, ObjectType::DirMeta),
                    object(3, ObjectType::DirTree),
                ],
                None,
            ),
            &mut marked,
        );
        assert_eq!(plan.scan.len(), 2);
        drain(&mut plan, &mut marked);
        assert!(plan.next().is_none());
        assert_eq!(marked, [csum(1)]);
    }

    /// An object that several commits reach is queued once. This holds if the
    /// other commits reach it while it is queued, and after it is fetched.
    #[test]
    fn an_object_several_commits_reach_is_queued_once() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let shared = object(9, ObjectType::DirMeta);
        for byte in [1u8, 2] {
            plan.apply(fetched(csum(byte), vec![shared], None), &mut marked);
        }
        assert_eq!(plan.scan.len(), 1);
        drain(&mut plan, &mut marked);
        plan.apply(fetched(csum(3), vec![shared], None), &mut marked);
        assert!(plan.next().is_none());
    }

    /// A commit reached again with more depth is not fetched again: the walk
    /// resumes at the parent that it named.
    #[test]
    fn a_commit_reached_deeper_resumes_at_its_parent() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let tip = CommitItem {
            checksum: csum(1),
            depth: 0,
            optional: false,
        };
        plan.push_commit(tip);
        assert!(matches!(plan.next(), Some(Item::Commit(_))));
        // Its parent is recorded, but depth 0 followed none of it.
        plan.apply(fetched(csum(1), Vec::new(), Some(csum(2))), &mut marked);
        assert!(plan.next().is_none());

        // A second ref reaches the same commit with one parent to follow.
        plan.push_commit(CommitItem {
            checksum: csum(1),
            depth: 1,
            optional: false,
        });
        let Some(Item::Commit(next)) = plan.next() else {
            panic!("the parent was not queued");
        };
        assert_eq!(next.checksum, csum(2));
        assert_eq!(next.depth, 0);
        assert!(next.optional);
        assert!(plan.next().is_none());
    }

    /// The drain order is the fetch order of the pull: the commits, then the
    /// objects that the scan waits for, then the content.
    #[test]
    fn the_plan_drains_commits_then_scan_then_content() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(
            fetched(
                csum(1),
                vec![
                    object(4, ObjectType::File),
                    object(2, ObjectType::DirMeta),
                    object(3, ObjectType::DirTree),
                ],
                None,
            ),
            &mut marked,
        );
        plan.push_commit(CommitItem {
            checksum: csum(5),
            depth: 0,
            optional: false,
        });
        let mut drained = Vec::new();
        while let Some(item) = plan.next() {
            drained.push(match item {
                Item::Commit(commit) => commit.checksum,
                Item::Object(name) => name.checksum,
                Item::Load(commit) => commit,
                Item::Part(part) => part.commit,
            });
        }
        assert_eq!(drained, [csum(5), csum(2), csum(3), csum(4)]);
    }

    /// A delta queues its parts and the objects that it hands over loose. The
    /// tree walk of the commit waits for the last part.
    #[test]
    fn a_delta_queues_its_parts_before_the_tree() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let fallback = object(7, ObjectType::File);
        let tree = vec![
            object(2, ObjectType::DirMeta),
            object(3, ObjectType::DirTree),
        ];
        plan.apply(by_delta(csum(1), 2, vec![fallback], tree), &mut marked);

        // The parts come before the fallback, which is content.
        assert!(matches!(plan.next(), Some(Item::Part(_))));
        assert!(matches!(plan.next(), Some(Item::Part(_))));
        let Some(Item::Object(name)) = plan.next() else {
            panic!("the fallback was not queued");
        };
        assert_eq!(name, fallback);
        // The tree is not queued while a part is outstanding.
        assert!(plan.next().is_none());

        plan.apply(Step::Part(csum(1)), &mut marked);
        assert!(plan.next().is_none());
        plan.apply(Step::Part(csum(1)), &mut marked);
        let Some(Item::Object(name)) = plan.next() else {
            panic!("the tree was not queued after the last part");
        };
        assert_eq!(name, object(2, ObjectType::DirMeta));
    }

    /// The plan gives out no more than [`PART_CAP`] parts at once, whatever the
    /// number of parts of the delta and of slots of the pull.
    #[test]
    fn the_part_cap_holds_however_many_parts_a_delta_has() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(by_delta(csum(1), 5, Vec::new(), Vec::new()), &mut marked);

        let mut in_flight = 0;
        let mut high_water = 0;
        let mut applied = 0;
        loop {
            while let Some(item) = plan.next() {
                assert!(matches!(item, Item::Part(_)));
                in_flight += 1;
                high_water = high_water.max(in_flight);
            }
            if in_flight == 0 {
                break;
            }
            plan.apply(Step::Part(csum(1)), &mut marked);
            in_flight -= 1;
            applied += 1;
        }
        assert_eq!(high_water, PART_CAP);
        assert_eq!(applied, 5);
    }

    /// The delta of an attachment queues a load step and no part. The parts
    /// follow the load. After the last part the plan counts the job as
    /// loaded no longer, and queues the tree.
    #[test]
    fn the_load_of_an_attachment_job_comes_before_its_parts() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let tree = vec![object(2, ObjectType::DirMeta)];
        plan.apply(by_attachment_delta(csum(1), 2, tree), &mut marked);

        assert!(matches!(plan.next(), Some(Item::Load(commit)) if commit == csum(1)));
        assert!(plan.loaded.contains(&csum(1)));
        // No part and no tree before the job is loaded.
        assert!(plan.next().is_none());

        plan.apply(Step::Loaded(csum(1)), &mut marked);
        assert!(matches!(plan.next(), Some(Item::Part(_))));
        assert!(matches!(plan.next(), Some(Item::Part(_))));
        assert!(plan.next().is_none());

        plan.apply(Step::Part(csum(1)), &mut marked);
        assert!(plan.loaded.contains(&csum(1)));
        assert!(plan.delta_parts.contains_key(&csum(1)));
        assert!(plan.next().is_none());
        plan.apply(Step::Part(csum(1)), &mut marked);
        assert!(plan.loaded.is_empty());
        assert!(!plan.delta_parts.contains_key(&csum(1)));
        let Some(Item::Object(name)) = plan.next() else {
            panic!("the tree was not queued after the last part");
        };
        assert_eq!(name, object(2, ObjectType::DirMeta));
    }

    /// A run of more attachments than [`PART_CAP`] holds at most
    /// [`PART_CAP`] parsed jobs at once. The test runs the plan as the drive
    /// loop does, with the steps in flight applied in order, and reads the
    /// jobs of the deltas from the record file. Each job goes after its last
    /// part.
    #[test]
    fn an_attachment_run_holds_at_most_part_cap_jobs() {
        block_on(async {
            let dir = ScratchDir::new("dependency-jobs");
            let archive = || crate::CreateOptions::new(RepoMode::Archive);
            let src = Repo::create(&dir.0.join("src"), archive()).await.unwrap();
            let dest = Repo::create(&dir.0.join("dest"), archive()).await.unwrap();
            let mut deltas = Vec::new();
            for name in ["d1", "d2", "d3", "d4", "d5"] {
                let commit = commit_under(&src, name, name.as_bytes()).await;
                src.generate_static_delta(None, &commit, &crate::DeltaOptions::default())
                    .await
                    .unwrap();
                deltas.push((None, commit));
            }
            assert!(deltas.len() > PART_CAP);
            let found = AttachmentDeltas::kept_from(&dest, &src, &deltas).await;
            let run = RunDeltas::Lazy(&found);

            let mut plan = Plan::default();
            let mut marked = Vec::new();
            for (_, commit) in &deltas {
                let bytes = run.commit_bytes(commit).await.unwrap().unwrap();
                assert_eq!(Checksum::sha256(&bytes), *commit);
                assert!(found.holds_commit_data(commit));
                let next = run.commit_next(commit, Vec::new());
                let CommitNext::Delta {
                    parts, lazy: true, ..
                } = next
                else {
                    panic!("the attachment has no delta");
                };
                assert!(parts > 0);
                // The head keeps the number of parts and the range of the
                // superblock for the load step, and no commit data.
                assert!(run.commit_bytes(commit).await.unwrap().is_none());
                assert!(!found.holds_commit_data(commit));
                assert!(found.has_head(commit));
                plan.apply(by_attachment_delta(*commit, parts, Vec::new()), &mut marked);
            }

            let mut in_flight = VecDeque::new();
            let mut high_water = 0;
            let mut loads = 0;
            loop {
                while let Some(item) = plan.next() {
                    in_flight.push_back(match item {
                        Item::Load(commit) => {
                            found.load_job(&dest, &commit).await.unwrap();
                            loads += 1;
                            Step::Loaded(commit)
                        }
                        Item::Part(part) => {
                            assert!(found.live_job(&part.commit).is_some());
                            Step::Part(part.commit)
                        }
                        Item::Object(_) => Step::Done,
                        Item::Commit(_) => panic!("the test queues no further commits"),
                    });
                    high_water = high_water.max(found.live_jobs());
                    assert!(found.live_jobs() <= PART_CAP);
                }
                let Some(step) = in_flight.pop_front() else {
                    break;
                };
                let part = match step {
                    Step::Part(commit) => Some(commit),
                    _ => None,
                };
                plan.apply(step, &mut marked);
                if let Some(commit) = part
                    && !plan.delta_parts.contains_key(&commit)
                {
                    run.release(&commit);
                    assert!(found.live_job(&commit).is_none());
                }
            }
            assert_eq!(loads, deltas.len());
            assert_eq!(high_water, PART_CAP);
            assert_eq!(found.live_jobs(), 0);
            assert!(found.is_empty());
        });
    }

    /// The head of the delta of an attachment goes in the step of a commit
    /// that needs no delta: a commit that is complete here, a commit-only
    /// pull, or a commit that an earlier run made complete. No load follows,
    /// so the head goes with no job.
    #[test]
    fn a_commit_that_needs_no_delta_releases_the_attachment_head() {
        block_on(async {
            let dir = ScratchDir::new("dependency-head-release");
            let archive = || crate::CreateOptions::new(RepoMode::Archive);
            let src = Repo::create(&dir.0.join("src"), archive()).await.unwrap();
            let dest = Repo::create(&dir.0.join("dest"), archive()).await.unwrap();
            let commit = commit_under(&src, "d1", b"d1").await;
            src.generate_static_delta(None, &commit, &crate::DeltaOptions::default())
                .await
                .unwrap();
            let found = AttachmentDeltas::kept_from(&dest, &src, &[(None, commit)]).await;
            assert!(found.holds_commit_data(&commit));

            RunDeltas::Lazy(&found).release(&commit);
            assert!(!found.has_head(&commit));
            assert_eq!(found.live_jobs(), 0);
            assert!(found.is_empty());
        });
    }

    /// The progress total counts the parts of the delta of an attachment at
    /// the step of its commit, before the load step queues them. The total
    /// is the total of a delta whose parts the plan queues at once, and it
    /// does not change at the load.
    #[test]
    fn the_progress_total_counts_the_parts_of_a_job_before_its_load() {
        let total = |progress: &PullCounters| {
            progress
                .own
                .objects_total
                .load(std::sync::atomic::Ordering::Relaxed)
        };
        let tree = || vec![object(2, ObjectType::DirMeta)];
        let mut marked = Vec::new();

        let eager_progress = PullCounters::new(None);
        let mut eager = Plan::default();
        eager.apply(by_delta(csum(1), 3, Vec::new(), tree()), &mut marked);
        eager.report(&eager_progress, 1, false);

        let lazy_progress = PullCounters::new(None);
        let mut lazy = Plan::default();
        lazy.apply(by_attachment_delta(csum(1), 3, tree()), &mut marked);
        lazy.report(&lazy_progress, 1, false);
        assert_eq!(total(&lazy_progress), total(&eager_progress));
        assert_eq!(total(&lazy_progress), 1 + 3);

        // The load step is in flight, and is no unit of work.
        assert!(matches!(lazy.next(), Some(Item::Load(_))));
        lazy.report(&lazy_progress, 1, false);
        assert_eq!(total(&lazy_progress), 1 + 3);
        lazy.apply(Step::Loaded(csum(1)), &mut marked);
        lazy.report(&lazy_progress, 1, false);
        assert_eq!(total(&lazy_progress), 1 + 3);
        assert_eq!(lazy.waiting_parts, 0);
    }

    /// A stream that checks, at its end, that the transaction did not stage the
    /// object yet.
    struct EndBeforeStore<'a> {
        inner: Cursor<Vec<u8>>,
        txn: &'a Transaction,
        checksum: Checksum,
        ended: bool,
    }

    impl AsyncRead for EndBeforeStore<'_> {
        fn poll_read(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<std::io::Result<usize>> {
            let me = self.get_mut();
            let n = ready!(Pin::new(&mut me.inner).poll_read(cx, buf))?;
            if n == 0 && !buf.is_empty() {
                assert!(
                    !me.txn.is_staged(&me.checksum, ObjectType::File),
                    "the object was stored before its stream ended"
                );
                me.ended = true;
            }
            Poll::Ready(Ok(n))
        }
    }

    /// Each destination reads the end of the stream of a content object before
    /// it stores the object. So a stream session moves to its next reply while
    /// the store finishes. The test covers the regular-file path of an archive
    /// and of a bare-user destination, and the symlink path.
    #[test]
    fn the_stream_ends_before_the_object_is_stored() {
        let dir =
            std::env::temp_dir().join(format!("ostrya-pull-stream-end-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let payload = b"payload of a regular file".to_vec();
        let symlink = FileHeader {
            symlink_target: "target".to_owned(),
            mode: 0o120777,
            ..regular_header()
        };
        block_on(async {
            for (mode, header) in [
                (RepoMode::Archive, regular_header()),
                (RepoMode::BareUser, regular_header()),
                (RepoMode::BareUser, symlink.clone()),
            ] {
                let root = dir.join(format!("{}-{}", mode.as_mode_str(), header.is_symlink()));
                let repo = Repo::create(&root, crate::CreateOptions::new(mode))
                    .await
                    .unwrap();
                let txn = repo.transaction().await.unwrap();
                let body = if header.is_symlink() {
                    Vec::new()
                } else {
                    payload.clone()
                };
                let mut hasher = ostrya_core::ContentHasher::new(&header).unwrap();
                hasher.update(&body);
                let checksum = hasher.finish();
                let mut deflated = Vec::new();
                if !header.is_symlink() {
                    DeflateEncoder::new(&body[..])
                        .read_to_end(&mut deflated)
                        .await
                        .unwrap();
                }
                let stored = framed(&header, body.len() as u64, &deflated);
                let (parsed, declared, framed_header, rest) =
                    read_archive_header(Cursor::new(stored)).await.unwrap();
                let FileHeader {
                    uid,
                    gid,
                    mode: file_mode,
                    xattrs,
                    ..
                } = parsed.clone();
                let meta = FileMeta {
                    uid,
                    gid,
                    mode: file_mode,
                    xattrs,
                };
                let mut stream = EndBeforeStore {
                    inner: rest,
                    txn: &txn,
                    checksum,
                    ended: false,
                };
                store_filez_payload(
                    &txn,
                    &checksum,
                    &parsed,
                    &meta,
                    declared,
                    &framed_header,
                    &mut stream,
                    &mut Vec::new(),
                )
                .await
                .unwrap();
                assert!(stream.ended, "{mode:?}: the stream was not read to its end");
                assert!(txn.is_staged(&checksum, ObjectType::File), "{mode:?}");
            }
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Pops the next item, which must be the dirtree `byte`.
    fn pop_dirtree(plan: &mut Plan, byte: u8) {
        loop {
            match plan.next() {
                Some(Item::Object(name)) if name.ty == ObjectType::DirMeta => continue,
                Some(Item::Object(name)) => {
                    assert_eq!(name, object(byte, ObjectType::DirTree));
                    return;
                }
                _ => panic!("dirtree {byte} was not queued"),
            }
        }
    }

    /// A dirtree reached at two subpath positions gets a walk under both, also
    /// if the second position reaches it after its first walk. The plan queues
    /// it again, and the second walk fetches what the first walk left out.
    #[test]
    fn a_dirtree_reached_again_under_a_wider_scope_is_walked_again() {
        let values = ["/p/x/".to_owned(), "/q/x".to_owned()];
        let mut plan = Plan::new(Subpaths::parse(&values).unwrap());
        let mut marked = Vec::new();
        // The root (1) holds `p` (10) and `q` (11), and both hold `x`, the one
        // dirtree 20, which holds the file 30.
        let root = DirTree {
            files: Vec::new(),
            dirs: vec![
                ("p".into(), csum(10), csum(2)),
                ("q".into(), csum(11), csum(2)),
            ],
        };
        let parent = DirTree {
            files: Vec::new(),
            dirs: vec![("x".into(), csum(20), csum(2))],
        };
        let x = DirTree {
            files: vec![("f".into(), csum(30))],
            dirs: Vec::new(),
        };
        plan.apply(
            fetched(
                csum(1),
                vec![
                    object(2, ObjectType::DirMeta),
                    object(1, ObjectType::DirTree),
                ],
                None,
            ),
            &mut marked,
        );
        pop_dirtree(&mut plan, 1);
        plan.apply(Step::DirTree(csum(1), root), &mut marked);
        pop_dirtree(&mut plan, 10);
        pop_dirtree(&mut plan, 11);
        plan.apply(Step::DirTree(csum(10), parent.clone()), &mut marked);
        // The walk of `x` is under `/p/x/` alone, which fetches nothing in it.
        pop_dirtree(&mut plan, 20);
        plan.apply(Step::DirTree(csum(20), x.clone()), &mut marked);
        assert!(plan.content.is_empty());
        // `/q/x` reaches it again and names it whole.
        plan.apply(Step::DirTree(csum(11), parent), &mut marked);
        pop_dirtree(&mut plan, 20);
        plan.apply(Step::DirTree(csum(20), x.clone()), &mut marked);
        assert_eq!(
            plan.content.iter().copied().collect::<Vec<_>>(),
            [object(30, ObjectType::File)]
        );
        // The scope covers a third reach, so the plan queues nothing again.
        plan.push_object(object(20, ObjectType::DirTree), Scope::All);
        assert!(plan.scan.is_empty());
    }

    /// A delta whose objects all went to fallbacks has no part to wait for. So
    /// the plan queues its tree walk at once.
    #[test]
    fn a_delta_with_no_parts_queues_its_tree_at_once() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(
            by_delta(
                csum(1),
                0,
                vec![object(7, ObjectType::File)],
                vec![object(2, ObjectType::DirMeta)],
            ),
            &mut marked,
        );
        assert_eq!(plan.scan.len(), 1);
        assert_eq!(plan.content.len(), 1);
        assert!(plan.parts.is_empty());
    }

    /// Returns the outcome of a fetched commit with no tree to fetch, which
    /// names the commit `att` of each `(name, att)` as an attachment.
    fn naming(checksum: Checksum, parent: Option<Checksum>, atts: &[(&str, u8)]) -> Step {
        Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Nothing,
            parent,
            attachments: atts
                .iter()
                .map(|(name, byte)| ((*name).to_owned(), csum(*byte)))
                .collect(),
            marked: true,
        })
    }

    /// Returns the next queued commit item.
    fn next_commit(plan: &mut Plan) -> CommitItem {
        match plan.next() {
            Some(Item::Commit(item)) => item,
            _ => panic!("the plan gave no commit"),
        }
    }

    /// Returns the commit, the field, and the reason of an
    /// [`Error::InvalidRelations`].
    fn invalid_relations(err: Error) -> (Option<Checksum>, String) {
        match err {
            Error::InvalidRelations {
                commit,
                field: crate::related::RelationField::Attachments,
                reason,
            } => (commit, reason),
            other => panic!("expected InvalidRelations in field 2, got {other:?}"),
        }
    }

    /// An attachment is recorded and not queued, also under a commit that the
    /// plan follows to its full depth. The parent is queued.
    #[test]
    fn an_attachment_is_recorded_and_not_queued() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.push_commit(CommitItem {
            checksum: csum(1),
            depth: -1,
            optional: false,
        });
        next_commit(&mut plan);
        plan.apply(
            naming(csum(1), Some(csum(2)), &[("boot/uki", 3)]),
            &mut marked,
        );
        let parent = next_commit(&mut plan);
        assert_eq!((parent.checksum, parent.depth), (csum(2), -1));
        assert!(parent.optional);
        assert!(plan.next().is_none());
        assert_eq!(marked, [csum(1)]);
        assert_eq!(
            plan.attachments.inner.named(&csum(3)),
            Some((csum(1), "boot/uki"))
        );
        assert_eq!(
            plan.attachments.inner.naming().get(&csum(1)),
            Some(&vec![("boot/uki".to_owned(), csum(3))])
        );
    }

    /// An attachment that two commits of one level name keeps the commit
    /// with the lower checksum and its first entry, in either order of the
    /// two steps. A commit of a lower level stays over a commit of a later
    /// level. The plan records the entries of each commit.
    #[test]
    fn an_attachment_two_commits_name_keeps_the_lowest_commit() {
        for order in [[1, 2], [2, 1]] {
            let mut plan = Plan::default();
            let mut marked = Vec::new();
            for byte in order {
                let entries: &[(&str, u8)] = if byte == 1 {
                    &[("a/x", 3), ("a/y", 3)]
                } else {
                    &[("b/x", 3)]
                };
                plan.apply(naming(csum(byte), None, entries), &mut marked);
            }
            assert!(plan.next().is_none());
            assert_eq!(
                plan.attachments.inner.named(&csum(3)),
                Some((csum(1), "a/x")),
                "{order:?}"
            );
            assert_eq!(plan.attachments.inner.order(), [csum(3)]);
            assert_eq!(plan.attachments.inner.naming().len(), 2);
            plan.apply(naming(csum(3), None, &[]), &mut marked);
            assert_eq!(plan.parents.get(&csum(3)), Some(&None));
        }

        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(naming(csum(2), None, &[("b/x", 3)]), &mut marked);
        plan.attachments.level += 1;
        plan.apply(naming(csum(1), None, &[("a/x", 3)]), &mut marked);
        assert_eq!(
            plan.attachments.inner.named(&csum(3)),
            Some((csum(2), "b/x"))
        );
    }

    /// An attachment that names attachments of its own is recorded, in
    /// either order of the two steps. Its attachments follow the attachments
    /// of the earlier commits in the order of the record, and keep the
    /// attachment as the commit that names them.
    #[test]
    fn a_nested_attachment_is_recorded_in_either_order() {
        // The commit that names the attachment comes first.
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(naming(csum(1), None, &[("lib/b", 2)]), &mut marked);
        plan.apply(naming(csum(2), None, &[("lib/c", 3)]), &mut marked);
        assert_eq!(marked, [csum(1), csum(2)]);
        assert_eq!(plan.attachments.inner.order(), [csum(2), csum(3)]);
        assert_eq!(
            plan.attachments.inner.named(&csum(2)),
            Some((csum(1), "lib/b"))
        );
        assert_eq!(
            plan.attachments.inner.named(&csum(3)),
            Some((csum(2), "lib/c"))
        );

        // The attachment comes first.
        let mut plan = Plan::default();
        plan.apply(naming(csum(2), None, &[("lib/c", 3)]), &mut marked);
        plan.apply(naming(csum(1), None, &[("lib/b", 2)]), &mut marked);
        assert_eq!(plan.attachments.inner.order(), [csum(3), csum(2)]);
        assert_eq!(
            plan.attachments.inner.named(&csum(3)),
            Some((csum(2), "lib/c"))
        );
        assert!(plan.next().is_none());
    }

    /// A parent that no source holds fails the pull at the end of the run if
    /// a commit names it as an attachment, in each order of the steps. The
    /// error names the commit with the lower checksum of the two that name
    /// the attachment.
    #[test]
    fn an_absent_parent_that_is_an_attachment_fails_in_each_order() {
        let unheld = format!(
            "attachment lib/b names commit {}, which neither a source nor this repository holds",
            csum(2)
        );
        let steps = || {
            [
                naming(csum(1), None, &[("lib/b", 2)]),
                naming(csum(4), None, &[("lib/x", 2)]),
                Step::Absent(csum(2)),
            ]
        };
        for order in [
            [0, 1, 2],
            [0, 2, 1],
            [1, 0, 2],
            [1, 2, 0],
            [2, 0, 1],
            [2, 1, 0],
        ] {
            let mut marked = Vec::new();
            let mut plan = Plan::default();
            let mut steps = steps().map(Some);
            for at in order {
                plan.apply(steps[at].take().unwrap(), &mut marked);
            }
            let err = plan.check_attachments().unwrap_err();
            assert_eq!(
                invalid_relations(err),
                (Some(csum(1)), unheld.clone()),
                "{order:?}"
            );
        }

        // An absent parent that no commit names ends its chain.
        let mut marked = Vec::new();
        let mut plan = Plan::default();
        plan.apply(Step::Absent(csum(2)), &mut marked);
        plan.apply(naming(csum(1), None, &[("lib/b", 3)]), &mut marked);
        plan.check_attachments().unwrap();
        assert!(plan.attachments.inner.named(&csum(3)).is_some());
        assert!(!plan.parents.contains_key(&csum(2)));
    }

    /// A scratch directory, removed on drop.
    struct ScratchDir(std::path::PathBuf);

    impl ScratchDir {
        fn new(tag: &str) -> ScratchDir {
            use std::sync::atomic::{AtomicU64, Ordering};
            static COUNTER: AtomicU64 = AtomicU64::new(0);
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir = std::env::temp_dir()
                .join(format!("ostrya-pull-jobs-{}-{tag}-{n}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            ScratchDir(dir)
        }
    }

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

    /// The time that a test waits for the end of a held job.
    const JOB_END: std::time::Duration = std::time::Duration::from_secs(120);

    /// Writes a commit whose tree holds the file `f` with `content` under the
    /// ref `name`, and returns it.
    async fn commit_under(repo: &Repo, name: &str, 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, &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: None,
            subject: None,
            body: None,
            timestamp: Some(1_700_000_000),
            metadata: None,
            attachments: Vec::new(),
        };
        let commit = txn.write_commit(options, &root).await.unwrap();
        txn.set_ref(&Ref::local(name), Some(&commit));
        txn.commit().await.unwrap();
        commit
    }

    /// A source repository with the ref `left` at the commit `left` and the
    /// ref `right` at the commit `right`, and an empty destination.
    struct TwoRefs {
        dir: ScratchDir,
        src: Repo,
        dest: Repo,
        left: Checksum,
        right: Checksum,
    }

    async fn two_refs(tag: &str) -> TwoRefs {
        let dir = ScratchDir::new(tag);
        let archive = || crate::CreateOptions::new(RepoMode::Archive);
        let src = Repo::create(&dir.0.join("src"), archive()).await.unwrap();
        let dest = Repo::create(&dir.0.join("dest"), archive()).await.unwrap();
        let left = commit_under(&src, "left", b"left content").await;
        let right = commit_under(&src, "right", b"right content").await;
        TwoRefs {
            dir,
            src,
            dest,
            left,
            right,
        }
    }

    /// Pulls the refs `left` and `right` from `src` into `dest` through a
    /// stream session, with `Repo::send` as the server of `src`.
    async fn pull_both_refs(src: &Repo, dest: &Repo) -> Result<PullStats> {
        let opts = PullOptions {
            refs: vec!["left".to_owned(), "right".to_owned()],
            ..PullOptions::default()
        };
        pull_over_stream(src, dest, opts).await
    }

    /// Pulls from `src` into `dest` with `opts` through a stream session,
    /// with `Repo::send` as the server of `src`.
    async fn pull_over_stream(src: &Repo, dest: &Repo, opts: PullOptions) -> Result<PullStats> {
        let (to_server, server_in) = test_pipe::pipe(64 * 1024);
        let (server_out, from_server) = test_pipe::pipe(64 * 1024);
        let access = crate::access::ReadAccess::new(
            Arc::new(crate::access::ClientAccess::implicit(None)),
            crate::access::AuthItem::Anonymous,
            None,
        );
        let (pulled, _) = futures_lite::future::zip(
            async {
                let session = PullSession::over_stream(
                    from_server,
                    to_server,
                    StreamSessionOptions::default(),
                )
                .await?;
                dest.pull_with_session(session, PullTrust::unverified(), opts)
                    .await
            },
            async move { src.send(server_in, server_out, &access).await },
        )
        .await;
        pulled
    }

    fn marker(repo: &Repo, commit: &Checksum) -> std::path::PathBuf {
        repo.path().join(super::super::partial_path(commit))
    }

    /// A failed pull removes the marker that the blocking job of a dropped
    /// step writes after the failure. The marker job of `left` waits until
    /// the run has failed, and the marker job of `right` fails once the job of
    /// `left` has started. Neither marker stays.
    #[test]
    fn a_failed_pull_clears_the_marker_of_a_dropped_step() {
        let fixture = block_on(two_refs("marker"));
        let dest_root = fixture.dest.path().to_path_buf();
        let held = format!("marker {}", fixture.left.to_hex());
        let finished = crate::jobs::job_gate::hold(&dest_root, held.clone());
        crate::jobs::job_gate::fail(
            &dest_root,
            format!("marker {}", fixture.right.to_hex()),
            held,
        );
        let pulled = block_on(pull_both_refs(&fixture.src, &fixture.dest));
        let err = pulled.unwrap_err();
        assert!(err.to_string().contains("injected job failure"), "{err}");
        finished.recv_timeout(JOB_END).unwrap();
        for commit in [&fixture.left, &fixture.right] {
            let path = marker(&fixture.dest, commit);
            assert!(!path.exists(), "{} stays", path.display());
        }
        drop(fixture.dir);
    }

    /// A failed pull removes its staging directory after the staging job of a
    /// dropped step ends. The job that stages the root dirtree of `left` waits
    /// until the run has failed, and it finds the staging directory in place.
    /// The marker job of `right` fails once that job has started.
    #[test]
    fn a_failed_pull_removes_the_staging_directory_after_a_dropped_step() {
        let fixture = block_on(two_refs("staging"));
        let dest_root = fixture.dest.path().to_path_buf();
        let (commit, _) = block_on(fixture.src.load_commit(&fixture.left)).unwrap();
        let held = format!("stage {}", commit.root_dirtree.to_hex());
        let finished = crate::jobs::job_gate::hold(&dest_root, held.clone());
        crate::jobs::job_gate::fail(
            &dest_root,
            format!("marker {}", fixture.right.to_hex()),
            held,
        );
        let pulled = block_on(pull_both_refs(&fixture.src, &fixture.dest));
        let err = pulled.unwrap_err();
        assert!(err.to_string().contains("injected job failure"), "{err}");
        let linked = finished.recv_timeout(JOB_END).unwrap();
        assert!(
            linked,
            "the job ran after the removal of the staging directory"
        );
        let staging: Vec<_> = std::fs::read_dir(dest_root.join("tmp"))
            .unwrap()
            .map(|entry| entry.unwrap())
            .filter(|entry| {
                entry.file_name().to_string_lossy().starts_with("staging-")
                    && entry.file_type().unwrap().is_dir()
            })
            .map(|entry| entry.file_name())
            .collect();
        assert!(staging.is_empty(), "{staging:?}");
        drop(fixture.dir);
    }

    /// Returns the path of the object `checksum` of type `ty` in the archive
    /// repository `repo`.
    fn object_file(repo: &Repo, checksum: &Checksum, ty: ObjectType) -> std::path::PathBuf {
        repo.path()
            .join("objects")
            .join(ostrya_core::loose_path(checksum, ty, RepoMode::Archive))
    }

    /// Copies the object file `from` to the object file `to`, in place of a
    /// file at `to`.
    fn put_object_file(from: &std::path::Path, to: &std::path::Path) {
        let _ = std::fs::remove_file(to);
        std::fs::create_dir_all(to.parent().unwrap()).unwrap();
        std::fs::copy(from, to).unwrap();
    }

    /// The pull hashes the commit bytes that the checks read from a
    /// localcache repository, and stages these bytes. The cache holds the
    /// bytes of `right` under the name of `left`, and the right bytes after
    /// the read. The pull fails with [`Error::ChecksumMismatch`], and does
    /// not store `left`.
    #[test]
    fn a_localcache_commit_that_changes_after_the_checks_fails_the_pull() {
        let fixture = block_on(two_refs("cache-commit"));
        let cache = block_on(Repo::create(
            &fixture.dir.0.join("cache"),
            crate::CreateOptions::new(RepoMode::Archive),
        ))
        .unwrap();
        let commit =
            |repo: &Repo, checksum: &Checksum| object_file(repo, checksum, ObjectType::Commit);
        let cached = commit(&cache, &fixture.left);
        put_object_file(&commit(&fixture.src, &fixture.right), &cached);
        let good = commit(&fixture.src, &fixture.left);
        let dest_root = fixture.dest.path().to_path_buf();
        super::super::import_seam::arm(&dest_root, move || put_object_file(&good, &cached));
        let opts = PullOptions {
            refs: vec!["left".to_owned()],
            localcache_repos: vec![cache],
            ..PullOptions::default()
        };
        let pulled = block_on(pull_over_stream(&fixture.src, &fixture.dest, opts));
        let armed = super::super::import_seam::disarm(&dest_root);
        assert!(!armed, "the pull did not read the cache");
        match pulled {
            Err(Error::ChecksumMismatch { expected, actual }) => {
                assert_eq!((expected, actual), (fixture.left, fixture.right));
            }
            other => panic!("{other:?}"),
        }
        let stored = block_on(fixture.dest.has_object(ObjectType::Commit, &fixture.left));
        assert!(!stored.unwrap(), "the pull stored the commit");
        drop(fixture.dir);
    }

    /// The walk reads a dirtree of a localcache repository from the bytes that
    /// the pull hashed and staged. The cache holds the root dirtree of `left`,
    /// and the root dirtree of `right` under its name after the read. The
    /// pull stores the file of `left` and not the file of `right`.
    #[test]
    fn the_walk_reads_the_localcache_dirtree_that_the_pull_staged() {
        let fixture = block_on(two_refs("cache-dirtree"));
        let cache = block_on(Repo::create(
            &fixture.dir.0.join("cache"),
            crate::CreateOptions::new(RepoMode::Archive),
        ))
        .unwrap();
        let root = |commit: &Checksum| {
            let (commit, _) = block_on(fixture.src.load_commit(commit)).unwrap();
            commit.root_dirtree
        };
        let (left_root, right_root) = (root(&fixture.left), root(&fixture.right));
        let dirtree =
            |repo: &Repo, checksum: &Checksum| object_file(repo, checksum, ObjectType::DirTree);
        let cached = dirtree(&cache, &left_root);
        put_object_file(&dirtree(&fixture.src, &left_root), &cached);
        let other = dirtree(&fixture.src, &right_root);
        let dest_root = fixture.dest.path().to_path_buf();
        super::super::import_seam::arm(&dest_root, move || put_object_file(&other, &cached));
        let opts = PullOptions {
            refs: vec!["left".to_owned()],
            localcache_repos: vec![cache],
            ..PullOptions::default()
        };
        let pulled = block_on(pull_over_stream(&fixture.src, &fixture.dest, opts));
        let armed = super::super::import_seam::disarm(&dest_root);
        assert!(!armed, "the pull did not read the cache");
        pulled.unwrap();
        let file = |root: &Checksum| block_on(fixture.src.load_dirtree(root)).unwrap().files[0].1;
        let (left_file, right_file) = (file(&left_root), file(&right_root));
        let held = |checksum: &Checksum| {
            block_on(fixture.dest.has_object(ObjectType::File, checksum)).unwrap()
        };
        assert!(held(&left_file), "the pull did not store the file of left");
        assert!(!held(&right_file), "the pull stored the file of right");
        drop(fixture.dir);
    }
}