ostrya 0.19.1

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
//! The pull of the refs of one collection from the remotes that serve it.
//!
//! [`Repo::pull_collection`] is the entry point and states the rules. The
//! pull runs in three parts:
//!
//! 1. The checks of the options, and the endpoint, the trust, and the
//!    transport of each remote. A failure stops the pull before its first
//!    request.
//! 2. The find step: the probe of each remote, in the given order. The probe
//!    reads the commit and the timestamp of each ref, from the ref listing or
//!    from the summary. The probe of a remote at a `file://` address reads
//!    the ref files of the local repository, or its summary. For each commit
//!    operand, the probe asks the remote for the commit object, until one
//!    remote serves it. With commit operands alone, the probe reads no ref.
//!    The probe skips each listed ref whose name fails the ref-name rule. The
//!    find step gives the refs, the names of the skipped refs, and the
//!    session of each remote that answers, and the error of each other
//!    remote. If the probe of a remote read the refs from its `summary`, the
//!    find step also gives these bytes. The pull from that remote reads them
//!    in place of the `summary` and the `summary.sig`. The probe of a local
//!    repository gives no summary. The pull skips a remote that fails. It
//!    reports each skipped remote and each skipped ref through its event
//!    callback.
//! 3. The selection of a remote for each ref and for each commit operand,
//!    and then one pull from each selected remote, in the given order,
//!    through the engine of [`Repo::pull`], over the session of its probe. A
//!    local repository goes through the engine of [`Repo::pull_local`].
//!
//! [`Repo::remote_list_collection_refs_with`] makes the checks of part 1 and
//! the find step of part 2 for its one remote. The error of that remote is
//! the error of the call. The call returns the name and the commit of each
//! ref that the find step read, and drops the timestamps. Its event callback
//! gets the name of each ref that the probe skipped.

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Instant;

use ostrya_core::{Checksum, Commit, ObjectType, Ref, RefSelector, Value, is_valid_collection_id};

use crate::config::repo;
use crate::endpoint::{EndpointOverrides, Origin, resolve_origin};
use crate::error::{Error, Result};
use crate::fetch::{Fetcher, Priority};
use crate::object::MAX_METADATA_SIZE;
use crate::refs::{check_ref_path, is_ref_path};
use crate::related::RelatedRule;
use crate::remote::proto::{MAX_REF_ENTRY_LEN, MAX_REF_ENTRY_PARTS, MAX_REF_PATTERNS};
#[cfg(feature = "s3")]
use crate::remote::s3::{Bucket, S3Endpoint};
use crate::remote::{Endpoint, PullSession, StreamSession, StreamSessionOptions};
use crate::repo::Repo;
use crate::send::write_escaped;
use crate::summary::{
    COMMIT_TIMESTAMP_KEY, SUMMARY_FILE, Summary, SummaryRef, collection_map_refs, parse_ref_list,
    summary_collection_id,
};
use crate::verify::PullTrust;
use crate::verify::trust::FieldGroup;

#[cfg(feature = "s3")]
use super::http::s3_fetcher;
use super::http::{Wanted, connect, object_path, open_local_blocking, session_options};
use super::source::{Connection, RemoteSource};
use super::subpath::Subpaths;
use super::verify::Verification;
use super::{
    LocalWanted, Operand, Pinned, PullFlags, PullOptions, PullReport, PullStats, PullVerify,
    RefChange, RefPlace, check_commit_operands, check_depth, check_hash, check_one_place,
    read_checked_local_summary,
};

/// The path of the ref listing under the base URL of a remote.
const LISTING_PATH: &str = "_ostrya/refs/v1";

/// The longest request target of a ref listing that the HTTP client sends:
/// 16 KiB, from the path of the listing to the end of the query.
///
/// [`PullSession::fetch_refs`] refuses a longer target before it sends the
/// request.
const MAX_LISTING_TARGET: usize = 16 * 1024;

/// The most bytes that the pairs of the names of one HTTP listing request
/// fill, each pair with the `&` before it ([`name_cost`]).
///
/// The target is the path, `?`, and the pairs with no `&` before the first
/// pair. So the target fits when the sum of the costs is at most this value.
const LISTING_BUDGET: usize = MAX_LISTING_TARGET - LISTING_PATH.len();

/// The options of [`Repo::pull_collection`].
///
/// The struct is `#[non_exhaustive]`, so a caller starts from
/// [`CollectionPullOptions::default`] and sets the fields.
#[derive(Default)]
#[non_exhaustive]
pub struct CollectionPullOptions {
    /// The options of the pull from each selected remote.
    ///
    /// [`refs`](PullOptions::refs) names the refs of the collection, and
    /// holds the commit operands. An empty list takes each ref of the
    /// collection that a remote lists. [`Repo::pull_collection`] states the
    /// fields that it refuses, and the fields that apply to each remote.
    pub pull: PullOptions,
    /// The callback for each [`CollectionPullEvent`] of the pull, or `None`.
    ///
    /// The pull gives it each remote and each listed ref that the probe
    /// skips, after the probe of the remote and before the probe of the next
    /// remote. The pull calls it on its own task, so the callback must return
    /// soon.
    /// A command writes the [`Display`](fmt::Display) text of the event as a
    /// warning on standard error. The default is `None`, which drops each
    /// event.
    pub on_event: Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
    /// `true` if a tip commit with no `ostree.collection-binding` key passes
    /// the collection-binding check.
    ///
    /// The default is `false`, and such a tip fails the pull. The switch
    /// applies only when the key is absent. A tip whose binding is not a
    /// string, or names another collection, fails with either value. The
    /// switch does not change the `ostree.ref-binding` check, the check of
    /// the listed timestamp, or the timestamp check. The switch applies to
    /// the commit of a commit operand as to a tip.
    ///
    /// Apart from the ref binding, the pull does not check a commit against
    /// the name of its ref. So a remote can serve, for a name, any commit with
    /// no binding of either kind. The trust of the remote and a check of the
    /// content by the caller after the pull are the protection.
    pub allow_unbound: bool,
}

/// The debug text shows a callback that is set as `<callback>`.
impl fmt::Debug for CollectionPullOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CollectionPullOptions")
            .field("pull", &self.pull)
            .field("on_event", &self.on_event.as_ref().map(|_| "<callback>"))
            .field("allow_unbound", &self.allow_unbound)
            .finish()
    }
}

/// An event of [`Repo::pull_collection`], which
/// [`CollectionPullOptions::on_event`] receives, or of
/// [`Repo::remote_list_collection_refs_with`], which its parameter `on_event`
/// receives.
///
/// [`Display`](fmt::Display) writes one line. It writes each ASCII control
/// character as an escape sequence, for example `\n`, so the line holds no
/// line break.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CollectionPullEvent {
    /// The pull skipped a remote, because the remote failed to tell the
    /// commits of the refs.
    ///
    /// The pull selects no ref from this remote. The causes are a failed
    /// connection or request, a listing or a summary that does not parse, a
    /// listed ref with no valid timestamp, a summary that the policy of the
    /// remote refuses, and a bucket repository with no summary. For a commit
    /// operand, the causes are a request for the commit object that fails
    /// for another cause than an absent object, and a commit object that
    /// does not hash to its name or does not parse. For a remote at a
    /// `file://` address, the causes also include a path with no repository,
    /// and a directory or a ref file of the selection that cannot be read.
    /// Without a summary policy, they also include a ref whose commit the
    /// repository does not hold. The message then names the path. Under a
    /// summary policy, the probe reads no commit of a listed ref, and a
    /// listed commit that the repository does not hold fails the pull from
    /// it, as for a remote.
    #[non_exhaustive]
    RemoteSkipped {
        /// The name of the remote.
        remote: String,
        /// The text of the failure.
        message: String,
    },
    /// The probe of a remote skipped a ref that the remote lists, because
    /// the name of the ref fails the ref-name rule. An example is
    /// `origin:main`.
    ///
    /// The other refs of the remote stay in the selection. The probe reads
    /// no commit and no timestamp of a skipped ref. A name that the caller
    /// gives passes the ref-name rule before the first request, so the probe
    /// skips a ref only when the caller gives no name.
    #[non_exhaustive]
    RefSkipped {
        /// The name of the remote.
        remote: String,
        /// The name of the ref, as the remote lists it.
        name: String,
    },
}

impl fmt::Display for CollectionPullEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CollectionPullEvent::RemoteSkipped { remote, message } => {
                f.write_str("remote ")?;
                write_escaped(f, remote)?;
                f.write_str(" skipped: ")?;
                write_escaped(f, message)
            }
            CollectionPullEvent::RefSkipped { remote, name } => {
                f.write_str("remote ")?;
                write_escaped(f, remote)?;
                f.write_str(" skipped the ref ")?;
                write_escaped(f, name)?;
                f.write_str(": the name fails the ref-name rule")
            }
        }
    }
}

/// The result of [`Repo::pull_collection`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionPullStats {
    /// Each pulled ref, with the remote that the pull selected for it.
    ///
    /// The order is the order of [`refs`](PullOptions::refs), or the
    /// byte-wise order of the names for a pull of each ref of the
    /// collection. A `REF@CHECKSUM` operand gives an entry for `REF`. A
    /// `CHECKSUM` operand gives no entry.
    pub refs: Vec<CollectionPullRef>,
    /// The sum of the statistics of the pulls from the selected remotes.
    ///
    /// [`elapsed`](PullStats::elapsed) is the run time of the whole call. A
    /// pull from a local repository adds its import counts, and no fetch
    /// count unless it reads static deltas. [`local`](Self::local) holds the
    /// part of these counts that the pulls from local repositories gave.
    pub stats: PullStats,
    /// The part of [`stats`](Self::stats) that the pulls from local
    /// repositories (`file://` candidates) gave.
    ///
    /// [`elapsed`](PullStats::elapsed) is the sum of the run times of those
    /// pulls. Each count is zero if the pull selected no local repository.
    pub local: PullStats,
    /// Each ref that the pull changed.
    ///
    /// The list joins the lists of the pulls from the selected remotes, in
    /// the order of the candidate remotes. Each list has the rules of
    /// [`PullReport::changed_refs`]. A pull that fails returns the error and
    /// no list, also after the pull from an earlier remote wrote its refs.
    pub changed_refs: Vec<RefChange>,
}

/// One ref of a collection pull, and the remote that the pull selected for
/// it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionPullRef {
    /// The ref name.
    pub name: String,
    /// The name of the selected remote.
    pub remote: String,
    /// The commit that the selected remote listed for the ref, or the commit
    /// of a `REF@CHECKSUM` operand.
    pub commit: Checksum,
    /// The commit timestamp that the selected remote listed for the ref, in
    /// seconds since the Unix epoch. For a `REF@CHECKSUM` operand, the
    /// timestamp of the commit that the probe read from the selected remote.
    pub timestamp: u64,
}

/// A remote of a collection pull: its name, its endpoint, and its trust.
struct Candidate<'a> {
    name: &'a str,
    transport: Transport,
    trust: PullTrust,
    /// The repository of the pull. A probe reads its X.509 CRL cache, and
    /// writes nothing to it.
    repo: Repo,
}

/// How the pull reaches a remote.
enum Transport {
    /// The fetcher of an HTTP remote. The pull builds it before its first
    /// request.
    Http(Fetcher),
    /// An ssh endpoint and the options of its session. The pull checks the
    /// command line of its ssh client before its first request.
    Ssh(Box<Endpoint>, StreamSessionOptions),
    /// The signed fetcher of a bucket repository at an `s3://` address, and
    /// its endpoint, which gives the bucket client of each session. The pull
    /// builds the fetcher before its first request.
    #[cfg(feature = "s3")]
    S3(Fetcher, Box<S3Endpoint>),
    /// The path of a local repository, from a `file://` address. The pull
    /// opens the repository in the probe.
    Local(PathBuf),
}

impl Transport {
    /// Returns the transport of `endpoint`, with the request limit
    /// `max_outstanding` of the caller.
    ///
    /// For an HTTP endpoint and an S3 endpoint, the call builds the fetcher.
    /// For an ssh endpoint, it checks the command line of the ssh client. It
    /// sends no request and starts no ssh client.
    async fn new(endpoint: Endpoint, max_outstanding: Option<usize>) -> Result<Transport> {
        let (endpoint, stream) = session_options(endpoint, max_outstanding);
        Ok(match endpoint {
            Endpoint::Http(_) => {
                let PullSession::Http(fetcher) = connect(endpoint, stream).await?.session else {
                    unreachable!("an HTTP endpoint opens an HTTP session");
                };
                Transport::Http(fetcher)
            }
            Endpoint::Ssh {
                ref address,
                ref options,
            } => {
                StreamSession::check_command_line(address, options)?;
                Transport::Ssh(Box::new(endpoint), stream)
            }
            #[cfg(feature = "s3")]
            Endpoint::S3(s3) => Transport::S3(s3_fetcher(&s3, stream).await?, Box::new(s3)),
            _ => {
                return Err(crate::endpoint::neither_ssh_nor_http(
                    "a read of collection refs",
                ));
            }
        })
    }

    /// Opens a session to the remote.
    ///
    /// The connection to a bucket repository holds a bucket client over the
    /// fetcher of the session. The session of a local repository is the open
    /// repository.
    async fn open(&self) -> Result<Session> {
        match self {
            Transport::Http(fetcher) => {
                Ok(Session::Remote(PullSession::Http(fetcher.clone()).into()))
            }
            Transport::Ssh(endpoint, stream) => connect(Endpoint::clone(endpoint), stream.clone())
                .await
                .map(Session::Remote),
            #[cfg(feature = "s3")]
            Transport::S3(fetcher, s3) => Ok(Session::Remote(Connection {
                session: PullSession::Http(fetcher.clone()),
                bucket: Some(Bucket::from_fetcher(s3, fetcher.clone())),
            })),
            Transport::Local(path) => {
                let path = path.clone();
                ostrya_rt::unblock(move || open_local_blocking(path))
                    .await
                    .map(Session::Local)
            }
        }
    }
}

/// An open session to a remote of a collection pull.
enum Session {
    /// The session to a server, and its bucket client.
    Remote(Connection),
    /// The repository at the `file://` address of a local candidate.
    Local(Repo),
}

/// One ref that a remote lists for the collection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Listed {
    pub(crate) name: String,
    pub(crate) commit: Checksum,
    pub(crate) timestamp: u64,
}

/// What the probe of one remote gives if the remote answers. [`find_refs`]
/// gives a `Result<Probed>` for each candidate: this value for a candidate
/// that answers, or the error that skips the candidate.
struct Probed {
    /// The refs of the collection that the remote lists, with names that
    /// pass the ref-name rule.
    listed: Vec<Listed>,
    /// Each name of a ref of the collection that the remote lists and that
    /// fails the ref-name rule, in the listed order. The probe skipped these
    /// refs. [`report_skipped_refs`] takes the list out after the probe, so
    /// the list is empty after the find step.
    skipped: Vec<String>,
    /// The `summary` of the candidate, if the probe read the refs from it.
    /// The probe of a local candidate reads the refs from the summary under
    /// a summary policy alone.
    summary: Option<Arc<Vec<u8>>>,
    /// The dict of the `summary.sig` of `summary`, if the probe checked it.
    summary_dict: Option<Arc<Value>>,
    /// Each commit of the commit operands that the probe asked for and that
    /// the remote serves, with the timestamp of the commit.
    commits: Vec<(Checksum, u64)>,
    /// The open session to the remote, for the pull from it. `None` after
    /// the find step ended the session.
    session: Option<Session>,
}

/// The operands of a collection pull, as [`collection_names`] reads them.
#[derive(Debug, Default, PartialEq, Eq)]
struct Operands {
    /// Each operand that names a ref, in the given order. A ref name with no
    /// commit occurs one time, and a ref name with one commit occurs one
    /// time.
    refs: Vec<RefOperand>,
    /// The commit of each `CHECKSUM` operand, in the given order, each one
    /// time.
    bare: Vec<Checksum>,
}

/// An operand of a collection pull that names a ref.
#[derive(Debug, PartialEq, Eq)]
struct RefOperand {
    /// The operand as given.
    given: String,
    /// The ref name, with no `@ID:` part.
    name: String,
    /// The commit of a `REF@CHECKSUM` operand. `None` for an operand that
    /// names no commit: the pull selects the commit that a remote lists.
    commit: Option<Checksum>,
}

/// The refs of the collection that a listing, a summary, or the ref files
/// of a local repository give.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ListedRefs {
    /// Each ref whose name passes the ref-name rule.
    pub(crate) listed: Vec<Listed>,
    /// Each name that fails the ref-name rule, in the listed order. The
    /// find step skips these refs, and reads no commit and no timestamp of
    /// them.
    skipped: Vec<String>,
}

/// The remote that the pull selected for one ref.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Selected {
    /// The position of the remote in the list of candidates.
    remote: usize,
    listed: Listed,
}

/// Methods that pull the refs of a collection.
impl Repo {
    /// Pulls refs of the collection `collection_id` from the remotes
    /// `remotes`.
    ///
    /// Each name in `remotes` is a `[remote "<name>"]` section of the config
    /// of this repository. These are the candidates: remotes that serve the
    /// collection. The call does not read the `collection-id` key or the
    /// `mirrored-collection-ids` key of a remote. The `ostrya` command gives
    /// the remotes whose `collection-id` is `collection_id`, or whose
    /// `mirrored-collection-ids` holds it, in the order of the config. The
    /// order of
    /// `remotes` is the order of the probe, of the ties, and of the pulls. A
    /// name that occurs again in `remotes` adds nothing.
    ///
    /// [`refs`](PullOptions::refs) of [`CollectionPullOptions::pull`] names
    /// the refs. A name is `NAME` or `@ID:NAME`, where `ID` is
    /// `collection_id`, and both forms name the ref `NAME` of the
    /// collection. An empty list takes each ref of the collection that a
    /// remote lists. A name that occurs again adds nothing, also in the
    /// other form. A name can also be a commit operand: `CHECKSUM`,
    /// `NAME@CHECKSUM`, or `@ID:NAME@CHECKSUM`, as "Commit operands" states.
    ///
    /// # Address and trust
    ///
    /// Before its first request, the pull resolves the endpoint of each
    /// remote with [`resolve_pull`](crate::endpoint::resolve_pull), with
    /// [`overrides`](PullOptions::overrides), and the trust of each remote
    /// with [`PullTrust::from_remote`], with [`verify`](PullOptions::verify)
    /// and [`trust_group`](PullOptions::trust_group).
    /// It also builds the fetcher of each HTTP remote and of each remote at
    /// an `s3://` address, which sends no request, and checks the command
    /// line of the ssh client of each ssh remote, which starts no ssh client.
    /// So an error in the config of one remote, for example a TLS file that
    /// does not parse, an empty `send-command`, or an `s3://` remote with no
    /// key pair, stops the pull before the first request. Each pull from a
    /// remote applies the keys of that remote: `gpg-verify`, `sign-verify`,
    /// and their key sources. With `trust_group`, or with the key `trust` of
    /// the remote, the trust group supplies the commit keys.
    ///
    /// A remote whose `pull-url`, or else `url`, has the scheme `file` is a
    /// local repository, and the pull does not call
    /// [`resolve_pull`](crate::endpoint::resolve_pull) for it. "Local
    /// repository" below states the rules.
    ///
    /// # Probe
    ///
    /// The pull asks each remote in turn for the commit of each ref. It
    /// opens one session to each remote: an ssh client over ssh, the
    /// fetcher and its connections over HTTP and to an `s3://` address, or
    /// the open repository at a `file://` address. The pull from a selected
    /// remote uses the same session. The pull ends the
    /// session of each other remote after the selection, and an error of
    /// that end has no effect.
    ///
    /// - If the policy of the remote covers the summary
    ///   (`gpg-verify-summary`, `sign-verify-summary`), the pull reads the
    ///   `summary` and the `summary.sig` of the remote, and verifies the
    ///   summary before it reads the refs from it. The ref listing has no
    ///   signature, so the pull does not read it.
    /// - Otherwise, the pull reads the ref listing of the remote, through
    ///   [`PullSession::fetch_refs`](crate::remote::PullSession::fetch_refs).
    ///   The first selector holds the names, and the second selector holds
    ///   each name under the collection id, `ID/NAME`. A request holds at
    ///   most [`MAX_REF_PATTERNS`] entries, and over HTTP a request target of
    ///   at most 16 KiB. So a long list of names takes more than one request.
    /// - A pull of each ref first sends the first selector `!**`, which
    ///   selects no ref, and the second selector `ID/**`. If the listing
    ///   states `collection_id` as the collection id of the remote, a second
    ///   request sends an empty first selector, which selects each ref, and
    ///   no second selector.
    /// - If the remote serves no ref listing, the pull reads the `summary`
    ///   of the remote. An HTTP remote serves no listing when it answers the
    ///   request with a status from 400 to 499. A 403, a 404, and a 410 for
    ///   the `summary` mark it absent. A remote with no listing and no
    ///   summary lists no ref.
    /// - A remote at an `s3://` address is a bucket repository, which serves
    ///   no ref listing. The pull sends it no listing request, and reads the
    ///   refs from its `summary` alone, with the S3 client of the bucket, as
    ///   [`Repo::pull`] reads the `summary`, the `summary.sig`, and the
    ///   `config` of a bucket repository. A bucket repository with no
    ///   `summary` fails the probe. The pull takes the commit that the
    ///   summary lists, also when the ref file of the bucket names a newer
    ///   commit.
    ///
    /// If the `ostree.summary.collection-id` of the listing or of the
    /// summary is `collection_id`, the refs of the collection are in the ref
    /// list, field 0. Otherwise, they are in `ostree.summary.collection-map`
    /// under `collection_id`, and the pull ignores field 0. The commit
    /// timestamp of a ref is its `ostree.commit.timestamp`.
    ///
    /// A remote that fails the probe is skipped:
    /// [`on_event`](CollectionPullOptions::on_event) gets a
    /// [`RemoteSkipped`](CollectionPullEvent::RemoteSkipped) event, and the
    /// pull asks the next remote. The causes are a connection or a request
    /// that fails, for example a listing request that gets a status from 500
    /// to 599, a listing or a summary that does not parse, a summary that the
    /// policy refuses, a listed ref with no `ostree.commit.timestamp` of type
    /// `t`, and a bucket repository with no `summary`.
    ///
    /// A listed ref whose name fails the ref-name rule, for example
    /// `origin:main`, is skipped: `on_event` gets a
    /// [`RefSkipped`](CollectionPullEvent::RefSkipped) event, and the other
    /// refs of the remote stay in the selection. The probe reads no commit and
    /// no timestamp of a skipped ref. Each name in
    /// [`refs`](PullOptions::refs) passes the ref-name rule before the first
    /// request, so the probe skips a ref only when `refs` is empty.
    ///
    /// # Access
    ///
    /// A remote that `ostrya serve` serves identifies the client of each
    /// request: by the client certificate of the keys `tls-client-cert-path`
    /// and `tls-client-key-path` of the remote, by the client address, or as
    /// `anonymous`. When `http_headers` of
    /// [`overrides`](PullOptions::overrides) holds an `Authorization` header,
    /// each HTTP request carries the bearer token or the Basic credential of
    /// that header, which gives a `token-sha256` or a `basic-sha256` item.
    /// Over ssh, `ostrya send` identifies the client by its `ssh:NAME` item.
    /// The listing holds a ref when the client group of the item has `r` on
    /// its name in the namespace of the ref. With `tls-accept-claim=true`,
    /// the claims of the certificate for that namespace replace the rules of
    /// the group there. The namespace of the own collection id of the remote
    /// is its local namespace. So the items of the local refs of the remote
    /// apply, with the claims with no `@ID:` and the claims with `@ID:` of
    /// that id.
    ///
    /// So the probe cannot tell a ref that the remote does not hold from a
    /// ref that the client cannot read. When one remote hides a ref, the pull
    /// takes the ref from another remote that lists it. Else the pull fails,
    /// because no remote lists the ref.
    ///
    /// A remote that refuses the client answers the listing request with 401
    /// or 403. The probe then reads the `summary`, by the rule of the status
    /// from 400 to 499, and the remote refuses that request with the same
    /// status. A 401 is an error, so the pull skips the remote with a
    /// [`RemoteSkipped`](CollectionPullEvent::RemoteSkipped) event. A 403
    /// marks the summary absent, so the remote is a candidate that lists no
    /// ref, and `on_event` gets no event. `ostrya serve` answers 403 to a
    /// client that it refuses.
    ///
    /// Under a summary policy, the probe reads the summary of the item alone.
    /// The item of a group with `summary=false` has no summary, and claims
    /// never apply to a summary. A group with `tls-accept-claim=true` cannot
    /// set `summary=true`. So from such a remote, a client whose right comes
    /// from claims, or from a group with `summary=false`, gets no ref. The policy refuses ref
    /// data that no signature covers, so the probe does not read the listing
    /// in place of the summary.
    ///
    /// # Selection
    ///
    /// For each ref, the pull selects the remote that lists the newest
    /// commit, by the listed timestamp. If two remotes list the same
    /// timestamp, the earlier remote in `remotes` wins.
    ///
    /// # Commit operands
    ///
    /// A commit operand names the commit that the pull fetches by its
    /// checksum, 64 lowercase hex characters:
    ///
    /// - `CHECKSUM` fetches the commit and writes no ref.
    /// - `NAME@CHECKSUM` and `@ID:NAME@CHECKSUM`, where `ID` is
    ///   `collection_id`, fetch the commit and write the ref `NAME` of the
    ///   collection to it. `NAME` need not be a ref that a remote lists.
    ///   [`commit_operand`](crate::commit_operand) makes the text.
    ///
    /// The checksum part of an operand starts after the last `@` that is not
    /// the first character, as [`Repo::pull`] states in "Refs". A plain name
    /// of 64 lowercase hex characters is a `CHECKSUM` operand, and names no
    /// ref.
    ///
    /// The pull reads no ref listing and no summary for a commit operand.
    /// The probe asks each remote, in the order of `remotes`, for the commit
    /// object of each commit operand that no earlier remote serves. The
    /// first remote that serves the commit object is the remote of the
    /// operand. A remote that does not serve the object leaves the operand to
    /// the next remote, with no event. Over HTTP, a 403, a 404, and a 410
    /// mark the object absent. A request that fails for another cause
    /// skips the remote with a
    /// [`RemoteSkipped`](CollectionPullEvent::RemoteSkipped) event, and the
    /// pull then selects no ref and no commit from it. The probe hashes the
    /// commit object against its name, reads its timestamp, and keeps no
    /// bytes of it. So the pull from the remote requests the commit object
    /// again, unless this repository holds the commit. The probe of a local
    /// repository reads the commit from the repository, and hashes nothing.
    ///
    /// If each name is a commit operand, the pull reads no ref listing, no
    /// `summary`, and no `summary.sig` of a remote, and the summary policy
    /// of a remote does not apply. The probe stops at the remote that
    /// serves the last commit, and opens no session to the remotes after it.
    /// If one name is not a commit operand, the probe and the pull read and
    /// verify the summaries as "Probe" and "Pull" state, also the pull from
    /// a remote that gives commits of commit operands alone.
    ///
    /// The pull from the remote of an operand fetches the commit with the
    /// refs that it selected from that remote, in one transaction.
    /// [`depth`](PullOptions::depth),
    /// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY),
    /// [`subpaths`](PullOptions::subpaths), the attachments, and the
    /// signature checks apply to the commit as to the tip of a ref. The
    /// checks of "Pull" apply as follows:
    ///
    /// - The collection-binding check applies to the commit of each commit
    ///   operand, also under [`no_ref_writes`](PullOptions::no_ref_writes).
    /// - The ref-binding check applies to the commit of `NAME@CHECKSUM`, and
    ///   reads `NAME`. The commit of `CHECKSUM` gets no ref-binding check.
    /// - No remote listed a timestamp for a commit operand, so its commit
    ///   gets no check of a listed timestamp.
    /// - [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef)
    ///   compares the commit of `NAME@CHECKSUM` with the current commit of
    ///   the ref. The pull refuses a `CHECKSUM` operand under that check.
    ///   Under [`TimestampCheck::Rev`](crate::TimestampCheck::Rev), the pull
    ///   compares each commit with the commit of the check.
    ///
    /// The static delta rules of a commit operand are the rules of
    /// [`Repo::pull`]: the commit of `NAME@CHECKSUM` takes a delta as the tip
    /// of the ref, and the commit of `CHECKSUM` takes none.
    ///
    /// Two names that give one ref name with two commits write one ref, and
    /// the pull refuses them before its first request. A ref name with no
    /// commit beside the same ref name with a commit is such a pair. Under
    /// [`no_ref_writes`](PullOptions::no_ref_writes), the pull takes the pair
    /// and fetches both commits. A `NAME@CHECKSUM` operand that occurs again
    /// with the same commit adds nothing, also in the other form.
    ///
    /// A name of 64 lowercase hex characters is a valid ref name. The
    /// operand `CHECKSUM@CHECKSUM` writes the ref of that name, and a
    /// `CHECKSUM` operand of the same checksum beside it fetches no other
    /// object and changes no ref. The operand `@ID:CHECKSUM` names the listed
    /// ref of that name. The pull writes that ref at the commit that the
    /// selected remote lists, also beside a `CHECKSUM` operand of that
    /// commit. In both cases, the pull still refuses the `CHECKSUM` operand
    /// under
    /// [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef) and
    /// under [`require_static_deltas`](PullOptions::require_static_deltas),
    /// as "Errors" states.
    ///
    /// # Pull
    ///
    /// The pull then takes all objects of each ref from the selected remote,
    /// as [`Repo::pull`] does, at the commit that the probe listed. It reads
    /// no ref of the remote again. If the probe read the refs from the
    /// summary, the pull uses those bytes and does not read the summary
    /// again. The remotes pull in the order of `remotes`, each with its own
    /// transaction. A remote with no selected ref and no commit of a commit
    /// operand is not asked again. The pull fetches the attachments of each
    /// commit from the remote of the commit, as [`Repo::pull`] states in
    /// "Attachments".
    ///
    /// So a failure of a later remote leaves the objects and the refs of the
    /// earlier remotes in place. A failure of a selected remote stops the
    /// whole pull. The pull does not take the ref from the next remote.
    ///
    /// For each pulled commit, the pull makes these checks, and a commit that
    /// fails one fails the pull with [`Error::Pull`]:
    ///
    /// - The `ostree.collection-binding` of the commit must be
    ///   `collection_id`. A commit with no `ostree.collection-binding` key
    ///   fails, unless [`allow_unbound`](CollectionPullOptions::allow_unbound)
    ///   is set. A key whose value is not a string fails always.
    /// - The `ostree.ref-binding` of the commit must hold the ref. A commit
    ///   with no ref binding passes, as in each other pull.
    /// - The timestamp of the commit must be the timestamp that the remote
    ///   listed for the ref.
    ///
    /// The pull makes none of these checks on an attachment. "Commit
    /// operands" states the checks of the commit of a commit operand.
    ///
    /// # Refs
    ///
    /// The pull writes each ref as the collection ref
    /// `refs/mirrors/<collection_id>/<name>`. It writes no ref under
    /// `refs/remotes/`.
    ///
    /// If the `[core] collection-id` of this repository is `collection_id`,
    /// the pull writes the local ref `refs/heads/<name>`, and it does not
    /// touch `refs/mirrors/<collection_id>/`.
    ///
    /// The pull writes no ref for a `CHECKSUM` operand, and no ref under
    /// [`no_ref_writes`](PullOptions::no_ref_writes).
    ///
    /// Delta discovery and
    /// [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef) read
    /// the current commit of a ref at the path that
    /// [`resolve_ref_tip`](Repo::resolve_ref_tip) reads.
    ///
    /// # Local repository
    ///
    /// The address of a local repository is `file://` followed by an
    /// absolute path, with the scheme in ASCII letters of either case. The
    /// pull takes the path as written, and decodes no `%` escape. A
    /// `pull-url` with another address wins over a `file://` value of
    /// `url`. The pull ignores the TLS keys, the key `proxy`, and the ssh
    /// keys of the remote. The trust of the remote applies, as for each
    /// remote.
    ///
    /// The probe opens the repository at the path in the strict open mode,
    /// and the repository stays open until the pull from it ends. The open
    /// reads `config` and opens `objects` as [`Repo::open`] does, and reads
    /// no `[ex-ostrya] remotes-config-dir` key and no remotes directory of
    /// the repository. The probe takes the refs as follows:
    ///
    /// - If the policy of the remote covers the summary, the probe reads the
    ///   `summary` and the `summary.sig` of the repository, verifies the
    ///   summary, and reads the refs from it, as from a remote.
    /// - Otherwise, the probe reads the ref files of the collection with
    ///   [`Repo::list_collection_refs_in`]. So a repository whose
    ///   `[core] collection-id` is `collection_id` gives its `refs/heads`
    ///   refs. The probe reads only the directories that the names can
    ///   reach. It skips each ref whose name fails the ref-name rule, as
    ///   "Probe" states. The timestamp of each other ref is the timestamp of
    ///   the commit that the probe pins. The probe reads each such commit for
    ///   its timestamp, and keeps no bytes of it for the pull.
    ///
    /// The client groups of the repository do not apply, because they govern
    /// `ostrya serve` and `ostrya send` alone. The file permissions are the
    /// access. A directory outside the selection that the probe cannot read
    /// fails nothing. A directory or a ref file inside the selection that the
    /// probe cannot read skips the remote, as each other error of the open
    /// and of the probe does. The message of the event names the path.
    ///
    /// The pull from a selected local repository is a pull of
    /// [`Repo::pull_local`] at the commits that the probe read. It reads no
    /// ref file again. It reads each tip commit from the repository, and
    /// makes the checks of "Pull" and the timestamp check of
    /// [`timestamp_check`](PullOptions::timestamp_check). So a tip commit
    /// whose timestamp changed between the probe and the pull fails the
    /// pull. Under a summary policy, the listed timestamps come from the
    /// verified summary, and the pull takes that summary from the probe. It
    /// reads the `summary` and the `summary.sig` of the repository one time.
    /// A listed commit that the repository does not hold fails the pull.
    /// With [`subpaths`](PullOptions::subpaths), the pull imports the objects
    /// that a fetch of the subpaths takes, follows no attachment, and keeps
    /// the `.commitpartial` marker of each commit that it marks, as a pull
    /// from an HTTP remote does. It reads a static delta only under
    /// [`require_static_deltas`](PullOptions::require_static_deltas).
    ///
    /// A local repository serves the commit of a commit operand if it holds
    /// the commit object. If each name is a commit operand, the pull reads no
    /// `summary` and no `summary.sig` of the repository. Under
    /// [`require_static_deltas`](PullOptions::require_static_deltas), it
    /// reads the delta index of each target if the `config` of the
    /// repository states `[core] indexed-deltas=true`, and else reads one
    /// superblock by name, as [`Repo::pull_local`] states in "Static
    /// deltas".
    ///
    /// If the trust of the remote checks the signatures of the commits or of
    /// the summary, the pull runs as with [`UNTRUSTED`](PullFlags::UNTRUSTED).
    /// It hashes each commit that it reads for the checks, each dirtree that
    /// the walk of the tree reads, and each object that it imports, and
    /// compares each result with the name of the object. A signature covers
    /// the commit or the summary alone. The commit names its root dirtree,
    /// and each dirtree names the objects below it. So each object that the
    /// pull imports is an object of the tree of the verified commit.
    /// Otherwise the flags of the caller apply: without
    /// [`UNTRUSTED`](PullFlags::UNTRUSTED), the pull links, clones, or copies
    /// an object with no hash, and an object that it writes again in another
    /// form always gets a hash. The counts of the pull go to
    /// [`CollectionPullStats::stats`] as the counts of a local pull: the
    /// import counts, and no fetch count unless it reads static deltas.
    /// [`CollectionPullStats::local`] also gets these counts.
    ///
    /// # Options
    ///
    /// Each field of [`PullOptions`] that [`Repo::pull`] reads applies to
    /// the pull from each selected remote, with these exceptions:
    ///
    /// - [`refs`](PullOptions::refs) selects the refs, as stated above.
    /// - [`overrides`](PullOptions::overrides),
    ///   [`verify`](PullOptions::verify),
    ///   [`trust_group`](PullOptions::trust_group), and
    ///   [`max_outstanding_fetches`](PullOptions::max_outstanding_fetches)
    ///   apply to the probe and the pull of each remote.
    /// - [`progress`](PullOptions::progress) gets the counters of each pull
    ///   from a remote, and no count of the probe. A pull from a local
    ///   repository does not use it.
    /// - [`flags`](PullOptions::flags) of a pull from a local repository
    ///   also hold [`UNTRUSTED`](PullFlags::UNTRUSTED) if the trust of the
    ///   remote checks signatures, as "Local repository" states.
    ///
    /// # Errors
    ///
    /// These errors stop the pull before its first request. The pull writes
    /// no object and no ref:
    ///
    /// - [`Error::InvalidInput`] if `collection_id` fails the collection-id
    ///   rule ([`is_collection_id`](crate::is_collection_id)) or is longer than
    ///   255 bytes.
    /// - [`Error::InvalidInput`] if `remotes` is empty.
    /// - [`Error::Pull`] if a subpath does not start with `/`.
    /// - [`Error::InvalidInput`] if [`depth`](PullOptions::depth) is below
    ///   `-1`.
    /// - [`Error::InvalidInput`] if [`remote`](PullOptions::remote) is set,
    ///   if [`flags`](PullOptions::flags) holds
    ///   [`MIRROR`](PullFlags::MIRROR) or
    ///   [`DISABLE_VERIFY_BINDINGS`](PullFlags::DISABLE_VERIFY_BINDINGS), if
    ///   [`static_deltas`](PullOptions::static_deltas) is set, or if
    ///   [`overrides`](PullOptions::overrides) holds a `url`.
    /// - [`Error::InvalidInput`] if a name in [`refs`](PullOptions::refs)
    ///   is an `@ID:NAME` ref of a collection other than `collection_id`.
    /// - [`Error::InvalidRefspec`] if a name in [`refs`](PullOptions::refs)
    ///   is not a valid ref name, a valid `@ID:NAME` ref, or a commit operand
    ///   with such a ref part and a checksum part of 64 lowercase hex
    ///   characters. The error holds the name as given.
    /// - [`Error::InvalidInput`] if a name in [`refs`](PullOptions::refs)
    ///   does not fit in a ref listing request alone: if its entry `ID/NAME`
    ///   is longer than [`MAX_REF_ENTRY_LEN`] bytes or has more than
    ///   [`MAX_REF_ENTRY_PARTS`] parts, or if the request target of the name
    ///   alone over HTTP is longer than 16 KiB. The limits do not apply to
    ///   the ref part of a commit operand, which no listing request holds.
    /// - [`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 [`refs`](PullOptions::refs) holds a `CHECKSUM`
    ///   operand whose commit this repository does not hold complete, under
    ///   [`require_static_deltas`](PullOptions::require_static_deltas)
    ///   without [`disable_static_deltas`](PullOptions::disable_static_deltas)
    ///   and without [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY).
    /// - [`Error::Pull`] if two names write one ref with two commits, unless
    ///   [`no_ref_writes`](PullOptions::no_ref_writes) is set. The error
    ///   holds both names as given, and the path of the ref.
    /// - [`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.
    /// - The errors of [`resolve_pull`](crate::endpoint::resolve_pull) and
    ///   of [`PullTrust::from_remote`], for each remote, and the errors of
    ///   [`trust_group`](PullOptions::trust_group).
    /// - For each remote at a `file:` address, [`Error::Pull`] if the
    ///   address does not start with `file://`, names a host (`localhost`
    ///   too), has no path, or holds `%`, `?`, or `#`. Also
    ///   [`Error::InvalidInput`] if [`overrides`](PullOptions::overrides)
    ///   sets a field of another transport, for example a TLS path, a
    ///   header, or a retry count above 0. The message names the field.
    /// - For each HTTP remote and each remote at an `s3://` address, the
    ///   errors of [`Repo::pull`] that come from the build of its fetcher:
    ///   [`Error::Unsupported`] for a mirror scheme other than `http` and
    ///   `https` or a refused proxy, and [`Error::Fetch`] for a mirror that is
    ///   not a valid absolute URL, an invalid header, or TLS material that
    ///   does not parse.
    /// - For each ssh remote, [`Error::Remote`] if the ssh command or the
    ///   send command is empty or holds only white space, or if the
    ///   `OSTRYA_SSH_COMMAND` environment variable is not UTF-8.
    ///
    /// These errors stop the pull after the probe, before its first object
    /// request:
    ///
    /// - [`Error::Pull`] if each remote failed the probe.
    /// - [`Error::Pull`] if no remote lists a requested ref.
    /// - [`Error::Pull`] if [`refs`](PullOptions::refs) is empty and no
    ///   remote lists a ref of the collection.
    /// - [`Error::Pull`] if no remote serves the commit of a commit operand.
    ///   The error names the commit.
    ///
    /// After these checks, the pull from each selected remote has the errors
    /// of [`Repo::pull`] that stop it before it fetches an object, while it
    /// fetches, and at any request or write. [`Error::Pull`] also comes from
    /// the checks of each commit above. [`Error::ChecksumMismatch`] comes
    /// from an object of a local repository that does not hash to its name.
    ///
    /// # Examples
    ///
    /// Pull one ref of a collection from the remotes that serve it:
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let mut opts = ostrya::CollectionPullOptions::default();
    /// opts.pull.refs = vec!["exampleos/stable".to_owned()];
    /// opts.on_event = Some(Box::new(|event| eprintln!("warning: {event}")));
    /// let pulled = repo
    ///     .pull_collection("org.example.Os", &["mirror1", "mirror2"], opts)
    ///     .await?;
    /// for r in &pulled.refs {
    ///     println!("{} from {}: {}", r.name, r.remote, r.commit);
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [`MAX_REF_PATTERNS`]: crate::MAX_REF_PATTERNS
    /// [`MAX_REF_ENTRY_LEN`]: crate::MAX_REF_ENTRY_LEN
    /// [`MAX_REF_ENTRY_PARTS`]: crate::MAX_REF_ENTRY_PARTS
    pub async fn pull_collection(
        &self,
        collection_id: &str,
        remotes: &[&str],
        opts: CollectionPullOptions,
    ) -> Result<CollectionPullStats> {
        let started = Instant::now();
        let CollectionPullOptions {
            pull: opts,
            mut on_event,
            allow_unbound,
        } = opts;
        let (subpaths, operands) = check_collection_pull(collection_id, remotes, &opts)?;
        check_commit_operands(self, &opts).await?;
        let place = RefPlace::of_collection(self, collection_id);
        // Two operands with one ref name write one ref. An operand that
        // occurs again is one operand, so each other pair has two commits.
        if !opts.no_ref_writes {
            check_one_place(
                place,
                operands
                    .refs
                    .iter()
                    .map(|operand| (operand.given.as_str(), operand.name.as_str())),
            )?;
        }
        // The pull reads the rule one time, here. A value that is not a
        // boolean stops the pull before its first request. Each run of each
        // remote takes this value.
        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().get::<repo::Fsync>()?;
        self.config().get::<repo::PerObjectFsync>()?;
        let names: Vec<&str> = operands
            .refs
            .iter()
            .filter(|operand| operand.commit.is_none())
            .map(|operand| operand.name.as_str())
            .collect();
        // Each commit that an operand names, one time.
        let mut named = HashSet::new();
        let commits: Vec<Checksum> = operands
            .refs
            .iter()
            .filter_map(|operand| operand.commit)
            .chain(operands.bare.iter().copied())
            .filter(|commit| named.insert(*commit))
            .collect();
        // An empty list of operands takes each ref of the collection. With
        // commit operands alone, the pull reads no ref of a remote.
        let commits_alone = names.is_empty() && !commits.is_empty();

        // The endpoint, the trust, and the transport of each remote come
        // before the first request, so an error in the config of one remote
        // stops the pull.
        let mut candidates = Vec::with_capacity(remotes.len());
        // The trust group of the options keeps its commit policy, so the pull
        // reads the key sources of the group one time for all the remotes.
        let mut group = opts.trust_group.as_deref().map(FieldGroup::new);
        for name in first_of_each(remotes.iter().copied()) {
            let trust = TrustScope::Pull(group.as_mut());
            candidates.push(resolve_candidate(self, name, &opts, trust).await?);
        }
        // The pull reports each remote and each ref that it skips before it
        // probes the next remote.
        let found = find_refs(
            &candidates,
            collection_id,
            &names,
            !commits_alone,
            &commits,
            |candidate, probed| match probed {
                Ok(probed) => report_skipped_refs(&mut on_event, candidate, probed),
                Err(e) => {
                    let Some(on_event) = on_event.as_mut() else {
                        return;
                    };
                    let message = match &candidate.transport {
                        Transport::Local(path) => {
                            format!("local repository '{}': {e}", path.display())
                        }
                        _ => e.to_string(),
                    };
                    on_event(CollectionPullEvent::RemoteSkipped {
                        remote: candidate.name.to_owned(),
                        message,
                    });
                }
            },
        )
        .await;
        // The session and the summary of each remote that answered, by the
        // position of the remote.
        let mut answers = Vec::with_capacity(found.len());
        let mut sessions = Vec::with_capacity(found.len());
        let mut summaries = Vec::with_capacity(found.len());
        // The first remote that serves each commit of the commit operands, by
        // its position, and the timestamp of the commit.
        let mut served: HashMap<Checksum, (usize, u64)> = HashMap::new();
        for (index, probed) in found.into_iter().enumerate() {
            match probed {
                Ok(probed) => {
                    for (commit, timestamp) in probed.commits {
                        served.insert(commit, (index, timestamp));
                    }
                    answers.push(Some(probed.listed));
                    sessions.push(probed.session);
                    summaries.push(probed.summary.map(|bytes| (bytes, probed.summary_dict)));
                }
                Err(_) => {
                    answers.push(None);
                    sessions.push(None);
                    summaries.push(None);
                }
            }
        }
        let selected = if commits_alone {
            if answers.iter().all(Option::is_none) {
                Err(none_answered(collection_id))
            } else {
                Ok(Vec::new())
            }
        } else {
            select(collection_id, &names, &answers)
        };
        let selected = selected.and_then(|selected| {
            match commits.iter().find(|commit| !served.contains_key(commit)) {
                Some(commit) => Err(Error::Pull(format!(
                    "no remote of collection '{collection_id}' serves the commit {commit}"
                ))),
                None => Ok(selected),
            }
        });
        let selected = match selected {
            Ok(selected) => selected,
            Err(e) => {
                end_sessions(sessions.into_iter().flatten()).await;
                return Err(e);
            }
        };
        drop(answers);
        // A remote with no selected ref and no commit is not asked again.
        let unselected = take_unselected(&mut sessions, &mut summaries, |index| {
            selected.iter().any(|s| s.remote == index)
                || served.values().any(|(remote, _)| *remote == index)
        });
        end_sessions(unselected).await;

        let candidate_names: Vec<&str> = candidates.iter().map(|c| c.name).collect();
        let mut stats = PullStats::default();
        let mut local = PullStats::default();
        let mut changed_refs = Vec::new();
        for (index, candidate) in candidates.into_iter().enumerate() {
            // The find step gives no session for a remote that it did not
            // probe.
            let Some(session) = sessions.get_mut(index).and_then(Option::take) else {
                continue;
            };
            let from_local = matches!(session, Session::Local(_));
            let mine: Vec<&Listed> = selected
                .iter()
                .filter(|selected| selected.remote == index)
                .map(|selected| &selected.listed)
                .collect();
            let mut targets: Vec<(String, Checksum)> =
                mine.iter().map(|l| (l.name.clone(), l.commit)).collect();
            let listed: HashMap<String, (Checksum, u64)> = mine
                .iter()
                .map(|l| (l.name.clone(), (l.commit, l.timestamp)))
                .collect();
            // The commit operands whose commit this remote serves first.
            let serves = |commit: &Checksum| served[commit].0 == index;
            targets.extend(operands.refs.iter().filter_map(|operand| {
                let commit = operand.commit.filter(serves)?;
                Some((operand.name.clone(), commit))
            }));
            // A listed ref whose name is the hex form of its commit writes
            // its ref. It wins over the operand `CHECKSUM` of that commit.
            let bare: Vec<Checksum> = operands
                .bare
                .iter()
                .copied()
                .filter(serves)
                .filter(|commit| {
                    listed
                        .get(&commit.to_hex())
                        .is_none_or(|(tip, _)| tip != commit)
                })
                .collect();
            targets.extend(bare.iter().map(|commit| (commit.to_hex(), *commit)));
            let (summary, summary_dict) = summaries[index].take().unzip();
            // The trust and the session hold what these fields gave.
            let run = PullOptions {
                refs: targets.iter().map(|(name, _)| name.clone()).collect(),
                verify: PullVerify::default(),
                trust_group: None,
                max_outstanding_fetches: None,
                overrides: EndpointOverrides::default(),
                ..opts.clone()
            };
            let pinned = Pinned {
                targets,
                listed,
                bare: bare.into_iter().collect(),
                commits_alone,
                collection: collection_id,
                allow_unbound,
                place,
                summary: Mutex::new(summary),
                summary_dict: summary_dict.flatten(),
            };
            let pulled = match session {
                Session::Remote(connection) => {
                    self.run_session(
                        connection,
                        candidate.trust,
                        related,
                        run,
                        Wanted::Pinned(&pinned),
                        subpaths.clone(),
                        None,
                        Instant::now(),
                        true,
                    )
                    .await
                }
                // The pull reads each tip commit from the source again, and
                // checks it against the listed timestamp. Under a summary
                // policy, it takes the summary that the probe checked.
                Session::Local(src) => {
                    self.pull_local_candidate(
                        &src,
                        candidate.trust,
                        related,
                        run,
                        subpaths.clone(),
                        &pinned,
                    )
                    .await
                }
            };
            match pulled {
                Ok(PullReport {
                    stats: pulled,
                    changed_refs: changed,
                }) => {
                    add_stats(&mut stats, &pulled);
                    if from_local {
                        add_stats(&mut local, &pulled);
                        local.elapsed += pulled.elapsed;
                    }
                    changed_refs.extend(changed);
                }
                Err(e) => {
                    end_sessions(sessions.into_iter().flatten()).await;
                    return Err(e);
                }
            }
        }
        stats.elapsed = started.elapsed();

        // The selection follows the order of the operands with no commit.
        let mut selected = selected.into_iter().map(|selected| CollectionPullRef {
            name: selected.listed.name,
            remote: candidate_names[selected.remote].to_owned(),
            commit: selected.listed.commit,
            timestamp: selected.listed.timestamp,
        });
        let mut refs = Vec::with_capacity(operands.refs.len());
        for operand in operands.refs {
            match operand.commit {
                Some(commit) => {
                    let (remote, timestamp) = served[&commit];
                    refs.push(CollectionPullRef {
                        name: operand.name,
                        remote: candidate_names[remote].to_owned(),
                        commit,
                        timestamp,
                    });
                }
                None => refs.extend(selected.next()),
            }
        }
        // A pull with no operand selected each listed ref.
        refs.extend(selected);
        Ok(CollectionPullStats {
            refs,
            stats,
            local,
            changed_refs,
        })
    }

    /// Lists the refs of the collection `collection_id` that the remote
    /// `remote` serves, as
    /// [`remote_list_collection_refs_with`](Repo::remote_list_collection_refs_with)
    /// does with the default overrides and no event callback.
    ///
    /// The default overrides do not set `allow_cleartext_credentials`, so the
    /// call refuses an `http://` S3 endpoint.
    ///
    /// # Errors
    ///
    /// The errors of
    /// [`remote_list_collection_refs_with`](Repo::remote_list_collection_refs_with).
    pub async fn remote_list_collection_refs(
        &self,
        remote: &str,
        collection_id: &str,
        names: &[&str],
    ) -> Result<Vec<(String, Checksum)>> {
        self.remote_list_collection_refs_with(
            remote,
            collection_id,
            names,
            EndpointOverrides::default(),
            None,
        )
        .await
    }

    /// Lists the refs of the collection `collection_id` that the remote
    /// `remote` serves, with the overrides `overrides` of the caller.
    ///
    /// `remote` is a `[remote "<name>"]` section of the config of this
    /// repository. The call does not read the `collection-id` key of the
    /// remote. `names` holds exact ref names. An empty slice selects each ref
    /// of the collection. A name that occurs again adds nothing.
    ///
    /// The result holds the name and the commit of each ref that the remote
    /// lists, sorted byte-wise by name. A name that the remote does not hold
    /// is absent from the result. The call writes nothing to this repository,
    /// and checks no commit signature.
    ///
    /// The call skips a listed ref whose name fails the ref-name rule, for
    /// example `origin:main`, and reads no commit of it. The ref is absent
    /// from the result, and `on_event`, if it is set, gets a
    /// [`RefSkipped`](CollectionPullEvent::RefSkipped) event for it, in the
    /// listed order, before the call returns. Each name in `names` passes the
    /// ref-name rule before the first request, so the call skips a ref only
    /// when `names` is empty. The call gives `on_event` no other event: the
    /// error of the probe is the error of the call. For an ssh remote, the
    /// call can fail after it gave the events, when the end of the session
    /// fails.
    ///
    /// # Address and trust
    ///
    /// The call resolves the remote as [`Repo::pull_collection`] resolves a
    /// remote, before its first request. A remote whose `pull-url`, or else
    /// `url`, has the scheme `file` is a local repository, as "Local
    /// repository" of [`Repo::pull_collection`] states. For each other
    /// remote, the call resolves the endpoint with
    /// [`resolve_pull`](crate::endpoint::resolve_pull) and `overrides`. So
    /// over HTTP, the TLS keys and the key `proxy` of the remote apply. Over
    /// ssh, the ssh command and the send command of the remote apply. For an
    /// `s3://` address, the S3 keys of the remote apply, and
    /// `allow_cleartext_credentials` permits an `http://` S3 endpoint.
    /// The trust of the remote is its summary policy alone: the keys
    /// `gpg-verify-summary` and `sign-verify-summary` of the remote and the
    /// key sources that they read, as [`PullTrust::from_remote`] reads them.
    /// The call checks no commit signature, so it does not read `gpg-verify`,
    /// `sign-verify`, the key `trust`, or a trust group.
    ///
    /// # Probe
    ///
    /// The call reads the refs as the probe of [`Repo::pull_collection`]
    /// does, with its one remote, in one session:
    ///
    /// - Under a summary policy (`gpg-verify-summary`,
    ///   `sign-verify-summary`), the call reads the `summary` and the
    ///   `summary.sig` of the remote, and verifies the summary before it
    ///   reads the refs from it. It does not read the ref listing.
    /// - Otherwise, the call reads the ref listing, in one or more requests.
    ///   With no names, it asks for the local refs of the remote when the
    ///   listing states `collection_id` as the collection id of the remote.
    /// - If the remote serves no ref listing, the call reads the `summary`.
    ///   An HTTP remote serves no listing when it answers with a status from
    ///   400 to 499. A remote with no listing and no summary gives an empty
    ///   vector.
    /// - A bucket repository at an `s3://` address gives the refs of its
    ///   `summary` alone.
    /// - A local repository gives the refs of its ref files, or of its
    ///   verified summary under a summary policy. Without a summary policy,
    ///   the call reads the tip commit of each ref for its timestamp.
    ///
    /// A commit that the source does not hold fails the call when the source
    /// reads the commit. The ref files of a local repository give
    /// [`Error::ObjectNotFound`]. `ostrya serve` answers the listing request
    /// with the status 500, and the call returns [`Error::HttpStatus`] after
    /// the retries of the request. `ostrya send` answers with an error, and
    /// the call returns [`Error::Remote`]. A ref that the call reads from a
    /// summary gives the commit that the summary lists.
    ///
    /// The call ends the session before it returns.
    ///
    /// # Access
    ///
    /// A remote that `ostrya serve` serves identifies the client by the client
    /// certificate of the keys `tls-client-cert-path` and
    /// `tls-client-key-path` of the remote, by the client address, or as
    /// `anonymous`. When `http_headers` of `overrides` holds an
    /// `Authorization` header, each HTTP request carries the bearer token or
    /// the Basic credential of that header, which gives a `token-sha256` or a
    /// `basic-sha256` item. Over ssh, `ostrya send` identifies the client by
    /// its `ssh:NAME` item.
    /// The result holds a ref when the client group of the item has `r` on
    /// its name in the namespace of the ref. With `tls-accept-claim=true`,
    /// the claims of the certificate for that namespace replace the rules of
    /// the group there. The namespace of the own collection id of the remote
    /// is its local namespace. So the items of the local refs of the remote
    /// apply, with the claims with no `@ID:` and the claims with `@ID:` of
    /// that id. So a ref that the client
    /// cannot read is absent from the result, as a ref that the remote does
    /// not hold is.
    ///
    /// A remote that refuses the client answers the listing request and the
    /// `summary` request with 401 or 403. For a 401, the call returns
    /// [`Error::HttpStatus`]. A 403 marks the listing and the `summary`
    /// absent, so the result holds no ref. `ostrya serve` answers 403 to a
    /// client that it refuses.
    ///
    /// Under a summary policy, the call reads the summary of the item alone.
    /// The item of a group with `summary=false` has no summary, and claims
    /// never apply to a summary. So from such a remote, a client whose right
    /// comes from claims, or from a group with `summary=false`, gets no ref.
    ///
    /// A local repository applies no client group. The file permissions are
    /// the access.
    ///
    /// # Errors
    ///
    /// These errors come before the first request:
    ///
    /// - [`Error::InvalidInput`] if `collection_id` fails the collection-id
    ///   rule ([`is_collection_id`](crate::is_collection_id)) or is longer than
    ///   255 bytes.
    /// - [`Error::InvalidRefspec`] if a name in `names` is not a valid ref
    ///   name.
    /// - [`Error::InvalidInput`] if a name in `names` does not fit in a ref
    ///   listing request alone, as for [`Repo::pull_collection`].
    /// - [`Error::InvalidInput`] if `overrides` holds a `url`.
    /// - The errors of [`resolve_pull`](crate::endpoint::resolve_pull).
    /// - The errors of [`PullTrust::from_remote`] that come from the summary
    ///   policy:
    ///   - [`Error::Core`] if `gpg-verify-summary` is not a boolean, if a
    ///     value holds a malformed escape sequence, or if a sign-api key is
    ///     not valid base64.
    ///   - [`Error::Signature`] if `sign-verify-summary` names an engine that
    ///     has no trusted key, if `sign-verify-summary=true` finds no engine
    ///     with a trusted key, or if a keyring or a key file of the policy
    ///     cannot be read or is not valid for its engine.
    ///   - [`Error::Unsupported`] if the policy asks for an engine that this
    ///     build does not verify with.
    ///   - [`Error::Io`] if a directory of keys cannot be listed.
    /// - For a remote at a `file:` address, the errors of the address and of
    ///   `overrides` that [`Repo::pull_collection`] states.
    /// - For an HTTP remote and a remote at an `s3://` address, the errors of
    ///   the build of its fetcher that [`Repo::pull_collection`] states. For
    ///   an ssh remote, the errors of its ssh command and of its send command.
    ///
    /// These errors come from the probe:
    ///
    /// - [`Error::HttpStatus`] if the remote refuses the client with 401, or
    ///   if a request gets a status from 500 to 599 after its retries.
    /// - [`Error::Fetch`] and the other errors of an HTTP request that fails.
    /// - [`Error::Remote`] if the ssh session fails, also at its end, or if
    ///   a read from a bucket repository fails.
    /// - [`Error::Signature`] if the summary fails the policy, or if the
    ///   remote has no `summary` or no `summary.sig` under the policy.
    /// - [`Error::Pull`] if a bucket repository has no `summary` and no
    ///   summary policy applies.
    /// - [`Error::Core`] or [`Error::InvalidFormat`] if the listing or the
    ///   summary does not parse, and [`Error::InvalidFormat`] if a listed ref
    ///   has no `ostree.commit.timestamp` of type `t`.
    /// - For a local repository, the errors of [`Repo::open`] except the
    ///   errors of the remotes directory, [`Error::Io`] if a directory or a ref file that the names reach
    ///   cannot be read, and, without a summary policy,
    ///   [`Error::ObjectNotFound`] if the repository does not hold the commit
    ///   of a ref.
    ///
    /// # Examples
    ///
    /// List each ref of a collection on one remote, with a warning for each
    /// skipped ref:
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let refs = repo
    ///     .remote_list_collection_refs_with(
    ///         "mirror1",
    ///         "org.example.Os",
    ///         &[],
    ///         ostrya::endpoint::EndpointOverrides::default(),
    ///         Some(Box::new(|event| eprintln!("warning: {event}"))),
    ///     )
    ///     .await?;
    /// for (name, commit) in &refs {
    ///     println!("{name} {commit}");
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn remote_list_collection_refs_with(
        &self,
        remote: &str,
        collection_id: &str,
        names: &[&str],
        overrides: EndpointOverrides,
        mut on_event: Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
    ) -> Result<Vec<(String, Checksum)>> {
        check_collection_id(collection_id)?;
        check_ref_names(collection_id, names)?;
        if overrides.url.is_some() {
            return Err(Error::InvalidInput(
                "a listing of collection refs reads the address of the remote from the \
                 config, and takes no url override"
                    .into(),
            ));
        }
        let names = first_of_each(names.iter().copied());
        let opts = PullOptions {
            overrides,
            ..PullOptions::default()
        };
        let candidate = resolve_candidate(self, remote, &opts, TrustScope::Summary).await?;
        let Some(found) = find_refs(
            std::slice::from_ref(&candidate),
            collection_id,
            &names,
            true,
            &[],
            |candidate, probed| {
                if let Ok(probed) = probed {
                    report_skipped_refs(&mut on_event, candidate, probed);
                }
            },
        )
        .await
        .pop() else {
            unreachable!("the find step gives one result for each candidate");
        };
        // The summary goes before the end of the session, which waits for the
        // ssh client.
        let Probed {
            listed, session, ..
        } = found?;
        // A local repository has no session to end.
        if let Some(Session::Remote(connection)) = session {
            RemoteSource::new(connection, Vec::new())
                .finish(Ok(()))
                .await?;
        }
        let mut refs: Vec<(String, Checksum)> = listed
            .into_iter()
            .map(|listed| (listed.name, listed.commit))
            .collect();
        refs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
        Ok(refs)
    }

    /// Pulls the selected refs `pinned` of a local candidate of
    /// [`Repo::pull_collection`] from the repository `src` that its probe
    /// opened, under the trust `trust` of the candidate, with the rule
    /// `related`, the options `run`, and the parsed subpaths `subpaths` of
    /// `run`.
    ///
    /// If `trust` checks the signatures of the commits or of the summary, the
    /// call adds [`UNTRUSTED`](PullFlags::UNTRUSTED) to the flags. A
    /// signature covers the commit or the checksum of the summary alone.
    /// Under the flag, the pull hashes each commit that it reads for the
    /// checks and the walk of the chain, each dirtree that the walk of the
    /// tree reads from `src`, and each object that it imports, against its
    /// name. So each imported object is an object of the tree of the verified
    /// commit.
    async fn pull_local_candidate(
        &self,
        src: &Repo,
        trust: PullTrust,
        related: RelatedRule,
        run: PullOptions,
        subpaths: Option<Subpaths>,
        pinned: &Pinned<'_>,
    ) -> Result<PullReport> {
        let started = Instant::now();
        let flags = if trust.checks_signatures() {
            run.flags | PullFlags::UNTRUSTED
        } else {
            run.flags
        };
        let run = PullOptions { flags, ..run };
        self.pull_local_from(
            src,
            trust,
            related,
            run,
            subpaths,
            LocalWanted::Pinned(pinned),
            None,
            started,
            true,
        )
        .await
    }
}

/// Returns the first appearance of each value of `values`, in order.
fn first_of_each<'a>(values: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
    let mut seen = HashSet::new();
    values.filter(|value| seen.insert(*value)).collect()
}

/// Takes out of `sessions` the session of each remote for whose position
/// `selected` returns `false`, and drops the summary of that remote in
/// `summaries`.
///
/// `sessions` and `summaries` hold one slot for each remote, by its
/// position. The pull reads nothing more from a remote with no selected
/// ref, so its summary does not stay in memory for the rest of the pull.
fn take_unselected<S, M>(
    sessions: &mut [Option<S>],
    summaries: &mut [Option<M>],
    selected: impl Fn(usize) -> bool,
) -> Vec<S> {
    sessions
        .iter_mut()
        .zip(summaries.iter_mut())
        .enumerate()
        .filter(|(index, _)| !selected(*index))
        .filter_map(|(_, (session, summary))| {
            *summary = None;
            session.take()
        })
        .collect()
}

/// Ends each session of `sessions`.
///
/// The pull reads nothing more from these remotes, so an error of an end has
/// no effect, and the call drops it. A local repository has no session to
/// end, and the call drops its handle.
async fn end_sessions(sessions: impl IntoIterator<Item = Session>) {
    for session in sessions {
        if let Session::Remote(connection) = session {
            let _ = connection.session.finish().await;
        }
    }
}

/// The trust that [`resolve_candidate`] reads for a remote.
enum TrustScope<'g, 'f> {
    /// The trust of a pull, with the trust group of the options, which
    /// [`PullTrust::for_pull`] reads.
    Pull(Option<&'g mut FieldGroup<'f>>),
    /// The summary policy of the remote alone, which
    /// [`PullTrust::for_summary`] reads.
    Summary,
}

/// Resolves the remote `name` of `repo` to a candidate of a collection pull,
/// with the options `opts` and the trust that `trust` gives.
///
/// The call resolves the origin with [`resolve_origin`], then the trust,
/// then the transport. A `file://` address gives a local candidate. Each
/// other address gives an endpoint, which goes through [`Transport::new`].
/// The call sends no request and opens no repository.
async fn resolve_candidate<'a>(
    repo: &Repo,
    name: &'a str,
    opts: &PullOptions,
    trust: TrustScope<'_, '_>,
) -> Result<Candidate<'a>> {
    let origin = resolve_origin(repo, name, opts.overrides.clone()).await?;
    let trust = match trust {
        TrustScope::Pull(group) => PullTrust::for_pull(repo, name, &opts.verify, group).await?,
        TrustScope::Summary => PullTrust::for_summary(repo, name).await?,
    };
    let transport = match origin {
        Origin::Local(path) => Transport::Local(path),
        Origin::Endpoint(endpoint) => {
            Transport::new(endpoint, opts.max_outstanding_fetches).await?
        }
    };
    Ok(Candidate {
        name,
        transport,
        trust,
        repo: repo.clone(),
    })
}

/// Makes the checks of [`Repo::pull_collection`] that read the arguments
/// alone, in the order of its `# Errors`, and returns the parsed subpaths and
/// the operands of [`refs`](PullOptions::refs), as [`collection_names`]
/// returns them.
fn check_collection_pull(
    collection_id: &str,
    remotes: &[&str],
    opts: &PullOptions,
) -> Result<(Option<Subpaths>, Operands)> {
    check_collection_id(collection_id)?;
    if remotes.is_empty() {
        return Err(Error::InvalidInput(
            "a collection pull needs at least one remote".into(),
        ));
    }
    let subpaths = Subpaths::parse(&opts.subpaths)?;
    check_depth(opts.depth)?;
    if opts.remote.is_some() {
        return Err(Error::InvalidInput(
            "a collection pull writes the refs of the collection, and takes no remote option"
                .into(),
        ));
    }
    if opts.flags.contains(PullFlags::MIRROR) {
        return Err(Error::InvalidInput(
            "a collection pull takes no MIRROR flag".into(),
        ));
    }
    if opts.flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS) {
        return Err(Error::InvalidInput(
            "a collection pull checks the bindings of each commit, and takes no \
             DISABLE_VERIFY_BINDINGS flag"
                .into(),
        ));
    }
    if opts.static_deltas.is_some() {
        return Err(Error::InvalidInput(
            "a collection pull takes no static_deltas list".into(),
        ));
    }
    if opts.overrides.url.is_some() {
        return Err(Error::InvalidInput(
            "a collection pull reads the address of each remote from the config, and takes \
             no url override"
                .into(),
        ));
    }
    let operands = collection_names(collection_id, &opts.refs)?;
    Ok((subpaths, operands))
}

/// Reads the operands `names` of a pull of the collection `collection_id`.
///
/// [`Operand`] reads each operand. The ref part of an operand is `NAME` or
/// `@ID:NAME`, where `ID` is `collection_id`, and both forms give the ref
/// name `NAME`. An operand that names a ref and no commit adds nothing if
/// its ref name occurred before with no commit. A `REF@CHECKSUM` operand adds
/// nothing if its ref name occurred before with its commit. A `CHECKSUM`
/// operand adds nothing if its commit occurred before with no ref, or if a
/// `REF@CHECKSUM` operand names its commit under the hex form of that commit
/// as `REF`.
///
/// Each ref name with no commit passes the checks of [`check_ref_names`].
/// The pull sends no ref name of a `REF@CHECKSUM` operand in a ref listing
/// request, so such a name passes the ref-name rule alone.
///
/// # Errors
///
/// - [`Error::InvalidRefspec`] if the part after the last `@` of an operand,
///   which is not at position 0, is not 64 lowercase hex characters. The
///   error holds the operand as given.
/// - [`Error::InvalidInput`] if the ref part of an operand is an `@ID:NAME`
///   ref of another collection.
/// - [`Error::InvalidRefspec`] if a ref part that starts with `@` is not an
///   `@ID:NAME` ref that [`Ref`] reads, or if the ref name of a
///   `REF@CHECKSUM` operand fails the ref-name rule. The error holds the
///   operand as given.
/// - The errors of [`check_ref_names`].
fn collection_names(collection_id: &str, names: &[String]) -> Result<Operands> {
    let mut out = Operands::default();
    let mut seen = HashSet::new();
    let mut seen_bare = HashSet::new();
    for given in names {
        let (r, commit) = match Operand::parse(given)? {
            Operand::Commit(commit) => {
                if seen_bare.insert(commit) {
                    out.bare.push(commit);
                }
                continue;
            }
            Operand::Name(r) => (r, None),
            Operand::NameAt { name, commit } => (name, Some(commit)),
        };
        let name = if r.starts_with('@') {
            match r.parse::<Ref>() {
                Ok(Ref::Collection { id, name }) if id == collection_id => name,
                Ok(Ref::Collection { .. }) => {
                    return Err(Error::InvalidInput(format!(
                        "the ref {given} is not a ref of the collection {collection_id}"
                    )));
                }
                _ => return Err(Error::InvalidRefspec(given.clone())),
            }
        } else {
            r.to_owned()
        };
        if commit.is_some() && !is_ref_path(&name) {
            return Err(Error::InvalidRefspec(given.clone()));
        }
        if seen.insert((name.clone(), commit)) {
            out.refs.push(RefOperand {
                given: given.clone(),
                name,
                commit,
            });
        }
    }
    let plain: Vec<&str> = out
        .refs
        .iter()
        .filter(|operand| operand.commit.is_none())
        .map(|operand| operand.name.as_str())
        .collect();
    check_ref_names(collection_id, &plain)?;
    // The operand that writes a ref wins over the operand `CHECKSUM` of the
    // same commit, when the name of that ref is the hex form of the commit.
    let own_name: HashSet<Checksum> = out
        .refs
        .iter()
        .filter_map(|operand| {
            operand
                .commit
                .filter(|commit| operand.name == commit.to_hex())
        })
        .collect();
    out.bare.retain(|commit| !own_name.contains(commit));
    Ok(out)
}

/// Checks the collection id `collection_id` of a pull or a listing of
/// collection refs.
///
/// # Errors
///
/// - [`Error::InvalidInput`] if `collection_id` fails
///   [`is_valid_collection_id`]: the
///   collection-id rule or the length limit.
fn check_collection_id(collection_id: &str) -> Result<()> {
    if !is_valid_collection_id(collection_id) {
        return Err(Error::InvalidInput(format!(
            "invalid collection id: {collection_id}"
        )));
    }
    Ok(())
}

/// Checks the ref names `names` of a pull or a listing of the collection
/// `collection_id`: first the ref-name rule of each name, then the size of
/// each name in a ref listing request.
///
/// # Errors
///
/// - [`Error::InvalidRefspec`] if a name is not a valid ref name.
/// - [`Error::InvalidInput`] if a ref listing request cannot hold a name
///   alone ([`check_listing_name`]).
fn check_ref_names<S: AsRef<str>>(collection_id: &str, names: &[S]) -> Result<()> {
    for name in names {
        check_ref_path(name.as_ref())?;
    }
    for name in names {
        check_listing_name(collection_id, name.as_ref())?;
    }
    Ok(())
}

/// Checks that a ref listing request of the collection `id` can hold the
/// valid ref name `name` alone.
///
/// The entry `ID/NAME` must have at most [`MAX_REF_ENTRY_LEN`] bytes and at
/// most [`MAX_REF_ENTRY_PARTS`] parts. The id holds no `/`, so it adds one
/// part. The request target of the name alone over HTTP must be at most
/// [`MAX_LISTING_TARGET`] bytes. The entry `NAME` is shorter than `ID/NAME`.
///
/// # Errors
///
/// - [`Error::InvalidInput`] if a limit refuses the name.
fn check_listing_name(id: &str, name: &str) -> Result<()> {
    let entry_len = id.len() + 1 + name.len();
    let parts = 1 + name.split('/').count();
    if entry_len > MAX_REF_ENTRY_LEN
        || parts > MAX_REF_ENTRY_PARTS
        || name_cost(id, name) > LISTING_BUDGET
    {
        return Err(Error::InvalidInput(format!(
            "the ref name '{name}' is too long for a ref listing request of the collection \
             '{id}'"
        )));
    }
    Ok(())
}

/// Returns the length of `value` in the query of a ref listing request.
///
/// Each byte outside `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, and `~` is `%XX`,
/// as [`PullSession::fetch_refs`] writes it.
fn encoded_len(value: &str) -> usize {
    value
        .bytes()
        .map(|byte| {
            if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
                1
            } else {
                3
            }
        })
        .sum()
}

/// Returns the bytes that the name `name` adds to the query of an HTTP ref
/// listing request of the collection `id`.
///
/// These are the pairs `pattern=NAME` and `collection=ID/NAME`, each with
/// its value encoded and the `&` before it.
fn name_cost(id: &str, name: &str) -> usize {
    let pattern = "pattern=".len() + encoded_len(name);
    let collection = "collection=".len() + encoded_len(id) + encoded_len("/") + encoded_len(name);
    pattern + collection + 2
}

/// Asks the remote of `candidate` for the commit of each ref of `names` in
/// the collection `id`, or of each ref of the collection if `names` is
/// empty, and for each commit of `commits`.
///
/// If `read_refs` is `false`, the probe reads no ref, and its result lists
/// none. The probe then asks for the commits alone.
///
/// The probe opens a session. If the probe fails, it ends the session. If
/// the probe succeeds, it gives the session back for the pull. The session
/// of a local candidate is the open repository at its `file://` address.
///
/// [`find_refs`] calls the probe for each candidate.
async fn probe(
    candidate: &Candidate<'_>,
    id: &str,
    names: &[&str],
    read_refs: bool,
    commits: &[Checksum],
) -> Result<Probed> {
    let connection = match candidate.transport.open().await? {
        Session::Remote(connection) => connection,
        Session::Local(src) => {
            let (ListedRefs { listed, skipped }, summary, summary_dict) = if read_refs {
                let verification =
                    Verification::from_trust(candidate.trust.clone()).reading_crls(&candidate.repo);
                let (refs, summary) = probe_local(&src, &verification, id, names).await?;
                (refs, summary, verification.summary_dict())
            } else {
                (ListedRefs::default(), None, None)
            };
            return Ok(Probed {
                listed,
                skipped,
                summary,
                summary_dict,
                commits: local_commits(&src, commits).await?,
                session: Some(Session::Local(src)),
            });
        }
    };
    let http = matches!(connection.session, PullSession::Http(_));
    // The probe reads files that a pull reads before its count starts, so it
    // counts no byte.
    let source = RemoteSource::new(connection, Vec::new());
    let probed = async {
        let (ListedRefs { listed, skipped }, summary, summary_dict) = if read_refs {
            let verification =
                Verification::from_trust(candidate.trust.clone()).reading_crls(&candidate.repo);
            let (refs, summary) = probe_source(&source, &verification, id, names, http).await?;
            (refs, summary, verification.summary_dict())
        } else {
            (ListedRefs::default(), None, None)
        };
        let commits = served_commits(&source, commits).await?;
        Ok((listed, skipped, summary, summary_dict, commits))
    }
    .await;
    match probed {
        Ok((listed, skipped, summary, summary_dict, commits)) => Ok(Probed {
            listed,
            skipped,
            summary,
            summary_dict,
            commits,
            session: Some(Session::Remote(source.into_connection())),
        }),
        Err(e) => source.finish(Err(e)).await,
    }
}

/// Returns each commit of `commits` that `source` serves, with its
/// timestamp.
///
/// The call requests each commit object, one at a time, under the size cap
/// of a metadata object. A commit that the remote does not serve is absent
/// from the result. Over HTTP, a 403, a 404, and a 410 mark a commit absent.
/// The call hashes the bytes of each other commit against its name and reads
/// its timestamp, on the blocking pool, and drops the bytes before the next
/// request.
///
/// # Errors
///
/// - The errors of a request that fails for another cause than an absent
///   object.
/// - [`Error::ChecksumMismatch`] if the bytes do not hash to the name of the
///   commit.
/// - [`Error::Core`] if the bytes hold no timestamp.
async fn served_commits(
    source: &RemoteSource,
    commits: &[Checksum],
) -> Result<Vec<(Checksum, u64)>> {
    let mut served = Vec::new();
    for commit in commits {
        let path = object_path(commit, ObjectType::Commit);
        let Some(bytes) = source
            .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
            .await?
        else {
            continue;
        };
        let commit = *commit;
        let timestamp = ostrya_rt::unblock(move || {
            check_hash(&commit, &bytes)?;
            Ok::<_, Error>(Commit::parse_timestamp(&bytes)?)
        })
        .await?;
        served.push((commit, timestamp));
    }
    Ok(served)
}

/// Returns each commit of `commits` that the local repository `src` holds,
/// with its timestamp.
///
/// The call reads each commit one time, on the blocking pool, under the size
/// cap of a metadata object, and drops its bytes before it reads the next
/// commit. A commit that `src` does not hold is absent from the result. The
/// call hashes no commit: the pull from `src` reads each commit again, and
/// hashes it under [`UNTRUSTED`](PullFlags::UNTRUSTED).
async fn local_commits(src: &Repo, commits: &[Checksum]) -> Result<Vec<(Checksum, u64)>> {
    if commits.is_empty() {
        return Ok(Vec::new());
    }
    let src = src.clone();
    let commits = commits.to_vec();
    ostrya_rt::unblock(move || {
        let mut held = Vec::new();
        for commit in commits {
            match src.load_object_bytes_blocking(ObjectType::Commit, &commit) {
                Ok(bytes) => held.push((commit, Commit::parse_timestamp(&bytes)?)),
                Err(Error::ObjectNotFound { .. }) => {}
                Err(e) => return Err(e),
            }
        }
        Ok(held)
    })
    .await
}

/// The find step of a collection pull: probes each of `candidates` for the
/// refs of `names` in the collection `id`, or for each ref of the collection
/// if `names` is empty, and for the commits `commits`.
///
/// The step probes the candidates one at a time, in their order, through
/// [`probe`]. After each probe, and before the next one, it calls
/// `on_probed` with the candidate and the result of its probe. `on_probed`
/// can change the result, for example to take the skipped names out of it.
///
/// The step asks a candidate only for the commits that no earlier candidate
/// serves. So the first candidate that serves a commit is the one candidate
/// whose result holds it. If `read_refs` is `false`, the probes read no ref,
/// and the step stops when no commit is left to find. It then opens no
/// session to the candidates that follow, and it ends the session of a
/// candidate that serves no commit before the next probe.
///
/// The result holds the result of each candidate that the step probed, at
/// the position of the candidate: the [`Probed`] of a candidate that
/// answered, or the error that skips the candidate.
async fn find_refs(
    candidates: &[Candidate<'_>],
    id: &str,
    names: &[&str],
    read_refs: bool,
    commits: &[Checksum],
    mut on_probed: impl FnMut(&Candidate<'_>, &mut Result<Probed>),
) -> Vec<Result<Probed>> {
    let mut wanted = commits.to_vec();
    let mut found = Vec::with_capacity(candidates.len());
    for candidate in candidates {
        if !read_refs && wanted.is_empty() {
            break;
        }
        let mut probed = Box::pin(probe(candidate, id, names, read_refs, &wanted)).await;
        if let Ok(probed) = &mut probed {
            let served: HashSet<Checksum> =
                probed.commits.iter().map(|(commit, _)| *commit).collect();
            wanted.retain(|commit| !served.contains(commit));
            // With commit operands alone, the pull reads nothing more from a
            // candidate that serves no commit.
            if !read_refs && served.is_empty() {
                end_sessions(probed.session.take()).await;
            }
        }
        on_probed(candidate, &mut probed);
        found.push(probed);
    }
    found
}

/// Takes the skipped names out of the probe `probed` of `candidate`, and
/// gives `on_event` a [`RefSkipped`](CollectionPullEvent::RefSkipped) event
/// for each of them, in the listed order.
///
/// Without `on_event`, the function drops the names. So the names do not
/// stay in memory while the find step probes the next candidate.
fn report_skipped_refs(
    on_event: &mut Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
    candidate: &Candidate<'_>,
    probed: &mut Probed,
) {
    let skipped = std::mem::take(&mut probed.skipped);
    let Some(on_event) = on_event.as_mut() else {
        return;
    };
    for name in skipped {
        on_event(CollectionPullEvent::RefSkipped {
            remote: candidate.name.to_owned(),
            name,
        });
    }
}

/// The refs and the skipped names that a probe read, and the `summary` if
/// the refs come from it.
type Refs = (ListedRefs, Option<Arc<Vec<u8>>>);

/// Reads the refs of `names` in the collection `id` from the local
/// repository `src`, or each ref of the collection if `names` is empty.
///
/// If `verification` checks the summary, the refs come from the `summary`
/// of `src`, after the check of the summary and its `summary.sig`, as from a
/// remote. [`read_checked_local_summary`] reads these files under the size
/// cap of a summary, with no symlink followed. The result then also holds
/// the bytes of the checked summary, so the pull from the candidate does not
/// read or check the summary again.
///
/// Otherwise the refs come from the ref files of `src`, through
/// [`Repo::list_collection_refs_in`]. So the collection id of `src` puts its
/// `refs/heads` refs in the collection, and the probe reads only the
/// directories that the names can reach. The probe puts each ref whose name
/// fails the ref-name rule in the skipped names before it reads a commit. The
/// timestamp of each other ref is the timestamp of its commit in `src`. The
/// probe reads each commit one time, on the blocking pool, under the size cap
/// of a metadata object, and drops its bytes before it reads the next commit.
///
/// Otherwise the result holds the refs and the skipped names alone.
///
/// # Errors
///
/// - [`Error::Signature`] if the summary fails the policy, or if `src` has
///   no `summary` or no `summary.sig` under the policy.
/// - [`Error::InvalidFormat`] if the `summary` or the `summary.sig` of `src`
///   is not a regular file or is larger than the size cap of a summary, or if
///   a ref of the summary has no `ostree.commit.timestamp` of type `t`.
/// - [`Error::Core`] or [`Error::InvalidFormat`] if the summary does not
///   parse.
/// - [`Error::ObjectNotFound`] if `src` does not hold the commit of a ref.
/// - [`Error::Io`] if a directory or a ref file that the names reach cannot
///   be read, and the errors of the read of a ref file or a commit.
async fn probe_local(
    src: &Repo,
    verification: &Verification,
    id: &str,
    names: &[&str],
) -> Result<Refs> {
    if verification.checks_summary() {
        let (Some(bytes), _) = read_checked_local_summary(src, verification, false, false).await?
        else {
            unreachable!("the summary check needs a summary");
        };
        let (_, refs) = parse_refs(Arc::clone(&bytes), id, names).await?;
        return Ok((refs, Some(bytes)));
    }
    let refs = src
        .list_collection_refs_in(id, &RefSelector::parse(names.iter().copied())?)
        .await?;
    let (refs, invalid): (Vec<_>, Vec<_>) =
        refs.into_iter().partition(|(name, _)| is_ref_path(name));
    let skipped = invalid.into_iter().map(|(name, _)| name).collect();
    let src = src.clone();
    let listed = ostrya_rt::unblock(move || {
        let mut timestamps: HashMap<Checksum, u64> = HashMap::new();
        refs.into_iter()
            .map(|(name, commit)| {
                let timestamp = match timestamps.entry(commit) {
                    Entry::Occupied(known) => *known.get(),
                    Entry::Vacant(slot) => {
                        let bytes = src.load_object_bytes_blocking(ObjectType::Commit, &commit)?;
                        *slot.insert(Commit::parse_timestamp(&bytes)?)
                    }
                };
                Ok(Listed {
                    name,
                    commit,
                    timestamp,
                })
            })
            .collect::<Result<Vec<Listed>>>()
    })
    .await?;
    Ok((ListedRefs { listed, skipped }, None))
}

/// Reads the refs of `names` in the collection `id` from `source`, or each
/// ref of the collection if `names` is empty.
///
/// If `verification` checks the summary, the refs come from the summary,
/// after its check. A bucket repository serves no ref listing, so its refs
/// come from its summary. Otherwise they come from the ref listing, or from
/// the summary of a remote with no ref listing. `http` applies the byte limit
/// of an HTTP request to the listing requests.
async fn probe_source(
    source: &RemoteSource,
    verification: &Verification,
    id: &str,
    names: &[&str],
    http: bool,
) -> Result<Refs> {
    // No signature covers the ref listing. So under a policy that covers the
    // summary, the summary alone tells the refs. A bucket repository serves
    // no ref listing.
    if verification.checks_summary() || source.has_bucket() {
        return summary_refs(source, verification, id, names).await;
    }
    if names.is_empty() {
        return every_ref(source, verification, id).await;
    }
    let mut listed = ListedRefs::default();
    for chunk in listing_chunks(id, names, http) {
        let refs = RefSelector::parse(chunk.iter().copied())?;
        let entries: Vec<String> = chunk.iter().map(|name| format!("{id}/{name}")).collect();
        let collections = RefSelector::parse(entries.iter().map(String::as_str))?;
        let Some(bytes) = read_listing(source, &refs, Some(&collections)).await? else {
            return summary_refs(source, verification, id, names).await;
        };
        let (_, parsed) = parse_refs(Arc::new(bytes), id, chunk).await?;
        listed.listed.extend(parsed.listed);
        listed.skipped.extend(parsed.skipped);
    }
    Ok((listed, None))
}

/// Reads each ref of the collection `id` from the ref listing of `source`,
/// or from the summary of a remote with no ref listing.
///
/// The first request selects no local ref, with the entry `!**`, and each
/// ref of the collection, with the entry `ID/**`. If the listing states `id`
/// as the collection id of the remote, the refs of the collection are its
/// local refs. A second request then selects each local ref, and no
/// collection ref. So a remote of another collection sends no local ref. The
/// skipped names come from the listing of the refs that the call returns.
async fn every_ref(source: &RemoteSource, verification: &Verification, id: &str) -> Result<Refs> {
    let no_local = RefSelector::parse(["!**"])?;
    let entry = format!("{id}/**");
    let collections = RefSelector::parse([entry.as_str()])?;
    let Some(bytes) = read_listing(source, &no_local, Some(&collections)).await? else {
        return summary_refs(source, verification, id, &[]).await;
    };
    let (own, listed) = parse_refs(Arc::new(bytes), id, &[]).await?;
    if !own {
        return Ok((listed, None));
    }
    let each_local = RefSelector::parse(std::iter::empty())?;
    let Some(bytes) = read_listing(source, &each_local, None).await? else {
        return summary_refs(source, verification, id, &[]).await;
    };
    Ok((parse_refs(Arc::new(bytes), id, &[]).await?.1, None))
}

/// Reads the ref listing of `refs` and `collections` from `source`, or
/// returns `None` if the remote serves no ref listing.
///
/// An HTTP remote serves no listing when it answers with a status from 400
/// to 499. [`RemoteSource::ref_listing`] gives `None` for 403, 404, and 410.
/// A static server answers 404, an ostrya server answers 403 to a client
/// that it refuses, and another server can refuse a query that it does not
/// know with another status of the range.
async fn read_listing(
    source: &RemoteSource,
    refs: &RefSelector,
    collections: Option<&RefSelector>,
) -> Result<Option<Vec<u8>>> {
    match source.ref_listing(refs, collections).await {
        Err(Error::HttpStatus {
            status: 400..=499, ..
        }) => Ok(None),
        other => other,
    }
}

/// Reads the refs of `names` in the collection `id` from the summary of
/// `source`, or each ref of the collection if `names` is empty, and returns
/// them with the summary.
///
/// If `verification` checks the summary, the call reads `summary.sig` too,
/// and verifies the summary before it reads the refs. Otherwise it reads
/// `summary` alone. If no policy applies to its summary, a remote with no
/// summary lists no ref. A bucket repository with no summary fails the call,
/// because its summary is the one source of its refs.
async fn summary_refs(
    source: &RemoteSource,
    verification: &Verification,
    id: &str,
    names: &[&str],
) -> Result<Refs> {
    let summary = if verification.checks_summary() {
        let (summary, signature) = source.summary_files().await?;
        let summary = summary.map(Arc::new);
        verification
            .check_summary(summary.as_ref(), signature)
            .await?;
        summary
    } else {
        source.read_root(SUMMARY_FILE).await?.map(Arc::new)
    };
    let Some(bytes) = summary else {
        if source.has_bucket() {
            return Err(Error::Pull(
                "the bucket repository has no summary, and the summary is the one source of \
                 the refs of a bucket repository"
                    .into(),
            ));
        }
        return Ok((ListedRefs::default(), None));
    };
    let (_, listed) = parse_refs(Arc::clone(&bytes), id, names).await?;
    Ok((listed, Some(bytes)))
}

/// Parses the listing or the summary `bytes`, and returns the refs of the
/// collection `id` that `names` names, or each ref of the collection if
/// `names` is empty, as [`collection_refs`] returns them.
///
/// The result also tells if the bytes state `id` as the collection id of the
/// remote. A summary can be as large as its read cap, so the parse runs on
/// the blocking pool.
async fn parse_refs(bytes: Arc<Vec<u8>>, id: &str, names: &[&str]) -> Result<(bool, ListedRefs)> {
    let id = id.to_owned();
    let wanted: Option<HashSet<String>> =
        (!names.is_empty()).then(|| names.iter().map(|name| (*name).to_owned()).collect());
    ostrya_rt::unblock(move || collection_refs(&bytes, &id, wanted.as_ref())).await
}

/// Returns the refs of the collection `id` in the listing or the summary
/// `bytes` that `wanted` names, or each ref of the collection if `wanted` is
/// `None`, and tells if the bytes state `id` as the collection id of the
/// remote.
///
/// The call reads the global metadata first. If it states `id` as the
/// collection id, the refs are in field 0, and the call parses field 0.
/// Otherwise they are in the entry of `id` of the collection map, and the
/// call parses that entry alone and leaves field 0 undecoded. A name that
/// occurs again keeps its first entry.
///
/// The call puts each name that fails the ref-name rule in the skipped names,
/// one time, and reads no timestamp of its ref.
///
/// # Errors
///
/// - [`Error::Core`] or [`Error::InvalidFormat`] if the bytes do not parse,
///   or if the collection map is malformed.
/// - [`Error::InvalidFormat`] if a ref with a valid name has no
///   `ostree.commit.timestamp` of type `t`.
pub(crate) fn collection_refs(
    bytes: &[u8],
    id: &str,
    wanted: Option<&HashSet<String>>,
) -> Result<(bool, ListedRefs)> {
    let metadata = Summary::parse_metadata(bytes)?;
    let own = summary_collection_id(&metadata) == Some(id);
    let entries = if own {
        drop(metadata);
        parse_ref_list(bytes)?
    } else {
        collection_map_refs(&metadata, id)?
    };
    let mut seen = HashSet::new();
    let mut out = ListedRefs::default();
    for entry in &entries {
        if wanted.is_some_and(|wanted| !wanted.contains(&entry.name))
            || !seen.insert(entry.name.as_str())
        {
            continue;
        }
        if !is_ref_path(&entry.name) {
            out.skipped.push(entry.name.clone());
            continue;
        }
        out.listed.push(Listed {
            name: entry.name.clone(),
            commit: entry.commit,
            timestamp: listed_timestamp(entry)?,
        });
    }
    Ok((own, out))
}

/// Returns the `ostree.commit.timestamp` of a listed ref.
///
/// The value is a big-endian `t`, so one byte swap of the decoded number
/// gives the timestamp.
fn listed_timestamp(entry: &SummaryRef) -> Result<u64> {
    match entry
        .metadata
        .dict_get(COMMIT_TIMESTAMP_KEY)
        .and_then(Value::as_variant)
    {
        Some((ty, Value::U64(raw))) if ty.signature() == "t" => Ok(raw.swap_bytes()),
        _ => Err(Error::InvalidFormat(format!(
            "the ref '{}' is listed with no {COMMIT_TIMESTAMP_KEY} of type t",
            entry.name
        ))),
    }
}

/// Splits `names` into the names of each ref listing request.
///
/// Each name adds two entries to a request: the name, and the name under the
/// collection id `id`. A request holds at most [`MAX_REF_PATTERNS`] entries.
/// If `http` is `true`, the pairs of the names of a request also fill at
/// most [`LISTING_BUDGET`] bytes, so the request target is at most
/// [`MAX_LISTING_TARGET`] bytes. A stream session has no such limit.
/// [`check_listing_name`] makes sure that each name fits in a request alone.
fn listing_chunks<'n, 'a>(id: &str, names: &'n [&'a str], http: bool) -> Vec<&'n [&'a str]> {
    let mut chunks = Vec::new();
    let mut start = 0;
    let mut cost = 0;
    for (index, name) in names.iter().enumerate() {
        let this = if http { name_cost(id, name) } else { 0 };
        if index > start
            && (2 * (index - start) >= MAX_REF_PATTERNS || cost + this > LISTING_BUDGET)
        {
            chunks.push(&names[start..index]);
            start = index;
            cost = 0;
        }
        cost += this;
    }
    if start < names.len() {
        chunks.push(&names[start..]);
    }
    chunks
}

/// Selects the remote of each ref: the remote that lists the newest commit,
/// by the listed timestamp, with a tie to the earlier remote.
///
/// `answers` holds the refs that each candidate listed, in the order of the
/// candidates, and `None` for a candidate that the pull skipped. The result
/// follows the order of `names`. If `names` is empty, the result holds each
/// listed ref, in byte-wise order of the names.
///
/// # Errors
///
/// - [`Error::Pull`] if each candidate was skipped.
/// - [`Error::Pull`] if no candidate lists a name of `names`.
/// - [`Error::Pull`] if `names` is empty and no candidate lists a ref.
fn select(id: &str, names: &[&str], answers: &[Option<Vec<Listed>>]) -> Result<Vec<Selected>> {
    if answers.iter().all(Option::is_none) {
        return Err(none_answered(id));
    }
    let mut best: HashMap<&str, (usize, &Listed)> = HashMap::new();
    for (remote, listed) in answers.iter().enumerate() {
        for listed in listed.iter().flatten() {
            best.entry(listed.name.as_str())
                .and_modify(|current| {
                    if listed.timestamp > current.1.timestamp {
                        *current = (remote, listed);
                    }
                })
                .or_insert((remote, listed));
        }
    }
    let order: Vec<&str> = if names.is_empty() {
        if best.is_empty() {
            return Err(Error::Pull(format!(
                "no remote lists a ref of collection '{id}'"
            )));
        }
        let mut all: Vec<&str> = best.keys().copied().collect();
        all.sort_unstable();
        all
    } else {
        names.to_vec()
    };
    order
        .into_iter()
        .map(|name| match best.get(name) {
            Some((remote, listed)) => Ok(Selected {
                remote: *remote,
                listed: (*listed).clone(),
            }),
            None => Err(Error::Pull(format!(
                "no remote of collection '{id}' lists the ref '{name}'"
            ))),
        })
        .collect()
}

/// Returns the error of a pull of the collection `id` whose candidates were
/// all skipped.
fn none_answered(id: &str) -> Error {
    Error::Pull(format!("no remote of collection '{id}' answered"))
}

/// Adds the counts of `pulled` to `total`. The run time stays as it is.
fn add_stats(total: &mut PullStats, pulled: &PullStats) {
    total.metadata_imported += pulled.metadata_imported;
    total.content_imported += pulled.content_imported;
    total.content_bytes_written += pulled.content_bytes_written;
    total.content_bytes_unpacked += pulled.content_bytes_unpacked;
    total.metadata_fetched += pulled.metadata_fetched;
    total.content_fetched += pulled.content_fetched;
    total.delta_parts += pulled.delta_parts;
    total.bytes_transferred += pulled.bytes_transferred;
}

/// A compile-time check that the futures of a collection pull and of a
/// listing of collection refs are `Send`, and that the result of a pull is
/// `Send` and `Sync`.
const _: fn() = || {
    fn assert_send<T: Send>(_: &T) {}
    fn assert_send_sync<T: Send + Sync>() {}
    let _ = |repo: &Repo| {
        assert_send(&repo.pull_collection(
            "org.example.Os",
            &["origin"],
            CollectionPullOptions::default(),
        ))
    };
    let _ = |repo: &Repo| {
        assert_send(&repo.remote_list_collection_refs("origin", "org.example.Os", &[]))
    };
    let _ = |repo: &Repo| {
        assert_send(&repo.remote_list_collection_refs_with(
            "origin",
            "org.example.Os",
            &[],
            EndpointOverrides::default(),
            None,
        ))
    };
    assert_send_sync::<CollectionPullStats>();
    assert_send_sync::<CollectionPullEvent>();
};

#[cfg(test)]
mod tests {
    use std::path::Path;

    use ostrya_core::{Type, to_bytes};

    use super::*;
    use crate::fetch::FetcherOptions;
    use crate::pull::import_seam;
    use crate::summary::COLLECTION_ID_KEY;

    /// The transport of an S3 endpoint builds its fetcher and connects to no
    /// server. Each session that it opens holds a bucket client.
    #[cfg(feature = "s3")]
    #[test]
    fn the_transport_of_an_s3_endpoint_sends_no_request() {
        use crate::remote::s3::{Address, Credentials, Location, S3Endpoint};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let location = Location::new(
            Address::parse("s3://bkt/repo").unwrap(),
            "us-east-1",
            Some(&url),
            None,
        )
        .unwrap();
        let credentials =
            Credentials::new("AKIDEXAMPLE".into(), "SECRETEXAMPLE".into(), None).unwrap();
        let mut s3 = S3Endpoint::new(location, credentials);
        s3.http.allow_cleartext_credentials = true;
        s3.http.proxy = crate::fetch::Proxy::None;
        ostrya_rt::block_on(async {
            let transport = Transport::new(Endpoint::S3(s3), None).await.unwrap();
            assert!(matches!(transport, Transport::S3(..)));
            let Session::Remote(connection) = transport.open().await.unwrap() else {
                panic!("an S3 transport opens a remote session");
            };
            assert!(matches!(connection.session, PullSession::Http(_)));
            assert!(connection.bucket.is_some());
        });
        assert_eq!(
            listener.accept().map(drop).map_err(|e| e.kind()),
            Err(std::io::ErrorKind::WouldBlock),
            "the transport connects to no server"
        );
    }

    /// A pull of collection refs resolves a remote at an `s3://` address,
    /// and so applies the rules of the S3 endpoint before its first request.
    /// The endpoint of the remote here is `http://`, and the pull does not
    /// allow cleartext credentials. So the pull fails with
    /// [`Error::InvalidInput`] and connects to no server, whatever the AWS
    /// environment and files hold: with no key pair, and with a key pair.
    #[cfg(feature = "s3")]
    #[test]
    fn a_collection_pull_resolves_an_s3_remote() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let dir = std::env::temp_dir().join(format!(
            "ostrya-collection-s3-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        ostrya_rt::block_on(async {
            drop(
                Repo::create(&dir, crate::CreateOptions::new(crate::RepoMode::Archive))
                    .await
                    .unwrap(),
            );
            let mut config = std::fs::read_to_string(dir.join("config")).unwrap();
            config.push_str(&format!(
                "\n[remote \"bkt\"]\npull-url=s3://bkt/repo\ns3-endpoint=http://{}\n",
                listener.local_addr().unwrap()
            ));
            std::fs::write(dir.join("config"), config).unwrap();
            let repo = Repo::open(&dir).await.unwrap();
            let mut opts = CollectionPullOptions::default();
            opts.pull.refs = vec!["exampleos/stable".to_owned()];
            match repo.pull_collection("org.example.Os", &["bkt"], opts).await {
                Err(Error::InvalidInput(_)) => {}
                Err(e) => panic!("{e:?}"),
                Ok(_) => panic!("a collection pull over a refused endpoint"),
            }
        });
        assert_eq!(
            listener.accept().map(drop).map_err(|e| e.kind()),
            Err(std::io::ErrorKind::WouldBlock),
            "the refusal connects to no server"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

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

    /// The operands of a collection pull split into the refs and the commits
    /// with no ref. Both forms of a ref give one ref name. An operand that
    /// occurs again adds nothing, and a ref name with two commits stays two
    /// operands. The operand `CHECKSUM` gives way to the operand
    /// `CHECKSUM@CHECKSUM` of the same commit.
    #[test]
    fn the_names_of_a_collection_pull_split_into_refs_and_commits() {
        let id = "org.example.Os";
        let (c1, c2, c3) = (csum(1), csum(2), csum(3));
        let given: Vec<String> = [
            "os/a".to_owned(),
            format!("@{id}:os/a"),
            format!("os/a@{c1}"),
            format!("@{id}:os/a@{c1}"),
            format!("@{id}:os/a@{c2}"),
            c1.to_hex(),
            c3.to_hex(),
            c1.to_hex(),
            format!("{c3}@{c3}"),
            format!("{c2}@{c3}"),
            format!("@{id}:os/b"),
        ]
        .into();
        let operands = collection_names(id, &given).unwrap();
        let refs: Vec<(&str, &str, Option<Checksum>)> = operands
            .refs
            .iter()
            .map(|r| (r.given.as_str(), r.name.as_str(), r.commit))
            .collect();
        let (c2_hex, c3_hex) = (c2.to_hex(), c3.to_hex());
        assert_eq!(
            refs,
            [
                ("os/a", "os/a", None),
                (given[2].as_str(), "os/a", Some(c1)),
                (given[4].as_str(), "os/a", Some(c2)),
                (given[8].as_str(), c3_hex.as_str(), Some(c3)),
                (given[9].as_str(), c2_hex.as_str(), Some(c3)),
                (given[10].as_str(), "os/b", None),
            ]
        );
        assert_eq!(operands.bare, [c1]);

        for bad in [format!("os/a@{}", &c1.to_hex()[..10]), format!("a:b@{c1}")] {
            match collection_names(id, std::slice::from_ref(&bad)) {
                Err(Error::InvalidRefspec(got)) => assert_eq!(got, bad),
                other => panic!("{bad}: {other:?}"),
            }
        }
        let other = format!("@org.example.Other:os/a@{c1}");
        assert!(matches!(
            collection_names(id, &[other]),
            Err(Error::InvalidInput(_))
        ));
    }

    fn listed(name: &str, byte: u8, timestamp: u64) -> Listed {
        Listed {
            name: name.to_owned(),
            commit: csum(byte),
            timestamp,
        }
    }

    /// Test refs, each `(name, commit byte, timestamp)`.
    type TestRefs<'a> = &'a [(&'a str, u8, u64)];

    /// Returns a ref entry `(s, (t, ay, a{sv}))` with the metadata dict
    /// `metadata`.
    fn ref_value(name: &str, byte: u8, metadata: Value) -> Value {
        Value::Tuple(vec![
            Value::Str(name.to_owned()),
            Value::Tuple(vec![
                Value::U64(1),
                Value::Bytes(csum(byte).as_bytes().to_vec()),
                metadata,
            ]),
        ])
    }

    /// Returns the ref entries of `refs`, each with its timestamp.
    fn ref_values(refs: TestRefs<'_>) -> Vec<Value> {
        refs.iter()
            .map(|(name, byte, ts)| {
                let timestamp = Value::Tuple(vec![
                    Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
                    Value::Variant(Box::new((
                        Type::parse("t").unwrap(),
                        Value::U64(ts.swap_bytes()),
                    ))),
                ]);
                ref_value(name, *byte, Value::Array(vec![timestamp]))
            })
            .collect()
    }

    /// Returns the bytes of a summary with the ref entries `field0` in field
    /// 0, the refs `map` under their ids in the collection map, and `own` as
    /// its collection id.
    fn summary_of(field0: Vec<Value>, map: &[(&str, TestRefs<'_>)], own: Option<&str>) -> Vec<u8> {
        let mut metadata = Vec::new();
        if !map.is_empty() {
            let entries = map
                .iter()
                .map(|(id, refs)| {
                    Value::Tuple(vec![
                        Value::Str((*id).to_owned()),
                        Value::Array(ref_values(refs)),
                    ])
                })
                .collect();
            metadata.push(Value::Tuple(vec![
                Value::Str("ostree.summary.collection-map".to_owned()),
                Value::Variant(Box::new((
                    Type::parse("a{sa(s(taya{sv}))}").unwrap(),
                    Value::Array(entries),
                ))),
            ]));
        }
        if let Some(own) = own {
            metadata.push(Value::Tuple(vec![
                Value::Str(COLLECTION_ID_KEY.to_owned()),
                Value::Variant(Box::new((
                    Type::parse("s").unwrap(),
                    Value::Str(own.to_owned()),
                ))),
            ]));
        }
        let value = Value::Tuple(vec![Value::Array(field0), Value::Array(metadata)]);
        to_bytes(&Type::parse("(a(s(taya{sv}))a{sv})").unwrap(), &value).unwrap()
    }

    /// Returns the bytes of a summary with the refs `field0` in field 0, the
    /// refs `map` under their ids in the collection map, and `own` as its
    /// collection id.
    fn summary(field0: TestRefs<'_>, map: &[(&str, TestRefs<'_>)], own: Option<&str>) -> Vec<u8> {
        summary_of(ref_values(field0), map, own)
    }

    /// The sessions of the remotes with no selected ref leave their slots,
    /// and the summaries of these remotes are dropped. The slots of the
    /// selected remotes keep their sessions and their summaries.
    #[test]
    fn the_unselected_remotes_leave_their_sessions_and_summaries() {
        let mut sessions = vec![Some('a'), None, Some('c'), Some('d')];
        let mut summaries = vec![Some(1), None, Some(3), Some(4)];
        let taken = take_unselected(&mut sessions, &mut summaries, |index| index == 2);
        assert_eq!(taken, ['a', 'd']);
        assert_eq!(sessions, [None, None, Some('c'), None]);
        assert_eq!(summaries, [None, None, Some(3), None]);
    }

    /// A summary whose own collection id is the pulled id gives the refs of
    /// field 0, and the collection map is not read for that id.
    #[test]
    fn the_own_collection_reads_field_0() {
        let s = summary(
            &[("os/stable", 1, 10), ("os/next", 2, 20)],
            &[("org.example.Os", &[("os/stable", 9, 99)])],
            Some("org.example.Os"),
        );
        let refs = collection_refs(&s, "org.example.Os", None).unwrap();
        assert!(refs.0);
        assert_eq!(
            refs.1.listed,
            [listed("os/stable", 1, 10), listed("os/next", 2, 20)]
        );
        assert!(refs.1.skipped.is_empty());
    }

    /// Another collection reads the entry of the map, ignores field 0, and
    /// keeps only the wanted names. The entry of another collection is not
    /// parsed, so a malformed entry after the entry of the id is not read.
    #[test]
    fn another_collection_reads_the_map_and_ignores_field_0() {
        let s = summary(
            &[("os/stable", 1, 10)],
            &[
                ("org.example.Other", &[("os/stable", 7, 70)]),
                (
                    "org.example.Os",
                    &[("os/stable", 3, 30), ("os/next", 4, 40)],
                ),
            ],
            Some("org.example.Mine"),
        );
        let wanted: HashSet<String> = ["os/stable".to_owned()].into();
        let refs = collection_refs(&s, "org.example.Os", Some(&wanted)).unwrap();
        assert_eq!(
            refs,
            (
                false,
                ListedRefs {
                    listed: vec![listed("os/stable", 3, 30)],
                    skipped: Vec::new(),
                }
            )
        );
        // A summary with no collection id and no map entry lists nothing.
        let s = summary(&[("os/stable", 1, 10)], &[], None);
        assert_eq!(
            collection_refs(&s, "org.example.Os", None).unwrap(),
            (false, ListedRefs::default())
        );
    }

    /// A ref with no timestamp, or with a timestamp of another type, fails
    /// the read.
    #[test]
    fn a_ref_with_no_valid_timestamp_fails() {
        let no_key = summary_of(
            vec![ref_value("os/stable", 1, Value::Array(Vec::new()))],
            &[],
            Some("org.example.Os"),
        );
        let other_type = summary_of(
            vec![ref_value(
                "os/stable",
                1,
                Value::Array(vec![Value::Tuple(vec![
                    Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
                    Value::Variant(Box::new((Type::parse("u").unwrap(), Value::U32(1)))),
                ])]),
            )],
            &[],
            Some("org.example.Os"),
        );
        for s in [no_key, other_type] {
            assert!(matches!(
                collection_refs(&s, "org.example.Os", None),
                Err(Error::InvalidFormat(_))
            ));
        }
    }

    /// A name that fails the ref-name rule goes to the skipped names one
    /// time, in the listed order, and the other refs stay. The read takes no
    /// timestamp of a skipped ref, so a skipped ref with no timestamp fails
    /// nothing. This is true in field 0 and in the collection map.
    #[test]
    fn a_name_that_fails_the_ref_name_rule_is_skipped() {
        let mut field0 = ref_values(&[
            ("origin:main", 1, 10),
            ("os/stable", 2, 20),
            ("origin:main", 3, 30),
        ]);
        field0.push(ref_value("bad name", 4, Value::Array(Vec::new())));
        let own = summary_of(field0, &[], Some("org.example.Os"));
        let expected = ListedRefs {
            listed: vec![listed("os/stable", 2, 20)],
            skipped: vec!["origin:main".to_owned(), "bad name".to_owned()],
        };
        assert_eq!(
            collection_refs(&own, "org.example.Os", None).unwrap(),
            (true, expected)
        );

        let map = summary(
            &[],
            &[("org.example.Os", &[("os/next", 5, 50), ("a/../b", 6, 60)])],
            None,
        );
        let expected = ListedRefs {
            listed: vec![listed("os/next", 5, 50)],
            skipped: vec!["a/../b".to_owned()],
        };
        assert_eq!(
            collection_refs(&map, "org.example.Os", None).unwrap(),
            (false, expected)
        );
    }

    /// The newest timestamp wins, a tie goes to the earlier remote, and a
    /// skipped remote takes no part.
    #[test]
    fn the_newest_commit_wins_and_a_tie_goes_to_the_earlier_remote() {
        let answers = vec![
            Some(vec![listed("a", 1, 10), listed("b", 2, 20)]),
            None,
            Some(vec![listed("a", 3, 30), listed("b", 4, 20)]),
        ];
        let selected = select("org.example.Os", &["b", "a"], &answers).unwrap();
        assert_eq!(
            selected,
            [
                Selected {
                    remote: 0,
                    listed: listed("b", 2, 20)
                },
                Selected {
                    remote: 2,
                    listed: listed("a", 3, 30)
                },
            ]
        );
    }

    /// With no names, each listed ref is selected, in byte-wise order. A
    /// named ref that no remote lists fails, and so does a pull in which each
    /// remote was skipped. With no names, a pull in which no remote lists a
    /// ref fails.
    #[test]
    fn selection_takes_each_listed_ref_or_fails_a_missing_one() {
        let answers = vec![
            Some(vec![listed("b", 2, 20)]),
            Some(vec![listed("a", 1, 10)]),
        ];
        let names: Vec<String> = select("org.example.Os", &[], &answers)
            .unwrap()
            .into_iter()
            .map(|s| s.listed.name)
            .collect();
        assert_eq!(names, ["a", "b"]);
        let err = select("org.example.Os", &["c"], &answers).unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("'c'") && m.contains("org.example.Os")),
            "{err:?}"
        );
        let err = select("org.example.Os", &["a"], &[None, None]).unwrap_err();
        assert!(matches!(err, Error::Pull(_)), "{err:?}");
        let err = select("org.example.Os", &[], &[Some(Vec::new()), None]).unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m == "no remote lists a ref of collection 'org.example.Os'"),
            "{err:?}"
        );
    }

    /// A long list of names splits into requests of at most the entry limit.
    /// Over HTTP, long names also split by the byte budget. Over a stream
    /// session, the entry limit alone applies.
    #[test]
    fn the_names_split_by_the_entry_limit_and_the_byte_budget() {
        let short: Vec<String> = (0..300).map(|n| format!("r{n}")).collect();
        let short: Vec<&str> = short.iter().map(String::as_str).collect();
        for http in [true, false] {
            let chunks = listing_chunks("org.example.Os", &short, http);
            assert_eq!(
                chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
                [
                    MAX_REF_PATTERNS / 2,
                    MAX_REF_PATTERNS / 2,
                    300 - MAX_REF_PATTERNS
                ]
            );
        }
        // Each long name costs about 8 KiB on the wire, so two fill a
        // request.
        let long = "x".repeat(4000);
        let names = [long.as_str(), long.as_str(), long.as_str(), "a"];
        let chunks = listing_chunks("org.example.Os", &names, true);
        assert_eq!(chunks.iter().map(|c| c.len()).collect::<Vec<_>>(), [2, 2]);
        assert_eq!(listing_chunks("org.example.Os", &names, false).len(), 1);
        assert!(listing_chunks("org.example.Os", &[], true).is_empty());
    }

    /// The byte budget is exact: names whose pairs fill it make a request
    /// target of 16 KiB, which the client sends. One more byte splits the
    /// names into two requests, and the client refuses the one request.
    #[test]
    fn the_byte_budget_matches_the_request_target_of_the_client() {
        ostrya_rt::block_on(async {
            // An id of odd length makes the cost of each name odd, so five
            // names can fill the odd budget.
            let id = "org.example.Oss";
            let mut opts = FetcherOptions::new("http://127.0.0.1:1/");
            opts.max_retries = 0;
            let session = PullSession::Http(Fetcher::new(opts).await.unwrap());
            let fetch = |names: Vec<String>| {
                let session = &session;
                async move {
                    let refs = RefSelector::parse(names.iter().map(String::as_str)).unwrap();
                    let entries: Vec<String> =
                        names.iter().map(|name| format!("{id}/{name}")).collect();
                    let collections =
                        RefSelector::parse(entries.iter().map(String::as_str)).unwrap();
                    session.fetch_refs(&refs, Some(&collections)).await
                }
            };
            let fill = |last: usize| -> Vec<String> {
                let mut names: Vec<String> =
                    (0..4).map(|n| format!("{n}{}", "x".repeat(1616))).collect();
                names.push("y".repeat(last));
                names
            };
            let exact = fill(1619);
            let cost: usize = exact.iter().map(|name| name_cost(id, name)).sum();
            assert_eq!(cost, LISTING_BUDGET);
            let names: Vec<&str> = exact.iter().map(String::as_str).collect();
            assert_eq!(listing_chunks(id, &names, true).len(), 1);
            let sent = fetch(exact.clone()).await;
            assert!(
                !matches!(sent, Err(crate::remote::Error::InvalidInput(_))),
                "{sent:?}"
            );

            let over = fill(1620);
            let names: Vec<&str> = over.iter().map(String::as_str).collect();
            assert_eq!(listing_chunks(id, &names, true).len(), 2);
            let refused = fetch(over.clone()).await;
            assert!(
                matches!(refused, Err(crate::remote::Error::InvalidInput(_))),
                "{refused:?}"
            );
        });
    }

    /// A name whose entry under the id passes the byte limit or the part
    /// limit, or whose request target alone passes 16 KiB, is refused before
    /// the first request. A name at each limit passes.
    #[test]
    fn a_name_that_no_listing_request_can_hold_is_refused() {
        let id = "org.example.Os";
        let at_len = "x".repeat(MAX_REF_ENTRY_LEN - id.len() - 1);
        let over_len = format!("{at_len}x");
        let at_parts = vec!["p"; MAX_REF_ENTRY_PARTS - 1].join("/");
        let over_parts = format!("{at_parts}/p");
        // Each `é` is two bytes, and each byte is `%XX` on the wire.
        let wide = "é".repeat(2000);
        assert!(id.len() + 1 + wide.len() <= MAX_REF_ENTRY_LEN);
        for name in [&at_len, &at_parts] {
            check_listing_name(id, name).unwrap();
        }
        for name in [&over_len, &over_parts, &wide] {
            let err = check_listing_name(id, name).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidInput(m) if m.contains("too long")),
                "{err:?}"
            );
        }
    }

    /// The text of an event escapes each control character.
    #[test]
    fn the_skip_event_escapes_control_characters() {
        let event = CollectionPullEvent::RemoteSkipped {
            remote: "mirror".to_owned(),
            message: "bad\nline".to_owned(),
        };
        assert_eq!(event.to_string(), "remote mirror skipped: bad\\nline");
    }

    /// The text of a ref skip event names the remote and the ref, and
    /// escapes each control character.
    #[test]
    fn the_ref_skip_event_escapes_control_characters() {
        let event = CollectionPullEvent::RefSkipped {
            remote: "mir\tror".to_owned(),
            name: "origin:main\n".to_owned(),
        };
        assert_eq!(
            event.to_string(),
            "remote mir\\tror skipped the ref origin:main\\n: the name fails the ref-name rule"
        );
    }

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

    /// The ed25519 key [`PUBLIC_B64`] as a trusted set.
    fn ed25519_keys() -> crate::verify::TrustedKeys {
        use crate::sign::{Ed25519Verifier, Verifier};
        let verifier = Ed25519Verifier::new(
            [ostrya_core::base64::decode(PUBLIC_B64).unwrap()],
            Vec::<Vec<u8>>::new(),
        )
        .unwrap();
        crate::verify::TrustedKeys::new(vec![Arc::new(verifier) as Arc<dyn Verifier>]).unwrap()
    }

    /// The signer of the key [`SECRET_B64`].
    fn ed25519_signer() -> crate::sign::Ed25519Signer {
        crate::sign::Ed25519Signer::from_base64(SECRET_B64).unwrap()
    }

    /// A scratch directory that the value removes when it drops.
    struct Scratch {
        root: PathBuf,
    }

    impl Scratch {
        fn new() -> Scratch {
            let root = std::env::temp_dir().join(format!(
                "ostrya-collection-local-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).unwrap();
            Scratch { root }
        }

        /// Creates an archive repository at `name` in the directory.
        async fn create(&self, name: &str) -> Repo {
            let mode = crate::CreateOptions::new(crate::RepoMode::Archive);
            Repo::create(&self.root.join(name), mode).await.unwrap()
        }
    }

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

    /// Writes a commit with the parent `parent` and the timestamp
    /// `timestamp` whose tree holds the file `f` with `content`, points the
    /// collection ref of each name of `names` in [`LOCAL_ID`] at it, and
    /// returns it.
    async fn local_commit(
        repo: &Repo,
        names: &[&str],
        parent: Option<Checksum>,
        timestamp: u64,
        content: &[u8],
    ) -> Checksum {
        let options = crate::commit::CommitOptions {
            parent,
            timestamp: Some(timestamp),
            ..crate::commit::CommitOptions::default()
        };
        local_commit_with(repo, names, options, content).await
    }

    /// Writes a commit with `options` whose tree holds the file `f` with
    /// `content`, points the collection ref of each name of `names` in
    /// [`LOCAL_ID`] at it, and returns it.
    async fn local_commit_with(
        repo: &Repo,
        names: &[&str],
        options: crate::commit::CommitOptions,
        content: &[u8],
    ) -> Checksum {
        let txn = repo.transaction().await.unwrap();
        let dirmeta = ostrya_core::DirMeta {
            uid: 0,
            gid: 0,
            mode: 0o40755,
            xattrs: Default::default(),
        };
        let dirmeta = txn
            .write_metadata(ObjectType::DirMeta, None, &dirmeta.serialize().unwrap())
            .await
            .unwrap();
        let file = txn
            .write_regfile_inline(None, &crate::write::FileMeta::regular(0, 0, 0o644), content)
            .await
            .unwrap();
        let mut mtree = crate::mtree::MutableTree::new();
        mtree.set_metadata_checksum(dirmeta);
        mtree.replace_file("f", file).unwrap();
        let root = txn.write_mtree(&mut mtree).await.unwrap();
        let commit = txn.write_commit(options, &root).await.unwrap();
        txn.commit().await.unwrap();
        for name in names {
            let cref = crate::Ref::collection(LOCAL_ID, *name);
            repo.set_ref_immediate(&cref, Some(&commit)).await.unwrap();
        }
        commit
    }

    /// Probes the local repository `src` under `trust` for the refs `names`,
    /// and pulls the refs into `dst` with the flags `flags` and the depth
    /// `depth`, as a pull of collection refs pulls from a selected local
    /// candidate.
    async fn probe_and_pull(
        dst: &Repo,
        src: &Repo,
        trust: PullTrust,
        names: &[&str],
        flags: PullFlags,
        depth: i32,
    ) -> Result<PullStats> {
        let verification = Verification::from_trust(trust.clone());
        let (refs, summary) = probe_local(src, &verification, LOCAL_ID, names).await?;
        let listed = refs.listed;
        let run = PullOptions {
            refs: listed.iter().map(|l| l.name.clone()).collect(),
            flags,
            depth,
            ..PullOptions::default()
        };
        let pinned = Pinned {
            summary: Mutex::new(summary),
            ..pinned_of(dst, &listed)
        };
        let related = RelatedRule::of(dst.config()).unwrap();
        dst.pull_local_candidate(src, trust, related, run, None, &pinned)
            .await
            .map(|report| report.stats)
    }

    /// The refs `listed` of a local candidate in [`LOCAL_ID`], at the place
    /// of the collection refs of `dst`, as the pull of collection refs pins
    /// them. A tip with no collection binding passes.
    fn pinned_of<'a>(dst: &Repo, listed: &[Listed]) -> Pinned<'a> {
        Pinned {
            targets: listed.iter().map(|l| (l.name.clone(), l.commit)).collect(),
            listed: listed
                .iter()
                .map(|l| (l.name.clone(), (l.commit, l.timestamp)))
                .collect(),
            bare: HashSet::new(),
            commits_alone: false,
            collection: LOCAL_ID,
            allow_unbound: true,
            place: RefPlace::of_collection(dst, LOCAL_ID),
            summary: Mutex::new(None),
            summary_dict: None,
        }
    }

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

    /// Puts the bytes of the object `from` of type `ty` of the archive
    /// repository at `dir` under the name of its object `to`.
    fn replace_object_file(dir: &Path, ty: ObjectType, to: &Checksum, from: &Checksum) {
        let _ = std::fs::remove_file(object_file(dir, to, ty));
        std::fs::copy(object_file(dir, from, ty), object_file(dir, to, ty)).unwrap();
    }

    /// Puts the bytes of the commit `from` of the archive repository at `dir`
    /// under the name of its commit `to`.
    fn replace_commit_file(dir: &Path, to: &Checksum, from: &Checksum) {
        replace_object_file(dir, ObjectType::Commit, to, from);
    }

    /// Returns an action that puts `bytes` back as the object `checksum` of
    /// type `ty` of the archive repository at `dir`.
    fn restore_object_file(
        dir: &Path,
        checksum: &Checksum,
        ty: ObjectType,
    ) -> impl FnOnce() + Send + 'static {
        let path = object_file(dir, checksum, ty);
        let bytes = std::fs::read(&path).unwrap();
        move || {
            std::fs::remove_file(&path).unwrap();
            std::fs::write(&path, bytes).unwrap();
        }
    }

    /// Asserts that the repository `dst` at `dir` holds no object, no
    /// `.commitpartial` marker, no staging directory, and no collection ref.
    async fn assert_nothing_written(dst: &Repo, dir: &Path) {
        let objects = dst.list_objects().await.unwrap();
        assert!(objects.is_empty(), "{objects:?}");
        let leftovers: Vec<String> = ["state", "tmp"]
            .into_iter()
            .flat_map(|sub| std::fs::read_dir(dir.join(sub)).unwrap())
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|name| name.ends_with(".commitpartial") || name.starts_with("staging-"))
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");
        let refs = dst
            .list_collection_refs_in(LOCAL_ID, &RefSelector::parse(std::iter::empty()).unwrap())
            .await
            .unwrap();
        assert!(refs.is_empty(), "{refs:?}");
    }

    /// Without a summary policy, the probe of a local candidate reads the
    /// timestamp of each tip commit. Under a summary policy, the refs and
    /// their timestamps come from the summary.
    #[test]
    fn the_local_probe_reads_the_timestamp_of_each_tip_commit() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let one = local_commit(&src, &["os/a", "os/b"], None, 1_700_000_001, b"one").await;
            let two = local_commit(&src, &["os/c"], None, 1_700_000_002, b"two").await;
            let unverified = Verification::from_trust(PullTrust::unverified());

            let listed = probe_local(&src, &unverified, LOCAL_ID, &[])
                .await
                .unwrap()
                .0
                .listed;
            assert_eq!(listed.len(), 3);
            let timestamps: HashMap<Checksum, u64> =
                listed.iter().map(|l| (l.commit, l.timestamp)).collect();
            assert_eq!(timestamps.len(), 2);
            assert_eq!(timestamps[&one], 1_700_000_001);
            assert_eq!(timestamps[&two], 1_700_000_002);

            // Under a summary policy, the refs come from the summary.
            src.regenerate_summary(&crate::SummaryOptions::default())
                .await
                .unwrap();
            src.sign_summary(&ed25519_signer()).await.unwrap();
            let policy =
                Verification::from_trust(PullTrust::unverified().with_summary(ed25519_keys()));
            let mut from_summary = probe_local(&src, &policy, LOCAL_ID, &[])
                .await
                .unwrap()
                .0
                .listed;
            let mut expected = listed;
            from_summary.sort_unstable_by(|a, b| a.name.cmp(&b.name));
            expected.sort_unstable_by(|a, b| a.name.cmp(&b.name));
            assert_eq!(from_summary, expected);
        });
    }

    /// Under a summary policy, the pull of a local candidate takes the
    /// `summary` that the probe read and checked, and reads neither the
    /// `summary` nor the `summary.sig` of the source again. So a pull that
    /// requires static deltas applies the delta that the probed summary
    /// advertises. After the probe, a removal of both files from the source
    /// does not fail the pull, with and without static deltas.
    #[test]
    fn a_local_candidate_takes_the_summary_that_the_probe_checked() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let tip = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
            src.generate_static_delta(None, &tip, &crate::DeltaOptions::default())
                .await
                .unwrap();
            src.regenerate_summary(&crate::SummaryOptions::default())
                .await
                .unwrap();
            src.sign_summary(&ed25519_signer()).await.unwrap();
            let trust = PullTrust::unverified().with_summary(ed25519_keys());
            let verification = Verification::from_trust(trust.clone());
            let (refs, summary) = probe_local(&src, &verification, LOCAL_ID, &["os/a"])
                .await
                .unwrap();
            let listed = refs.listed;
            let summary = summary.expect("the probe gives the checked summary");
            let pinned_with = |dst: &Repo| Pinned {
                summary: Mutex::new(Some(Arc::clone(&summary))),
                ..pinned_of(dst, &listed)
            };
            let run = PullOptions {
                refs: vec!["os/a".to_owned()],
                require_static_deltas: true,
                ..PullOptions::default()
            };
            let cref = crate::Ref::collection(LOCAL_ID, "os/a");

            let dst = scratch.create("dst").await;
            let related = RelatedRule::of(dst.config()).unwrap();
            let stats = dst
                .pull_local_candidate(
                    &src,
                    trust.clone(),
                    related,
                    run.clone(),
                    None,
                    &pinned_with(&dst),
                )
                .await
                .unwrap()
                .stats;
            assert!(stats.delta_parts > 0, "{stats:?}");
            assert_eq!(dst.resolve_ref_tip(&cref).await.unwrap(), Some(tip));

            for file in ["summary.sig", "summary"] {
                std::fs::remove_file(scratch.root.join("src").join(file)).unwrap();
            }
            let plain = PullOptions {
                refs: vec!["os/a".to_owned()],
                ..PullOptions::default()
            };
            for (name, run, deltas) in [("unsigned", run, true), ("unsigned-plain", plain, false)] {
                let dst = scratch.create(name).await;
                let related = RelatedRule::of(dst.config()).unwrap();
                let stats = dst
                    .pull_local_candidate(
                        &src,
                        trust.clone(),
                        related,
                        run,
                        None,
                        &pinned_with(&dst),
                    )
                    .await
                    .unwrap_or_else(|e| panic!("{name}: {e:?}"))
                    .stats;
                assert_eq!(stats.delta_parts > 0, deltas, "{name}: {stats:?}");
                assert_eq!(
                    dst.resolve_ref_tip(&cref).await.unwrap(),
                    Some(tip),
                    "{name}"
                );
            }
        });
    }

    /// With depth 1, a selected tip that is the parent of another selected
    /// tip is pulled, and each ref gets its commit, in each order of the
    /// refs.
    #[test]
    fn a_selected_tip_that_is_a_parent_of_another_is_pulled_in_each_order() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            for (at, (child_ref, parent_ref)) in
                [("os/a", "os/b"), ("os/b", "os/a")].into_iter().enumerate()
            {
                let src = scratch.create(&format!("src{at}")).await;
                let parent = local_commit(&src, &[parent_ref], None, 1_700_000_001, b"one").await;
                let child =
                    local_commit(&src, &[child_ref], Some(parent), 1_700_000_002, b"two").await;
                let dst = scratch.create(&format!("dst{at}")).await;
                let src = Repo::open(&scratch.root.join(format!("src{at}")))
                    .await
                    .unwrap();
                probe_and_pull(
                    &dst,
                    &src,
                    PullTrust::unverified(),
                    &["os/a", "os/b"],
                    PullFlags::NONE,
                    1,
                )
                .await
                .unwrap();
                for (name, commit) in [(child_ref, child), (parent_ref, parent)] {
                    let cref = crate::Ref::collection(LOCAL_ID, name);
                    assert_eq!(dst.resolve_ref_tip(&cref).await.unwrap(), Some(commit));
                }
            }
        });
    }

    /// Under `UNTRUSTED`, a tip commit file that does not hash to its name
    /// fails the pull with [`Error::ChecksumMismatch`] at the read of the
    /// tip, before the listed check. The file has the listed timestamp, so
    /// the hash is the one check that can fail. The pull publishes no object
    /// and writes no ref, and it leaves no `.commitpartial` marker and no
    /// staging directory.
    #[test]
    fn a_commit_that_does_not_hash_to_its_name_fails_an_untrusted_pull() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let one = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
            let two = local_commit(&src, &[], None, 1_700_000_001, b"two").await;
            replace_commit_file(&scratch.root.join("src"), &one, &two);
            let dst = scratch.create("dst").await;
            let pulled = probe_and_pull(
                &dst,
                &src,
                PullTrust::unverified(),
                &["os/a"],
                PullFlags::UNTRUSTED,
                0,
            )
            .await;
            match pulled {
                Err(Error::ChecksumMismatch { expected, actual }) => {
                    assert_eq!((expected, actual), (one, two));
                }
                other => panic!("{other:?}"),
            }
            assert_nothing_written(&dst, &scratch.root.join("dst")).await;
        });
    }

    /// A tip commit whose timestamp changes between the probe and the pull
    /// of a local candidate fails the check of the listed timestamp with
    /// [`Error::Pull`]. Under `UNTRUSTED`, the commit file does not hash to
    /// its name, and the pull fails with [`Error::ChecksumMismatch`] at the
    /// read of the tip, before the check. The pull writes nothing.
    #[test]
    fn a_tip_commit_that_changes_after_the_probe_fails_the_listed_check() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let one = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
            let two = local_commit(&src, &[], None, 1_700_000_002, b"two").await;
            let unverified = Verification::from_trust(PullTrust::unverified());
            let listed = probe_local(&src, &unverified, LOCAL_ID, &["os/a"])
                .await
                .unwrap()
                .0
                .listed;
            assert_eq!(
                listed,
                [Listed {
                    name: "os/a".to_owned(),
                    commit: one,
                    timestamp: 1_700_000_001,
                }]
            );
            replace_commit_file(&scratch.root.join("src"), &one, &two);

            for (at, flags) in [PullFlags::NONE, PullFlags::UNTRUSTED]
                .into_iter()
                .enumerate()
            {
                let name = format!("dst{at}");
                let dst = scratch.create(&name).await;
                let run = PullOptions {
                    refs: vec!["os/a".to_owned()],
                    flags,
                    ..PullOptions::default()
                };
                let pinned = pinned_of(&dst, &listed);
                let related = RelatedRule::of(dst.config()).unwrap();
                let pulled = dst
                    .pull_local_candidate(
                        &src,
                        PullTrust::unverified(),
                        related,
                        run,
                        None,
                        &pinned,
                    )
                    .await;
                match pulled {
                    Err(Error::Pull(message)) if flags == PullFlags::NONE => {
                        assert!(message.contains("timestamp"), "case {at}: {message}");
                    }
                    Err(Error::ChecksumMismatch { expected, actual })
                        if flags == PullFlags::UNTRUSTED =>
                    {
                        assert_eq!((expected, actual), (one, two), "case {at}");
                    }
                    other => panic!("case {at}: {other:?}"),
                }
                assert_nothing_written(&dst, &scratch.root.join(&name)).await;
            }
        });
    }

    /// Two refs that name one tip commit each get the check of their own
    /// listed timestamp. A wrong listed timestamp of either ref fails the
    /// pull with [`Error::Pull`] that names the ref, and the pull writes
    /// nothing. With the listed timestamps of the probe, the pull writes both
    /// refs.
    #[test]
    fn each_ref_that_names_one_tip_gets_the_listed_check() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let names = ["os/a", "os/b"];
            let tip = local_commit(&src, &names, None, 1_700_000_001, b"one").await;
            let unverified = Verification::from_trust(PullTrust::unverified());
            let listed = probe_local(&src, &unverified, LOCAL_ID, &names)
                .await
                .unwrap()
                .0
                .listed;
            let run = PullOptions {
                refs: names.map(str::to_owned).to_vec(),
                ..PullOptions::default()
            };

            for (at, wrong) in names.into_iter().enumerate() {
                let dir = format!("wrong{at}");
                let dst = scratch.create(&dir).await;
                let mut pinned = pinned_of(&dst, &listed);
                pinned.listed.insert(wrong.to_owned(), (tip, 1_700_000_002));
                let related = RelatedRule::of(dst.config()).unwrap();
                let pulled = dst
                    .pull_local_candidate(
                        &src,
                        PullTrust::unverified(),
                        related,
                        run.clone(),
                        None,
                        &pinned,
                    )
                    .await;
                match pulled {
                    Err(Error::Pull(message)) => {
                        assert!(message.contains(&format!("'{wrong}'")), "{message}");
                    }
                    other => panic!("{wrong}: {other:?}"),
                }
                assert_nothing_written(&dst, &scratch.root.join(&dir)).await;
            }

            let dst = scratch.create("dst").await;
            let pinned = pinned_of(&dst, &listed);
            let related = RelatedRule::of(dst.config()).unwrap();
            dst.pull_local_candidate(&src, PullTrust::unverified(), related, run, None, &pinned)
                .await
                .unwrap();
            for name in names {
                let cref = crate::Ref::collection(LOCAL_ID, name);
                assert_eq!(dst.resolve_ref_tip(&cref).await.unwrap(), Some(tip));
            }
        });
    }

    /// Under a commit policy, the pull hashes the commit that the signature
    /// check reads. The source holds the bytes and the `.commitmeta` of a
    /// signed commit under the name of an unsigned commit, and holds the
    /// bytes of the unsigned commit again before the import. The pull fails
    /// with [`Error::ChecksumMismatch`] at the read of the tip, and writes
    /// nothing.
    #[test]
    fn a_commit_that_changes_after_its_signature_check_fails_the_pull() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let signed = local_commit(&src, &[], None, 1_700_000_001, b"one").await;
            src.sign_commit(&signed, &ed25519_signer()).await.unwrap();
            let unsigned = local_commit(&src, &["os/a"], None, 1_700_000_001, b"two").await;
            let src_dir = scratch.root.join("src");
            replace_object_file(&src_dir, ObjectType::CommitMeta, &unsigned, &signed);
            let restore = restore_object_file(&src_dir, &unsigned, ObjectType::Commit);
            replace_commit_file(&src_dir, &unsigned, &signed);
            let dst = scratch.create("dst").await;
            let dst_dir = scratch.root.join("dst");
            import_seam::arm(&dst_dir, restore);
            let pulled = probe_and_pull(
                &dst,
                &src,
                PullTrust::commits(ed25519_keys()),
                &["os/a"],
                PullFlags::NONE,
                0,
            )
            .await;
            let armed = import_seam::disarm(&dst_dir);
            match pulled {
                Err(Error::ChecksumMismatch { expected, actual }) => {
                    assert_eq!((expected, actual), (unsigned, signed));
                }
                other => panic!("{other:?}"),
            }
            assert!(armed, "the pull got to the import");
            assert_nothing_written(&dst, &dst_dir).await;
        });
    }

    /// Under `UNTRUSTED`, the pull hashes each dirtree that the walk of the
    /// tree reads. The source holds the bytes of another dirtree under the
    /// name of the root dirtree of the tip, and holds the right bytes again
    /// before the import. The pull fails with [`Error::ChecksumMismatch`] at
    /// the walk, and writes nothing.
    #[test]
    fn a_dirtree_that_changes_after_the_walk_fails_an_untrusted_pull() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let tip = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
            let other = local_commit(&src, &[], None, 1_700_000_001, b"two").await;
            let root = src.load_commit(&tip).await.unwrap().0.root_dirtree;
            let other_root = src.load_commit(&other).await.unwrap().0.root_dirtree;
            let src_dir = scratch.root.join("src");
            let restore = restore_object_file(&src_dir, &root, ObjectType::DirTree);
            replace_object_file(&src_dir, ObjectType::DirTree, &root, &other_root);
            let dst = scratch.create("dst").await;
            let dst_dir = scratch.root.join("dst");
            import_seam::arm(&dst_dir, restore);
            let pulled = probe_and_pull(
                &dst,
                &src,
                PullTrust::unverified(),
                &["os/a"],
                PullFlags::UNTRUSTED,
                0,
            )
            .await;
            let armed = import_seam::disarm(&dst_dir);
            match pulled {
                Err(Error::ChecksumMismatch { expected, actual }) => {
                    assert_eq!((expected, actual), (root, other_root));
                }
                other => panic!("{other:?}"),
            }
            assert!(armed, "the pull got to the import");
            assert_nothing_written(&dst, &dst_dir).await;
        });
    }

    /// Under a commit policy, the import stages the `.commitmeta` that the
    /// signature check read. The source holds the `.commitmeta` of another
    /// signed commit after the check. The pull fails with [`Error::Pull`],
    /// and writes nothing.
    #[test]
    fn a_commitmeta_that_changes_after_the_signature_check_fails_the_pull() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let tip = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
            let other = local_commit(&src, &[], None, 1_700_000_001, b"two").await;
            for commit in [&tip, &other] {
                src.sign_commit(commit, &ed25519_signer()).await.unwrap();
            }
            let src_dir = scratch.root.join("src");
            let dst = scratch.create("dst").await;
            let dst_dir = scratch.root.join("dst");
            import_seam::arm(&dst_dir, move || {
                replace_object_file(&src_dir, ObjectType::CommitMeta, &tip, &other)
            });
            let pulled = probe_and_pull(
                &dst,
                &src,
                PullTrust::commits(ed25519_keys()),
                &["os/a"],
                PullFlags::NONE,
                0,
            )
            .await;
            let armed = import_seam::disarm(&dst_dir);
            assert!(!armed, "the pull did not get to the import");
            match pulled {
                Err(Error::Pull(message)) => {
                    assert!(message.contains(".commitmeta"), "{message}");
                }
                other => panic!("{other:?}"),
            }
            assert_nothing_written(&dst, &dst_dir).await;
        });
    }

    /// Under `UNTRUSTED`, the pull hashes each attachment that it reads for
    /// the walk. The source holds the bytes of another commit under the name
    /// of the attachment, and holds the right bytes again before the import.
    /// The pull fails with [`Error::ChecksumMismatch`] at the read of the
    /// attachment, and writes nothing.
    #[test]
    fn an_attachment_that_changes_after_the_walk_fails_an_untrusted_pull() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new();
            let src = scratch.create("src").await;
            let attachment = local_commit(&src, &[], None, 1_700_000_001, b"dep").await;
            let other = local_commit(&src, &[], None, 1_700_000_001, b"other").await;
            let options = crate::commit::CommitOptions {
                timestamp: Some(1_700_000_001),
                attachments: vec![("lib/b".to_owned(), attachment)],
                ..crate::commit::CommitOptions::default()
            };
            local_commit_with(&src, &["os/a"], options, b"one").await;
            let src_dir = scratch.root.join("src");
            let restore = restore_object_file(&src_dir, &attachment, ObjectType::Commit);
            replace_commit_file(&src_dir, &attachment, &other);
            let dst = scratch.create("dst").await;
            let dst_dir = scratch.root.join("dst");
            import_seam::arm(&dst_dir, restore);
            let pulled = probe_and_pull(
                &dst,
                &src,
                PullTrust::unverified(),
                &["os/a"],
                PullFlags::UNTRUSTED,
                0,
            )
            .await;
            let armed = import_seam::disarm(&dst_dir);
            match pulled {
                Err(Error::ChecksumMismatch { expected, actual }) => {
                    assert_eq!((expected, actual), (attachment, other));
                }
                other => panic!("{other:?}"),
            }
            assert!(armed, "the pull got to the import");
            assert_nothing_written(&dst, &dst_dir).await;
        });
    }
}