ostrya 0.15.0

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
//! The `Commit` message that ends a push session.
//!
//! This module holds the checks of the ref updates and the server
//! signatures. It also holds the hooks of the host, the update lock, the ref
//! writes, the transaction commit, and the summary.

use std::any::Any;
use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use ostrya_core::{Checksum, Commit, ObjectName, ObjectType, Ref, Type, Value, to_bytes, validate};

use super::ancestry::{Parents, Walks};
use super::hooks::{self, HookRefusal, HostEntry, ReceiveHooks, ReceiveRefUpdate, UpdatePlan};
use super::merge::{
    SIGNATURE_KEYS, check_stored, merge_detached, replace_entries, signature_keys_in,
};
use super::policy::{SessionPolicy, UpdateRule};
use super::session::{
    Failure, ReceiveCommit, ReceiveRefOutcome, ReceiveReport, ReceiveStep, ReceiveWarning,
};
use super::walk::{self, Missing};
use super::{ReceiveVerify, TrustedKeys};
use crate::MAX_METADATA_SIZE;
use crate::access::ClientAccess;
use crate::error::{Error, Result};
use crate::lock::UpdateLockHeld;
use crate::read::CommitState;
use crate::refs::{RefFileState, nested_ref_paths};
use crate::related::{self, HeldAttachment, RelatedRule, RelationField};
use crate::remote::proto::{CommitRequest, MAX_FRAME, Message};
use crate::remote::{self, Expected, RefOutcome, RefUpdate};
use crate::repo::Repo;
use crate::sign::{Signer, SigningKey, append_signature};
use crate::summary::{
    OSTREE_METADATA_REF, SummaryOptions, SummaryStep, parse_signature_dict,
    serialize_signature_dict,
};
use crate::transaction::{Transaction, TransactionStats};
use crate::verify::Payload;
use crate::write::flat_name;

/// The detached-metadata key of GPG signatures. The `ostree` command writes
/// the summary signatures of this key first in `summary.sig`, and ostrya does
/// the same. `docs/format-reference.md`, "Summary signature -- `a{sv}`",
/// records this order.
const GPG_KEY: &str = "ostree.gpgsigs";

pub(super) type Checked<T> = std::result::Result<T, Failure>;

/// A serialized detached-metadata dict, shared with the blocking pool.
type Bytes = Arc<Vec<u8>>;

/// The states of the held attachments, and the entries below the first level
/// of attachments, that [`held_levels_blocking`] reads.
type HeldLevels = (
    HashMap<Checksum, HeldAttachment>,
    Vec<(Checksum, Checksum, String)>,
);

pub(super) fn protocol(message: String) -> Failure {
    Failure::Wire(remote::Error::Protocol(message))
}

pub(super) fn ref_denied(message: String) -> Failure {
    Failure::Wire(remote::Error::RefDenied(message))
}

/// The refs that `Hello` named.
pub(super) struct Named<'a> {
    /// The refs of `Hello`, as the client sent them.
    pub(super) names: &'a [String],
    /// The canonical form of each ref of `names`, in the same order.
    pub(super) refs: &'a [Ref],
    /// The path under `refs/` of each ref of `names`, in the same order.
    pub(super) paths: &'a [String],
    /// `true` if the session reads a one-way stream.
    pub(super) one_way: bool,
}

impl Named<'_> {
    /// Returns a map from each name of `names` to its index.
    pub(super) fn by_name(&self) -> HashMap<&str, usize> {
        self.names
            .iter()
            .enumerate()
            .map(|(i, name)| (name.as_str(), i))
            .collect()
    }

    /// Returns the index in `names` of each name of `wanted`, in order, as
    /// `index` maps it. `index` is the map that [`Named::by_name`] returns.
    ///
    /// A name that `Hello` did not name is `protocol`, and so is a name that
    /// `wanted` holds two times. `what` is the verb of the message of the
    /// second case.
    pub(super) fn indices<'n>(
        index: &HashMap<&str, usize>,
        wanted: impl Iterator<Item = &'n str>,
        what: &str,
    ) -> Checked<Vec<usize>> {
        let mut seen = HashSet::new();
        let mut found = Vec::new();
        for name in wanted {
            let Some(&i) = index.get(name) else {
                return Err(protocol(format!("ref '{name}' was not named in Hello")));
            };
            if !seen.insert(i) {
                return Err(protocol(format!("ref '{name}' is {what} more than once")));
            }
            found.push(i);
        }
        Ok(found)
    }
}

/// Reads the ref name `name` of a `Commit` message, and returns its
/// canonical form in a repository whose collection id is `own`.
///
/// A name that [`Ref`] does not read is `invalid-ref`. So is a local ref of
/// 64 lowercase hex characters if `writes` is `true`: a revision reads such
/// text as a checksum, so a push writes no commit to such a ref.
pub(super) fn commit_ref(own: Option<&str>, name: &str, writes: bool) -> Checked<Ref> {
    let r = name
        .parse::<Ref>()
        .map_err(|_| invalid_ref(name))?
        .canonical(own);
    check_shape(&r, name, writes)?;
    Ok(r)
}

/// Checks the canonical ref `r` of the ref name `name` of a `Commit`
/// message.
///
/// A local ref of 64 lowercase hex characters is `invalid-ref` if `writes`
/// is `true`.
fn check_shape(r: &Ref, name: &str, writes: bool) -> Checked<()> {
    match r {
        Ref::Local { name: local } if writes && ostrya_core::is_checksum_shaped(local) => {
            Err(invalid_ref(name))
        }
        _ => Ok(()),
    }
}

fn invalid_ref(name: &str) -> Failure {
    Failure::Wire(remote::Error::InvalidRef(format!(
        "invalid ref name '{name}'"
    )))
}

/// A commit that a ref update names as its new value.
struct Target {
    checksum: Checksum,
    /// The serialized commit, the payload of its signatures. The trust check
    /// and the search for a signature of a server key give it to the blocking
    /// pool with no copy.
    bytes: Arc<Vec<u8>>,
    commit: Commit,
    /// The index of each ref update whose new value the commit is, in order.
    /// The rules of these updates verify and sign the commit.
    updates: Vec<usize>,
}

/// A server signature over the bytes of a new commit, made before the
/// update lock.
struct Prepared<'a> {
    signer: &'a SigningKey,
    signature: Vec<u8>,
}

/// The detached-metadata edit of one commit of the session, planned before
/// the update lock and checked again under it.
struct Edit<'a> {
    commit: Checksum,
    /// The commit bytes, the payload of its signatures. A commit that no
    /// update names gets no signature, and its payload is empty.
    payload: Payload<'a>,
    /// The dict that the repository held at the time of the plan, `None` for
    /// no dict.
    stored: Option<Bytes>,
    /// The filtered incoming dict, with the entries of the host in place of
    /// each client entry of the same key.
    incoming: Option<Bytes>,
    /// The keys of the host entries whose value stays where the stored dict
    /// holds the key, shared with the blocking pool.
    keep: Arc<Vec<String>>,
    /// The server keys of the rules of the updates of the commit, which the
    /// plan before the lock signs with.
    signers: Vec<&'a Arc<SigningKey>>,
    /// The prepared signatures whose key did not sign the commit in the
    /// merged dict, with the signatures kept before each.
    signatures: Vec<Prepared<'a>>,
    /// The size of the dict the commit writes, where it is over
    /// `MAX_METADATA_SIZE`.
    oversize: Option<u64>,
}

/// Runs the checks of the ref updates of `request`, then writes the refs and
/// commits `txn` under the update lock.
///
/// `named` holds the refs of `Hello`, their canonical forms, and their
/// paths. `commit_meta` holds the detached metadata dicts of the session.
/// The ref of a collection other than the collection id of the repository is
/// under `refs/mirrors/ID/`.
///
/// A request with a server commit goes to
/// [`server_commit::finish`](super::server_commit::finish), and the sections
/// below do not apply to it.
///
/// # Checks
///
/// The checks run in this order. The first failure ends the session, and the
/// session publishes nothing.
///
/// - Each ref name is valid, and no update writes a commit to a local ref of
///   64 lowercase hex characters (`invalid-ref`). A delete of such a ref
///   passes. The message holds one update at least, and each update names a
///   ref of `Hello` once, with the text of `Hello` (`protocol`).
/// - The `CommitReply` of the updates fits in a frame of [`MAX_FRAME`], with
///   the longest outcome of each update (`limit-exceeded`). Because of this
///   check, the server can always send the reply of a commit that wrote its
///   refs.
/// - Each detached metadata dict belongs to a commit of the session, a staged
///   commit or the new commit of an update, or to a commit that the
///   repository holds (`protocol`).
/// - No update names the collection anchor ref of the local refs of a
///   repository with a collection id, and `policy` gives a rule for each
///   update, in the namespace of its ref (`ref-denied`).
///   The policy of a client group needs `w` or `t` for an update that writes
///   a commit. The policy of a one-way stream needs a rule that accepts the
///   ref.
/// - Each new commit is staged or present (`missing-objects`), and each
///   commit of the session parses.
/// - A dict for a commit that the repository holds, that the session did not
///   stage, and that no update names, belongs to an attachment: an entry of
///   field 2 of a commit of the session, or of a held attachment below the
///   session, names the commit (`protocol`). The check reads field 2 of the
///   held attachments only if a dict stays unnamed after the commits of the
///   session, and it reads their commit objects alone. The session drops each
///   such dict, with no merge and no write. The repository held the
///   attachment and its dict before the session, and no rule of the session
///   covers a change to them.
/// - The tree of each commit of the session is complete (`missing-objects`).
/// - Each entry of field 2 of each staged commit, the staged parents of a new
///   commit included, has a name that is not empty and a 32-byte checksum
///   (`protocol`). A new commit that the repository holds with a partial
///   marker gets the same check. Each attachment that these entries name is
///   staged or held (`missing-objects`, with each absent attachment listed).
///   A held attachment is complete (`missing-objects`, with no object
///   listed). A staged attachment is a staged commit, so its own entries get
///   these checks. For an attachment that the repository holds complete, and
///   for a new commit that the repository holds complete, the check reads
///   field 2 from its commit object, and each attachment that it names gets
///   the same checks, one level at a time. A defective entry in field 2 of
///   such a held commit is `internal`. An attachment that is a new commit is
///   complete, also with a partial marker, because the completeness walk ran
///   over its tree.
/// - The ref binding and the collection binding of each new commit name each
///   of its refs and the namespace of each ref (`binding-mismatch`), as
///   [`check_bindings`] states.
/// - Each new commit passes the signature verification of each of its rules
///   (`signature-required`). The verification reads the union of the stored
///   and the incoming detached metadata. A rule that accepts a commit with no
///   signature skips a commit whose union holds no signature blob. A commit
///   that no update names gets no verification, a staged parent and an
///   attachment included. The checksum of an attachment is in field 2 of a
///   commit of the session. A new commit is that commit, or binds it through
///   the parent checksums of its history, and the signatures of the new
///   commit cover these checksums. An attachment that only a staged commit
///   outside each history names is bound to no new commit. The session staged
///   each object under the checksum of its bytes.
///
/// # Before the update lock
///
/// After the checks, if `[ex-ostrya] keep-detached-related` of the repository
/// is `false`, this step drops `ostrya.related` from each incoming dict. Then
/// the staged objects become durable. At the same time, each new commit gets
/// a signature from each server key of its rules. No other commit gets a
/// server signature. Each other commit with a filtered incoming dict, a staged
/// attachment included, gets the merge of that dict alone. A key makes no
/// signature if it already signed the commit in one of these places:
///
/// - The merge of the filtered incoming dict into the stored dict.
/// - A signature that a key before it made.
///
/// If no `hooks` are given, this step also finds the size of each dict that
/// the commit writes. Then the fast-forward walk of each update reads the
/// parent chain as far as the ref tip that this function read before the
/// lock. If the client sent `force` and the rule allows a non-fast-forward
/// update, no walk runs. If the rule only creates its ref, no walk runs,
/// because the check under the lock refuses the update for a ref that is
/// present. The walk of a ref that the update creates does not run, so the
/// parent chain of its new commit can stop at any depth.
///
/// # Hooks
///
/// If `hooks` are given, [`ReceiveHooks::before_update`] runs next,
/// immediately before the update lock, with the canonical name of each ref.
/// If the hook refuses, the session ends with the code of the refusal. This
/// function then checks the plan of the hook. If the checks refuse the plan,
/// the failure is on the server side.
///
/// The entries of the host merge into the incoming dicts. Each commit with
/// host entries and no edit gets a new edit. Then this function finds the
/// size of each dict that the commit writes. If a dict with host entries is
/// over the size limit, the failure is `limit-exceeded`.
///
/// If a failure occurs after the hook, the carried value of the plan drops
/// once, after the release of the update lock. `after_update` does not run.
///
/// # Under the update lock
///
/// Under the lock, this function reads the refs again. These cases are
/// `ref-denied`:
///
/// - A ref that is an alias.
/// - A path that a ref write cannot replace.
/// - Two updates where one update names a directory of the other.
///
/// Each update then gets these checks:
///
/// - The ref is in the state that the update expects (`ref-mismatch`).
/// - A rule that only creates its ref refuses a commit for a ref that is
///   present (`ref-mismatch`).
/// - The rule allows the delete of a present ref (`delete-denied`).
/// - The new commit is a fast-forward (`non-fast-forward`): the parent chain
///   of the new commit reaches the commit of the ref before it stops at an
///   absent commit or a root commit.
///
/// This function then reads the stored detached metadata again. If it changed
/// after the plan, this function drops each prepared signature whose key
/// signed the commit in the new merge. The size is also found again, with the
/// keys of the host entries that keep a stored value. Then each dict over the
/// size limit is `limit-exceeded`. Only a dict with host entries can fail the
/// size check before the lock.
///
/// The merges, the signatures, and the refs that change go into the queue of
/// the transaction. If the repository has a collection id, the policy
/// regenerates the summary, and a ref changes, the anchor commit also goes
/// into the queue. Its parent is the anchor commit that this function reads
/// under the lock. A failure of the anchor is `internal`, and nothing is
/// published. Then the transaction commits.
///
/// After the transaction commit, this function removes the partial marker of
/// each commit of the session. If the policy regenerates the summary and a ref
/// changed, it builds, signs, and writes the root summary and the summary of
/// each auth item of the client groups of the config. A failure of these last steps is a warning of
/// the report.
///
/// # Failure of the transaction commit
///
/// The transaction commit is not atomic. These failures can leave the
/// detached metadata and some refs written:
///
/// - A failure of a detached-metadata write.
/// - A failure of a ref write.
/// - A failure of the `fsync` of a ref directory.
///
/// In this case, this function returns the error, and `after_update` does not
/// run.
///
/// # After the update lock
///
/// This function then releases the update lock. If `hooks` are given,
/// [`ReceiveHooks::after_update`] runs next with the report and the carried
/// value. It runs also when no ref changes.
///
/// An error of the hook is `internal`, with the message cut at 4096 bytes at a
/// character boundary. After an error of the hook, the refs and the detached
/// metadata stay written.
pub(super) async fn finish(
    repo: &Repo,
    policy: &dyn SessionPolicy,
    hooks: Option<&dyn ReceiveHooks>,
    txn: Transaction,
    named: Named<'_>,
    mut commit_meta: HashMap<Checksum, Vec<u8>>,
    request: CommitRequest,
) -> Checked<ReceiveCommit> {
    if request.server_commit.is_some() {
        // The future of a server commit is large. The box keeps it out of the
        // future of a session with ref updates.
        return Box::pin(super::server_commit::finish(
            repo,
            policy,
            hooks,
            txn,
            named,
            commit_meta,
            request,
        ))
        .await;
    }
    let CommitRequest { updates, force, .. } = request;
    let own = repo.config().collection_id();
    let indices = check_names(own, &named, &updates)?;
    let paths: Arc<[String]> = indices.iter().map(|&i| named.paths[i].clone()).collect();
    let names: Vec<&Ref> = indices.iter().map(|&i| &named.refs[i]).collect();
    drop(indices);
    check_reply_fits(&updates)?;
    // The box keeps the futures of the dict check and of the commit reads out
    // of the future of the session.
    let (
        rules,
        Loaded {
            targets,
            session_commits,
            roots,
            parents,
            staged,
            fields,
        },
    ) = Box::pin(async {
        let outside = check_commit_meta_commits(&txn, &updates, &commit_meta).await?;
        let rules = select_rules(repo, policy, &names, &updates)?;
        let loaded = load_commits(&txn, &updates).await?;
        drop_attachment_meta(
            &txn,
            outside,
            &loaded.session_commits,
            &loaded.fields,
            &mut commit_meta,
        )
        .await?;
        Ok::<_, Failure>((rules, loaded))
    })
    .await?;
    let missing = walk::completeness(&txn, roots).await?;
    if missing.total > 0 {
        return Err(missing_objects(missing, "the trees of the commits reach"));
    }
    check_attachments(&txn, &targets, &staged, &fields).await?;
    check_bindings(
        repo,
        policy.verifies_ref_bindings(),
        named.one_way,
        &names,
        &targets,
    )?;
    drop((staged, fields));
    let commit_meta: HashMap<Checksum, Bytes> = commit_meta
        .into_iter()
        .map(|(commit, bytes)| (commit, Arc::new(bytes)))
        .collect();
    let mut stored = read_stored_for(repo, &rules, &targets, &commit_meta).await?;
    check_signatures(&rules, &commit_meta, &targets, &stored).await?;
    let incoming = filter_detached(repo, commit_meta).await?;
    let edits = plan(&rules, &targets, &mut stored, incoming);
    // The dicts that no edit took. The merge of the host entries takes them,
    // so they stay only where the session has hooks.
    let leftover = match hooks {
        Some(_) => stored,
        None => {
            drop(stored);
            HashMap::new()
        }
    };

    let (synced, edits) = futures_lite::future::zip(
        txn.sync_staged(),
        prepare_signatures(edits, hooks.is_none()),
    )
    .await;
    synced.map_err(Failure::Internal)?;
    let edits = edits?;
    let tips = repo
        .resolve_relpath_tips(Arc::clone(&paths))
        .await
        .map_err(Failure::Internal)?;
    let mut walks = Walks::new(parents);
    let mut chains = Vec::with_capacity(updates.len());
    for ((update, tip), rule) in updates.iter().zip(&tips).zip(&rules) {
        chains.push(match (update.new, tip) {
            // A forced update that the rule allows needs no walk.
            _ if force && rule.allow_non_fast_forward => None,
            // An update that only creates its ref needs no walk: the check
            // under the lock refuses it for a ref that is present.
            _ if rule.create_only => None,
            (Some(new), Some(tip)) if new != *tip => Some(walks.chain(&txn, new, *tip).await?),
            _ => None,
        });
    }

    // Declared before the update lock, so on each failure the carried value
    // drops after the lock is released. On success it goes to `after_update`,
    // after the lock is released.
    let mut carried: Option<Box<dyn Any + Send>> = None;
    let edits = match hooks {
        None => edits,
        Some(hooks) => {
            let UpdatePlan {
                metadata,
                carried: value,
            } = hooks
                .before_update(&hook_updates(&names, &updates))
                .await
                .map_err(HookRefusal::into_failure)?;
            carried = Some(value);
            add_host_entries(repo, &targets, edits, leftover, metadata).await?
        }
    };
    let held = repo.lock_update().await.map_err(Failure::Internal)?;
    let anchor = policy.regenerates_summary() && repo.config().collection_id().is_some();
    let (states, anchor_parent) = repo
        .read_ref_states(Arc::clone(&paths), anchor.then_some(OSTREE_METADATA_REF))
        .await
        .map_err(Failure::Internal)?;
    let refs: Vec<(&str, &str, bool)> = updates
        .iter()
        .zip(paths.iter())
        .map(|(update, path)| (update.name.as_str(), path.as_str(), update.new.is_some()))
        .collect();
    let current = check_ref_paths(&refs, &states)?;
    drop(refs);
    let mut changes = Vec::with_capacity(updates.len());
    for (i, update) in updates.iter().enumerate() {
        let changed = check_ref(
            &txn, update, &rules[i], force, current[i], chains[i], &mut walks,
        )
        .await?;
        changes.push(changed);
    }
    queue_detached(repo, &txn, edits).await?;
    for ((update, name), changed) in updates.iter().zip(&names).zip(&changes) {
        if !*changed {
            continue;
        }
        txn.set_ref(name, update.new.as_ref());
    }
    let changed = changes.contains(&true);
    // The future of the publication is large. The box keeps it out of the
    // future of the checks.
    let (stats, warnings) = Box::pin(publish(
        repo,
        policy,
        txn,
        held,
        changed,
        anchor_parent,
        session_commits,
    ))
    .await?;
    // The state of the checks is freed here, so it is not held while the
    // hook of the host runs.
    drop((walks, targets, chains, tips, paths, rules, states, changes));

    let refs = names
        .iter()
        .zip(&updates)
        .zip(&current)
        .map(|((&name, update), &old)| ReceiveRefOutcome {
            name: name.clone(),
            old,
            new: update.new,
        })
        .collect();
    let reply = updates
        .into_iter()
        .zip(current)
        .map(|(update, old)| RefOutcome {
            name: update.name,
            old,
            new: update.new,
        })
        .collect();
    let report = report(policy, refs, stats, warnings);
    if let (Some(hooks), Some(carried)) = (hooks, carried)
        && let Err(mut message) = hooks.after_update(&report, carried).await
    {
        hooks::cut(&mut message);
        return Err(Failure::Wire(remote::Error::Internal(message)));
    }
    Ok(ReceiveCommit { report, reply })
}

/// Returns the ref updates that [`ReceiveHooks::before_update`] gets: each
/// update of `updates` with the canonical name of its ref of `names`.
fn hook_updates(names: &[&Ref], updates: &[RefUpdate]) -> Vec<ReceiveRefUpdate> {
    names
        .iter()
        .zip(updates)
        .map(|(&name, update)| ReceiveRefUpdate {
            name: name.clone(),
            expected: update.expected,
            new: update.new,
        })
        .collect()
}

/// Publishes `txn`, whose ref writes are in its queue, under the update lock
/// `held`, and returns the statistics and the warnings of the commit.
///
/// `changed` is `true` if a ref changes. If the policy regenerates the
/// summary, a ref changes, and the repository has a collection id, the anchor
/// commit goes into the queue first. Its parent is `anchor_parent`, the tip
/// of the anchor ref that the caller read under the lock. A failure of the
/// anchor is `internal`, and nothing is published.
///
/// After the transaction commit, the call removes the partial marker of each
/// commit of `session_commits`, with the `fsync` rule of the transaction. If
/// the policy regenerates the summary and a ref changed, it writes each
/// summary. A failure of these two steps is a warning. Then the call releases
/// the update lock.
pub(super) async fn publish(
    repo: &Repo,
    policy: &dyn SessionPolicy,
    txn: Transaction,
    held: UpdateLockHeld,
    changed: bool,
    anchor_parent: Option<Result<Option<Checksum>>>,
    session_commits: Vec<Checksum>,
) -> Checked<(TransactionStats, Vec<ReceiveWarning>)> {
    let summary = policy.regenerates_summary() && changed;
    if summary && let Some(collection_id) = repo.config().collection_id().map(str::to_owned) {
        let parent = anchor_parent
            .transpose()
            .map_err(Failure::Internal)?
            .flatten();
        repo.stage_anchor_commit(&txn, &collection_id, parent, None)
            .await
            .map_err(Failure::Internal)?;
    }
    let marker_fsync = txn.fsync_flags().map_err(Failure::Internal)?.0;
    let stats = txn.commit_under(&held).await.map_err(Failure::Internal)?;
    let mut warnings: Vec<ReceiveWarning> = match repo
        .remove_partial_markers(session_commits, marker_fsync)
        .await
    {
        Ok(failed) => failed
            .into_iter()
            .map(|(commit, e)| ReceiveWarning {
                step: ReceiveStep::PartialMarker,
                message: format!("the partial marker of commit {commit}: {e}"),
            })
            .collect(),
        Err(e) => vec![ReceiveWarning {
            step: ReceiveStep::PartialMarker,
            message: format!("the partial markers: {e}"),
        }],
    };
    if summary && let Err(warning) = write_summary(repo, policy.summary_keys()).await {
        warnings.push(warning);
    }
    drop(held);
    Ok((stats, warnings))
}

/// Returns the report of a session that committed under `policy`, with the
/// outcomes `refs`.
pub(super) fn report(
    policy: &dyn SessionPolicy,
    refs: Vec<ReceiveRefOutcome>,
    stats: TransactionStats,
    warnings: Vec<ReceiveWarning>,
) -> ReceiveReport {
    ReceiveReport {
        refs,
        stats,
        warnings,
        group: policy.group().map(str::to_owned),
    }
}

/// Checks the ref names of the updates against the refs of `Hello`, and
/// returns the index in `named` of the ref of each update, in order.
///
/// - Each ref name is valid.
/// - No update writes a commit to a local ref of 64 lowercase hex characters,
///   after the map of `@ID:NAME` with `ID` the collection id `own` of the
///   repository to the local ref `NAME`.
/// - The message holds one update at least.
/// - Each update names a ref of `Hello`, with the text of `Hello`, once.
fn check_names(own: Option<&str>, named: &Named<'_>, updates: &[RefUpdate]) -> Checked<Vec<usize>> {
    // `Hello` holds the canonical ref of each of its names. Read the other
    // names here, so that an invalid name is `invalid-ref` before the
    // protocol check.
    let index = named.by_name();
    for update in updates {
        let writes = update.new.is_some();
        match index.get(update.name.as_str()) {
            Some(&i) => check_shape(&named.refs[i], &update.name, writes)?,
            None => {
                commit_ref(own, &update.name, writes)?;
            }
        }
    }
    if updates.is_empty() {
        return Err(protocol("the Commit message holds no ref update".into()));
    }
    Named::indices(&index, updates.iter().map(|u| u.name.as_str()), "updated")
}

/// Checks that the `CommitReply` of `updates` fits in a frame of
/// [`MAX_FRAME`].
///
/// The check uses the longest outcome that each update can get. That
/// outcome holds the name and the new commit of the update, and an old
/// commit. An update that expects its ref absent, or that takes any state,
/// does not state the old commit. Under the lock, the ref can still hold one.
///
/// A reply over the limit is `limit-exceeded`. The check runs before any ref
/// write.
fn check_reply_fits(updates: &[RefUpdate]) -> Checked<()> {
    let any_commit = Checksum::from_bytes([0; 32]);
    let longest = Message::CommitReply(
        updates
            .iter()
            .map(|u| RefOutcome {
                name: u.name.clone(),
                old: Some(any_commit),
                new: u.new,
            })
            .collect(),
    );
    let body = longest.encode_body().map_err(Failure::Wire)?;
    let len = body.len() as u64 + 1;
    if len > u64::from(MAX_FRAME) {
        return Err(Failure::Wire(remote::Error::LimitExceeded(format!(
            "the reply to the {} ref updates of Commit can need a frame of {len} bytes, over the \
             limit {MAX_FRAME}",
            updates.len()
        ))));
    }
    Ok(())
}

/// Returns the commits of the dicts of `commit_meta` that the session did
/// not stage and that no update names, in the order of their checksums.
fn outside_commits(
    txn: &Transaction,
    updates: &[RefUpdate],
    commit_meta: &HashMap<Checksum, Vec<u8>>,
) -> Vec<Checksum> {
    let new: HashSet<&Checksum> = updates.iter().filter_map(|u| u.new.as_ref()).collect();
    let mut outside: Vec<Checksum> = commit_meta
        .keys()
        .filter(|commit| !(new.contains(commit) || txn.is_staged(commit, ObjectType::Commit)))
        .copied()
        .collect();
    outside.sort_unstable();
    outside
}

/// Checks that each detached metadata dict of the session belongs to a commit
/// of the session or to a commit that the repository holds.
///
/// A commit of the session is a commit that the session staged, or the new
/// commit of an update. A dict for a held commit outside the session goes to
/// [`drop_attachment_meta`]. A dict for a commit that is neither is
/// `protocol`. The reads of the held commits run in one trip to the blocking
/// pool, and only if the session has a dict outside the session.
///
/// Returns the commits of the dicts outside the session, in the order of
/// their checksums. The repository holds each of them.
async fn check_commit_meta_commits(
    txn: &Transaction,
    updates: &[RefUpdate],
    commit_meta: &HashMap<Checksum, Vec<u8>>,
) -> Checked<Vec<Checksum>> {
    let outside = outside_commits(txn, updates, commit_meta);
    if outside.is_empty() {
        return Ok(outside);
    }
    let repo = txn.repo().clone();
    let held: Vec<(Checksum, bool)> = ostrya_rt::unblock(move || {
        outside
            .into_iter()
            .map(|commit| {
                repo.has_object_blocking(ObjectType::Commit, &commit)
                    .map(|held| (commit, held))
            })
            .collect::<Result<_>>()
    })
    .await
    .map_err(Failure::Internal)?;
    if let Some((commit, _)) = held.iter().find(|(_, held)| !held) {
        return Err(protocol(format!(
            "detached metadata for commit {commit}, which the session did not stage, no ref \
             update names, and the repository does not hold"
        )));
    }
    Ok(held.into_iter().map(|(commit, _)| commit).collect())
}

/// Drops the dict of each commit that the session did not stage and that no
/// update names, if an entry of field 2 of a commit of the session, or of a
/// held attachment below the session, names that commit.
///
/// `outside` is the list that [`check_commit_meta_commits`] returns: the
/// commits of `commit_meta` that the session did not stage and that no update
/// names. The repository holds each of them. A named commit is an attachment
/// that the repository holds. The repository held that commit and its dict
/// before the session, and no rule of the session covers a change to them. A
/// staged attachment is a commit that the repository did not hold before the
/// session, and its dict merges as the dict of each other staged commit.
/// `session_commits` lists the commits of the session, and `fields` holds
/// their field 2, as [`load_commits`] reads it. An entry with an empty name
/// or a checksum that is not 32 bytes names no commit.
///
/// If the entries of `fields` name each commit of `outside`, the function
/// reads nothing. Otherwise it reads field 2 of the held attachments, one
/// level at a time. The first level is each commit that an entry of `fields`
/// names and that is not a commit of the session. The next level is each
/// commit that an entry of field 2 of a commit of the level names, that is
/// not a commit of the session, and that no level before it holds. The walk
/// reads the commit objects alone, and each commit one time. The reads of
/// one level run in one trip to the blocking pool. The walk stops when the
/// entries name each commit of `outside`, also in the middle of a level, or
/// when a level is empty. A commit that the repository does not hold names
/// no commit. The walk reads no partial marker.
///
/// A dict for such a commit that no entry names is `protocol`. Without this
/// check, a dict can edit the detached metadata of a commit that no rule of
/// the message covers.
///
/// A commit of the walk whose field 2 does not decode is a failure on the
/// server side ([`Error::Core`]), as for a held attachment in
/// [`check_attachments`].
async fn drop_attachment_meta(
    txn: &Transaction,
    outside: Vec<Checksum>,
    session_commits: &[Checksum],
    fields: &HashMap<Checksum, Vec<(String, Vec<u8>)>>,
    commit_meta: &mut HashMap<Checksum, Vec<u8>>,
) -> Checked<()> {
    if outside.is_empty() {
        return Ok(());
    }
    let named: HashSet<Checksum> = fields
        .values()
        .flatten()
        .filter(|(name, _)| !name.is_empty())
        .filter_map(|(_, bytes)| Checksum::from_ay(bytes).ok())
        .collect();
    let mut unnamed: HashSet<Checksum> = outside
        .iter()
        .filter(|commit| !named.contains(commit))
        .copied()
        .collect();
    if !unnamed.is_empty() {
        let mut seen: HashSet<Checksum> = session_commits.iter().copied().collect();
        let mut level: Vec<Checksum> = named
            .into_iter()
            .filter(|commit| seen.insert(*commit))
            .collect();
        while !level.is_empty() && !unnamed.is_empty() {
            level.sort_unstable();
            let repo = txn.repo().clone();
            (level, seen, unnamed) = ostrya_rt::unblock(move || {
                let mut below = Vec::new();
                for commit in level {
                    let Some(bytes) =
                        repo.held_object_bytes_blocking(ObjectType::Commit, &commit)?
                    else {
                        continue;
                    };
                    for entry in related::parse_attachments(&bytes)? {
                        if entry.name.is_empty() {
                            continue;
                        }
                        let Ok(named) = entry.checksum else {
                            continue;
                        };
                        unnamed.remove(&named);
                        if seen.insert(named) {
                            below.push(named);
                        }
                    }
                    if unnamed.is_empty() {
                        break;
                    }
                }
                Ok::<_, Error>((below, seen, unnamed))
            })
            .await
            .map_err(Failure::Internal)?;
        }
    }
    for commit in outside {
        if unnamed.contains(&commit) {
            return Err(protocol(format!(
                "detached metadata for commit {commit}, which the session did not stage, no ref \
                 update names, and no commit of the session or held attachment below it names \
                 as an attachment"
            )));
        }
        commit_meta.remove(&commit);
    }
    Ok(())
}

/// Returns the rule of each update, in order.
///
/// In a repository with a collection id, an update of the local anchor ref
/// is `ref-denied`. `names` gives the canonical ref of each update. Then
/// `policy` gives the rule of each update, or its `ref-denied` refusal.
fn select_rules<'a>(
    repo: &Repo,
    policy: &'a dyn SessionPolicy,
    names: &[&Ref],
    updates: &[RefUpdate],
) -> Checked<Vec<UpdateRule<'a>>> {
    let own = repo.config().collection_id();
    names
        .iter()
        .zip(updates)
        .map(|(&name, update)| {
            check_anchor(own.is_some(), name)?;
            policy.rule(name, update, own)
        })
        .collect()
}

/// Refuses the local ref `ostree-metadata` with `ref-denied` if `collection`
/// is `true`: in a repository with a collection id, the ref holds the
/// collection anchor commit, which the server writes.
pub(super) fn check_anchor(collection: bool, name: &Ref) -> Checked<()> {
    match name {
        Ref::Local { name } if collection && name == OSTREE_METADATA_REF => Err(ref_denied(
            format!("ref '{name}' holds the collection anchor commit, which the server writes"),
        )),
        _ => Ok(()),
    }
}

/// The commits of the session, as [`load_commits`] reads them.
struct Loaded {
    /// The new commits of the updates, each once, in the order of the
    /// updates.
    targets: Vec<Target>,
    /// Every commit of the session: the staged commits and the new commits.
    session_commits: Vec<Checksum>,
    /// The root dirtree and root dirmeta of each commit of the session.
    roots: Vec<(Checksum, Checksum)>,
    /// The parent of each commit of the session.
    parents: Parents,
    /// The commits that the session staged, or none if `fields` is empty.
    staged: HashSet<Checksum>,
    /// The field 2 of each commit of the session whose field 2 is not empty.
    fields: HashMap<Checksum, Vec<(String, Vec<u8>)>>,
}

/// One commit as [`read_commits`] returns it.
enum ReadCommit {
    /// A new commit that neither the session nor the repository holds.
    Absent,
    /// A commit that does not parse.
    Unparsable(ostrya_core::Error),
    /// A new commit, with its bytes.
    Target(Vec<u8>, Commit),
    /// A staged commit that no update names: its root, its parent, and its
    /// field 2.
    Other(
        (Checksum, Checksum),
        Option<Checksum>,
        Vec<(String, Vec<u8>)>,
    ),
}

/// Reads and parses the commits of the session.
///
/// The commits of the session are the new commit of each update and each
/// staged commit. The reads and the parses run in one trip to the blocking
/// pool. The read of a commit tries the staging directory before `objects/`.
///
/// A new commit that is neither staged nor present is `missing-objects`. A
/// staged commit that does not parse is `protocol`. A stored commit that does
/// not parse is a failure on the server side.
async fn load_commits(txn: &Transaction, updates: &[RefUpdate]) -> Checked<Loaded> {
    let mut news: Vec<(Checksum, Vec<usize>)> = Vec::new();
    let mut index: HashMap<Checksum, usize> = HashMap::new();
    for (i, update) in updates.iter().enumerate() {
        let Some(new) = update.new else {
            continue;
        };
        match index.entry(new) {
            Entry::Occupied(at) => news[*at.get()].1.push(i),
            Entry::Vacant(at) => {
                at.insert(news.len());
                news.push((new, vec![i]));
            }
        }
    }
    let mut reads: Vec<(Checksum, bool)> = news
        .iter()
        .map(|(new, _)| (*new, txn.is_staged(new, ObjectType::Commit)))
        .collect();
    reads.extend(
        txn.staged_of_type(ObjectType::Commit)
            .into_iter()
            .filter(|commit| !index.contains_key(commit))
            .map(|commit| (commit, true)),
    );
    let count = news.len();
    let mut read = read_commits(txn, reads.clone(), count)
        .await
        .map_err(Failure::Internal)?;
    let others = read.split_off(count);

    let parse_failure = |checksum: &Checksum, staged: bool, e: ostrya_core::Error| {
        let message = format!("commit {checksum} does not parse: {e}");
        if staged {
            protocol(message)
        } else {
            Failure::Internal(Error::InvalidFormat(message))
        }
    };
    let mut loaded = Loaded {
        targets: Vec::with_capacity(count),
        session_commits: Vec::with_capacity(reads.len()),
        roots: Vec::with_capacity(reads.len()),
        parents: Parents::with_capacity(reads.len()),
        staged: HashSet::new(),
        fields: HashMap::new(),
    };
    let mut absent = Missing::default();
    for (((checksum, staged), read), (_, updates)) in reads.iter().zip(read).zip(news) {
        match read {
            ReadCommit::Absent => absent.add(ObjectName::new(*checksum, ObjectType::Commit)),
            ReadCommit::Unparsable(e) => return Err(parse_failure(checksum, *staged, e)),
            ReadCommit::Target(bytes, mut commit) => {
                loaded.session_commits.push(*checksum);
                loaded
                    .roots
                    .push((commit.root_dirtree, commit.root_dirmeta));
                loaded.parents.insert(*checksum, commit.parent);
                let related = std::mem::take(&mut commit.related);
                if !related.is_empty() {
                    loaded.fields.insert(*checksum, related);
                }
                loaded.targets.push(Target {
                    checksum: *checksum,
                    bytes: Arc::new(bytes),
                    commit,
                    updates,
                });
            }
            ReadCommit::Other(..) => unreachable!("a new commit is read with its bytes"),
        }
    }
    if absent.total > 0 {
        return Err(missing_objects(absent, "the ref updates name"));
    }
    for ((checksum, staged), read) in reads[count..].iter().zip(others) {
        match read {
            ReadCommit::Other(root, parent, related) => {
                loaded.session_commits.push(*checksum);
                loaded.roots.push(root);
                loaded.parents.insert(*checksum, parent);
                if !related.is_empty() {
                    loaded.fields.insert(*checksum, related);
                }
            }
            ReadCommit::Unparsable(e) => return Err(parse_failure(checksum, *staged, e)),
            ReadCommit::Absent | ReadCommit::Target(..) => {
                unreachable!("a staged commit is read without its bytes")
            }
        }
    }
    // Only the checks of field 2 read the staged commits.
    if !loaded.fields.is_empty() {
        loaded.staged = reads
            .iter()
            .filter(|(_, staged)| *staged)
            .map(|(checksum, _)| *checksum)
            .collect();
    }
    Ok(loaded)
}

/// Reads and parses `reads` on the blocking pool.
///
/// Each entry of `reads` is a commit and a flag that is `true` if the session
/// staged the commit. The first `targets` entries are new commits. A new
/// commit keeps its bytes, and it reads as absent if the repository does not
/// hold it.
async fn read_commits(
    txn: &Transaction,
    reads: Vec<(Checksum, bool)>,
    targets: usize,
) -> Result<Vec<ReadCommit>> {
    let mode = txn.repo().mode();
    let repo = txn.repo().clone();
    let staging = txn.staging_dir().clone();
    ostrya_rt::unblock(move || {
        reads
            .into_iter()
            .enumerate()
            .map(|(i, (checksum, staged))| {
                let bytes = if staged {
                    let name = flat_name(&checksum, ObjectType::Commit, mode);
                    staging.read_capped(&name, MAX_METADATA_SIZE)?
                } else {
                    match repo.held_object_bytes_blocking(ObjectType::Commit, &checksum)? {
                        Some(bytes) => bytes,
                        None => return Ok(ReadCommit::Absent),
                    }
                };
                Ok(match Commit::parse(&bytes) {
                    Err(e) => ReadCommit::Unparsable(e),
                    Ok(commit) if i < targets => ReadCommit::Target(bytes, commit),
                    Ok(commit) => ReadCommit::Other(
                        (commit.root_dirtree, commit.root_dirmeta),
                        commit.parent,
                        commit.related,
                    ),
                })
            })
            .collect()
    })
    .await
}

/// Returns the `missing-objects` failure for `missing`.
///
/// `what` completes the phrase "objects that ..." of the message.
pub(super) fn missing_objects(missing: Missing, what: &str) -> Failure {
    let mut message = format!(
        "{} objects that {what} are neither staged nor present",
        missing.total
    );
    if missing.listed.len() < missing.total {
        message.push_str(&format!(", the first {} listed", missing.listed.len()));
    }
    Failure::Wire(remote::Error::MissingObjects {
        message,
        missing: missing.listed,
    })
}

/// Checks the attachments of each commit of the session.
///
/// The checked commits are the staged commits, and each new commit that the
/// repository holds with a partial marker: the session completes the tree of
/// that commit, and the publication removes its marker. A new commit that
/// the repository holds with no partial marker is a held commit. The commits
/// of the session with a field 2 that is not empty are taken in order: the
/// new commits in the order of the updates, then the other staged commits in
/// the order of their checksums. These checks run in order, and the first
/// failure is the refusal:
///
/// - Each entry of field 2 of each commit of the session has a name that is
///   not empty and a 32-byte checksum, in the order of the commits
///   (`protocol` for a checked commit, `internal` for a held commit).
/// - Field 2 of each held attachment with no partial marker decodes, and
///   each of its entries has a name that is not empty and a 32-byte checksum
///   (`internal`).
/// - Each attachment is staged or held (`missing-objects`). The failure lists
///   each attachment that is neither, in level order, and in the order of the
///   commits that name them in a level.
/// - Each held attachment is complete (`missing-objects`, with no object
///   listed), in the same order.
///
/// An attachment that is a commit of the session is complete, because the
/// completeness walk ran over its tree. A new commit that the repository
/// marks partial is such an attachment too. A repository that the `ostree`
/// command wrote can hold a commit complete with its own attachments absent.
/// So the attachments of each commit of the session get these checks: the
/// first level is the attachments that field 2 of these commits names. For
/// each held attachment with no partial marker, the check reads field 2 from
/// its commit object, and each attachment that it names gets these checks,
/// one level at a time, until a level is empty. An entry that names a commit
/// of the session passes, and its own entries are in the first level. The
/// check takes field 2 of a commit of the session from `fields`, reads each
/// other commit object one time, and reads no tree. The reads of the partial
/// markers of the held new commits run in one trip to the blocking pool, and
/// the reads of the held attachments, at all levels, in one more trip.
async fn check_attachments(
    txn: &Transaction,
    targets: &[Target],
    staged: &HashSet<Checksum>,
    fields: &HashMap<Checksum, Vec<(String, Vec<u8>)>>,
) -> Checked<()> {
    if fields.is_empty() {
        return Ok(());
    }
    // The new commits that the repository holds with a field 2 that is not
    // empty. Of these, each commit with a partial marker is checked.
    let held: Vec<Checksum> = targets
        .iter()
        .map(|t| t.checksum)
        .filter(|c| !staged.contains(c) && fields.contains_key(c))
        .collect();
    let partial: HashSet<Checksum> = if held.is_empty() {
        HashSet::new()
    } else {
        let repo = txn.repo().clone();
        ostrya_rt::unblock(move || {
            held.into_iter()
                .filter_map(|commit| match repo.commit_state_blocking(&commit) {
                    Ok(CommitState::Partial) => Some(Ok(commit)),
                    Ok(CommitState::Normal) => None,
                    Err(e) => Some(Err(e)),
                })
                .collect::<Result<_>>()
        })
        .await
        .map_err(Failure::Internal)?
    };
    let news: HashSet<&Checksum> = targets.iter().map(|t| &t.checksum).collect();
    // Each commit of `fields` that no update names is a staged commit.
    let mut others: Vec<&Checksum> = fields.keys().filter(|c| !news.contains(c)).collect();
    others.sort_unstable();
    let naming = targets.iter().map(|t| &t.checksum).chain(others);
    // Each attachment, the commit that first names it, and the name of that
    // entry.
    let mut known = HashSet::new();
    let mut named: Vec<(Checksum, Checksum, Cow<'_, str>)> = Vec::new();
    for commit in naming {
        let Some(field) = fields.get(commit) else {
            continue;
        };
        // A new commit that the repository holds complete is a held commit,
        // so a defect in its field 2 is a failure on the server side.
        let checked = staged.contains(commit) || partial.contains(commit);
        let entries = related::borrowed_attachments(commit, field).map_err(|e| {
            if checked {
                protocol(e.to_string())
            } else {
                Failure::Internal(e)
            }
        })?;
        for (name, attachment) in entries {
            if known.insert(attachment) {
                named.push((attachment, *commit, Cow::Borrowed(name)));
            }
        }
    }
    // The staged and the new commits. The walk reads none of them, and an
    // entry that names one of them passes: its own entries are in `named`.
    let stop: HashSet<Checksum> = staged.iter().chain(news.iter().copied()).copied().collect();
    let held: Vec<Checksum> = named
        .iter()
        .map(|(attachment, ..)| *attachment)
        .filter(|attachment| !stop.contains(attachment))
        .collect();
    let (states, deep) = if held.is_empty() {
        (HashMap::new(), Vec::new())
    } else {
        let repo = txn.repo().clone();
        ostrya_rt::unblock(move || held_levels_blocking(&repo, held, known, &stop))
            .await
            .map_err(Failure::Internal)?
    };
    named.extend(
        deep.into_iter()
            .map(|(attachment, naming, name)| (attachment, naming, Cow::Owned(name))),
    );
    let mut absent = Missing::default();
    for (attachment, ..) in &named {
        if states.get(attachment) == Some(&HeldAttachment::Absent) {
            absent.add(ObjectName::new(*attachment, ObjectType::Commit));
        }
    }
    if absent.total > 0 {
        return Err(missing_objects(
            absent,
            "the commits of the session and the held attachments below them name as attachments",
        ));
    }
    for (attachment, naming, name) in named {
        if states.get(&attachment) == Some(&HeldAttachment::Partial) {
            return Err(Failure::Wire(remote::Error::MissingObjects {
                message: related::partial_attachment(naming, &name, &attachment).to_string(),
                missing: Vec::new(),
            }));
        }
    }
    Ok(())
}

/// Reads the held attachments `held`, then the attachments below them, one
/// level at a time, on the calling thread.
///
/// `held` is the first level. For each attachment of a level, the call reads
/// its state. For an attachment with no partial marker, it also reads field 2
/// from the commit object. Each entry that names a commit that is not in
/// `known` adds that commit to `known`. If the commit is not in `stop`, the
/// entry also adds it to the next level. The walk stops at an empty level.
/// So the call reads each commit object one time, and reads no tree.
///
/// Returns the state of each attachment that the call read, and each entry
/// below the first level that added a commit to a level, as the commit, the
/// held attachment that names it, and the name of the entry, in level order.
///
/// # Errors
///
/// - [`Error::InvalidRelations`] with the held attachment, for the first entry
///   of its field 2 with an empty name or with a checksum that is not 32
///   bytes.
/// - Each error of [`related::held_attachment_blocking`].
fn held_levels_blocking(
    repo: &Repo,
    held: Vec<Checksum>,
    mut known: HashSet<Checksum>,
    stop: &HashSet<Checksum>,
) -> Result<HeldLevels> {
    let mut states = HashMap::new();
    let mut deep = Vec::new();
    let mut level = held;
    while !level.is_empty() {
        let mut next = Vec::new();
        for attachment in level {
            let state =
                related::held_attachment_blocking(repo, None, &attachment, |_, entries| {
                    related::checked_entries(RelationField::Attachments, Some(attachment), entries)
                })?;
            let state = match state {
                HeldAttachment::Absent => HeldAttachment::Absent,
                HeldAttachment::Partial => HeldAttachment::Partial,
                HeldAttachment::Complete { value } => {
                    for (name, below) in value {
                        if known.insert(below) && !stop.contains(&below) {
                            next.push(below);
                            deep.push((below, attachment, name));
                        }
                    }
                    HeldAttachment::Complete { value: () }
                }
            };
            states.insert(attachment, state);
        }
        level = next;
    }
    Ok((states, deep))
}

/// Checks the ref binding and the collection binding of each new commit,
/// for each ref that the commit is the new value of.
///
/// `names` holds the canonical ref of each update. A commit with the key
/// `ostree.ref-binding` must list the name of each of its refs, without the
/// remote part of a remote ref and without the `@ID:` part of a collection
/// ref. So a commit with an empty list fails. A commit without the key
/// passes. With `ref_bindings` `false`, this part of the check does not run.
///
/// The `ostree.collection-binding` of each new commit is the id of the
/// namespace of each of its refs:
///
/// - A local ref takes the collection id of the repository. In a repository
///   with no collection id, a commit with the key fails and a commit without
///   the key passes, but the check of a one-way stream does not read the key.
/// - A collection ref `@ID:NAME` takes `ID`. A commit without the key fails,
///   because a commit with no collection binding goes to the local refs
///   alone.
/// - A remote ref of a one-way stream takes the collection id of the
///   repository. In a repository with no collection id, the check does not
///   read the key. A commit without the key passes.
fn check_bindings(
    repo: &Repo,
    ref_bindings: bool,
    one_way: bool,
    names: &[&Ref],
    targets: &[Target],
) -> Checked<()> {
    let own = repo.config().collection_id();
    let mismatch = |message: String| Failure::Wire(remote::Error::BindingMismatch(message));
    for target in targets {
        let commit = &target.checksum;
        let listed = target.commit.metadata_value("ostree.ref-binding").is_some();
        let bindings = target.commit.ref_bindings();
        let bound = target.commit.collection_binding();
        for &i in &target.updates {
            let name = names[i];
            if ref_bindings && listed && !bindings.contains(&name.name()) {
                return Err(mismatch(format!(
                    "commit {commit} is bound to the refs {bindings:?}, which do not hold '{}'",
                    name.name()
                )));
            }
            let wanted = match name {
                Ref::Collection { id, .. } => Some(id.as_str()),
                // A one-way stream writes a local ref of a repository with
                // no collection id with no collection check.
                Ref::Local { .. } if one_way && own.is_none() => continue,
                Ref::Local { .. } => own,
                Ref::Remote { .. } if own.is_some() => own,
                Ref::Remote { .. } => continue,
            };
            match (bound, wanted) {
                (Some(bound), Some(id)) if id == bound => {}
                (Some(bound), Some(id)) => {
                    return Err(mismatch(format!(
                        "commit {commit} is bound to the collection '{bound}', not '{id}' of \
                         ref '{name}'"
                    )));
                }
                (Some(bound), None) => {
                    return Err(mismatch(format!(
                        "commit {commit} is bound to the collection '{bound}', and ref '{name}' \
                         is a local ref of a repository with no collection id"
                    )));
                }
                (None, _) if matches!(name, Ref::Collection { .. }) => {
                    return Err(mismatch(format!(
                        "commit {commit} has no collection binding, which a ref of the \
                         collection of ref '{name}' needs"
                    )));
                }
                (None, _) => {}
            }
        }
    }
    Ok(())
}

/// Returns the trusted keys of the rules of the updates `indices`, each set
/// once.
///
/// The flag of a set is `true` if each rule with the set accepts a commit
/// with no signature.
fn target_keys<'a>(
    rules: &[UpdateRule<'a>],
    indices: &[usize],
) -> Vec<(&'a Arc<TrustedKeys>, bool)> {
    let mut keys: Vec<(&Arc<TrustedKeys>, bool)> = Vec::new();
    for &i in indices {
        let rule = &rules[i];
        if let ReceiveVerify::Keys(held) = rule.verify {
            match keys.iter_mut().find(|(k, _)| Arc::ptr_eq(k, held)) {
                Some((_, unsigned)) => *unsigned &= rule.allow_unsigned,
                None => keys.push((held, rule.allow_unsigned)),
            }
        }
    }
    keys
}

/// Returns the union of the server keys of the rules of the updates
/// `indices`, each key once.
fn target_signers<'a>(rules: &[UpdateRule<'a>], indices: &[usize]) -> Vec<&'a Arc<SigningKey>> {
    let mut signers: Vec<&Arc<SigningKey>> = Vec::new();
    for &i in indices {
        for signer in rules[i].signers {
            if !signers.iter().any(|s| Arc::ptr_eq(s, signer)) {
                signers.push(signer);
            }
        }
    }
    signers
}

/// Reads the stored detached metadata of each commit whose dict a later step
/// reads.
///
/// These commits are each new commit with a signature verification or a
/// server key, and each commit with an incoming dict.
async fn read_stored_for(
    repo: &Repo,
    rules: &[UpdateRule<'_>],
    targets: &[Target],
    commit_meta: &HashMap<Checksum, Bytes>,
) -> Checked<HashMap<Checksum, Option<Bytes>>> {
    let mut commits: Vec<Checksum> = targets
        .iter()
        .filter(|t| {
            !target_keys(rules, &t.updates).is_empty()
                || !target_signers(rules, &t.updates).is_empty()
                || commit_meta.contains_key(&t.checksum)
        })
        .map(|t| t.checksum)
        .collect();
    let listed: HashSet<Checksum> = commits.iter().copied().collect();
    commits.extend(commit_meta.keys().filter(|c| !listed.contains(c)).copied());
    let stored = read_stored(repo, commits.clone()).await?;
    Ok(commits.into_iter().zip(stored).collect())
}

/// Signs the server commit `commit`, whose bytes are `payload`, with each key
/// of `signers` once, under the update lock, and queues the signatures in
/// `txn`.
///
/// The call reads the dict that the repository holds for the commit. A key
/// that signed the commit in that dict, or in a signature that a key before
/// it made, makes no signature. A merged dict over the size limit is
/// `limit-exceeded`. The search for a signature gives `payload` to each
/// verifier with no copy.
pub(super) async fn sign_server_commit(
    repo: &Repo,
    txn: &Transaction,
    commit: Checksum,
    payload: &Arc<Vec<u8>>,
    signers: &[Arc<SigningKey>],
) -> Checked<()> {
    let mut unique: Vec<&Arc<SigningKey>> = Vec::with_capacity(signers.len());
    for signer in signers {
        if !unique.iter().any(|s| Arc::ptr_eq(s, signer)) {
            unique.push(signer);
        }
    }
    if unique.is_empty() {
        return Ok(());
    }
    let stored = read_stored(repo, vec![commit]).await?.pop().flatten();
    let edit = Edit {
        commit,
        payload: payload.into(),
        stored,
        incoming: None,
        keep: Arc::default(),
        signers: unique,
        signatures: Vec::new(),
        oversize: None,
    };
    // The read of the stored dict and the plan run under the update lock, so
    // the dict cannot change before the queue, and the queue reads it no
    // second time.
    let edits = prepare_signatures(vec![edit], true).await?;
    queue_edits(txn, edits)
}

/// Reads the detached metadata dict that the repository holds for each of
/// `commits`, in order.
///
/// The reads run in one trip to the blocking pool. The result is `None` for no
/// file and for the zero-length "no metadata" marker.
async fn read_stored(repo: &Repo, commits: Vec<Checksum>) -> Checked<Vec<Option<Bytes>>> {
    let repo = repo.clone();
    ostrya_rt::unblock(move || {
        commits
            .iter()
            .map(|commit| {
                let bytes = repo.held_object_bytes_blocking(ObjectType::CommitMeta, commit)?;
                Ok(bytes.filter(|b| !b.is_empty()).map(Arc::new))
            })
            .collect::<Result<Vec<_>>>()
    })
    .await
    .map_err(Failure::Internal)
}

/// Returns the merge of `incoming` into `stored`, each a serialized dict.
///
/// The result is `None` if neither holds a dict. Under a key of `keep` that
/// `stored` holds, the stored value stays.
fn merged_dict(
    stored: Option<&[u8]>,
    incoming: Option<&[u8]>,
    keep: &[String],
) -> Result<Option<Value>> {
    let stored = stored.map(parse_signature_dict).transpose()?.flatten();
    match incoming.map(parse_signature_dict).transpose()?.flatten() {
        Some(incoming) => merge_detached(stored, incoming, keep).map(Some),
        None => Ok(stored),
    }
}

/// Returns an empty `a{sv}` dict.
fn empty_dict() -> Value {
    Value::Array(Vec::new())
}

/// Verifies the signatures of each new commit against the rule of each of its
/// updates, once for each set of trusted keys.
///
/// The verification reads the union of the stored detached metadata of the
/// commit and the incoming dict, before the rule of `[ex-ostrya]
/// keep-detached-related` applies. This function builds the union on the
/// blocking pool.
///
/// A set whose rules accept a commit with no signature skips the commit if
/// the union holds no blob under a signature key. A commit with a blob must
/// pass the verification on each axis of the set. The message of a failure
/// names the commit. No other commit gets a verification.
async fn check_signatures(
    rules: &[UpdateRule<'_>],
    commit_meta: &HashMap<Checksum, Bytes>,
    targets: &[Target],
    stored: &HashMap<Checksum, Option<Bytes>>,
) -> Checked<()> {
    for target in targets {
        let checksum = target.checksum;
        let keys = target_keys(rules, &target.updates);
        if keys.is_empty() {
            continue;
        }
        let stored = stored.get(&checksum).cloned().flatten();
        let incoming = commit_meta.get(&checksum).cloned();
        let dict = ostrya_rt::unblock(move || {
            merged_dict(
                stored.as_deref().map(Vec::as_slice),
                incoming.as_deref().map(Vec::as_slice),
                &[],
            )
        })
        .await
        .map_err(Failure::Internal)?;
        let subject = format!("commit {checksum}");
        let signed = keys.iter().any(|(_, allow_unsigned)| *allow_unsigned)
            && dict.as_ref().is_some_and(has_signature);
        for (held, allow_unsigned) in keys {
            if allow_unsigned && !signed {
                continue;
            }
            held.check(&subject, &target.bytes, dict.as_ref())
                .await
                .map_err(|e| match e {
                    Error::Signature(message) => {
                        Failure::Wire(remote::Error::SignatureRequired(message))
                    }
                    other => Failure::Internal(other),
                })?;
        }
    }
    Ok(())
}

/// Returns `true` if the detached-metadata dict `dict` holds a blob under a
/// key of [`SIGNATURE_KEYS`].
///
/// The check copies no blob.
fn has_signature(dict: &Value) -> bool {
    SIGNATURE_KEYS.iter().any(|key| {
        let Some(value) = dict.dict_get(key) else {
            return false;
        };
        let array = match value.as_variant() {
            Some((_, inner)) => inner,
            None => value,
        };
        array
            .as_array()
            .is_some_and(|blobs| blobs.iter().any(|blob| blob.as_bytes().is_some()))
    })
}

/// Checks the ref paths under the lock and returns the commit that each ref
/// names.
///
/// These cases are `ref-denied`:
///
/// - A ref that is an alias.
/// - A path that a ref write cannot replace.
/// - Two refs that the message writes, where one ref names a directory of
///   the other.
///
/// In these cases no ref write can complete, so the check runs before any
/// write goes into the queue.
/// Each entry of `refs` is the name of a ref of the message, its path under
/// `refs/`, and `true` if the message writes a commit to it. `states` holds
/// the state of each path, in the same order.
pub(super) fn check_ref_paths(
    refs: &[(&str, &str, bool)],
    states: &[RefFileState],
) -> Checked<Vec<Option<Checksum>>> {
    let mut current = Vec::with_capacity(refs.len());
    for (&(name, _, _), state) in refs.iter().zip(states) {
        current.push(match state {
            RefFileState::Absent => None,
            RefFileState::Commit(commit) => Some(*commit),
            RefFileState::Alias => {
                return Err(ref_denied(format!(
                    "ref '{name}' is an alias of another ref"
                )));
            }
            RefFileState::NotARef(_) => {
                return Err(ref_denied(format!(
                    "ref '{name}' names a directory or a path below a ref file \
                     or an alias, which a ref write cannot replace"
                )));
            }
        });
    }
    let writes = || refs.iter().filter(|&&(_, _, writes)| writes);
    let entries: Vec<(&str, bool)> = writes().map(|&(_, relpath, _)| (relpath, true)).collect();
    if let Some((outer, inner)) = nested_ref_paths(&entries) {
        let write_name = |i| writes().nth(i).expect("an index of a write entry").0;
        let (name, other) = (write_name(inner), write_name(outer));
        return Err(ref_denied(format!(
            "ref '{name}' names a path below ref '{other}' of the same message"
        )));
    }
    Ok(current)
}

/// Checks one update against the state of its ref under the lock.
///
/// The result is `true` if the update changes the ref. A delete of an absent
/// ref and an update to the current commit change nothing.
///
/// - The ref must be in the state that the update expects, also for `Any`.
/// - A rule that only creates its ref refuses a commit for a ref that is
///   present, also the current commit (`ref-mismatch`).
/// - A delete of a ref that is present needs `allow_delete`.
/// - If a new commit differs from the current commit, the current commit must
///   be in the parent chain of the new commit. If the client sent `force` and
///   the rule has `allow_non_fast_forward`, this check does not apply.
///
/// `chain` is the walk made before the lock, if one was made.
async fn check_ref(
    txn: &Transaction,
    update: &RefUpdate,
    rule: &UpdateRule<'_>,
    force: bool,
    current: Option<Checksum>,
    chain: Option<usize>,
    walks: &mut Walks,
) -> Checked<bool> {
    let name = &update.name;
    let expected = match update.expected {
        Expected::Absent => current.is_none(),
        Expected::Commit(commit) => current == Some(commit),
        Expected::Any => true,
    };
    if !expected {
        let state = match current {
            Some(commit) => format!("at {commit}"),
            None => "absent".into(),
        };
        return Err(Failure::Wire(remote::Error::RefMismatch {
            message: format!("ref '{name}' is {state}"),
            name: name.clone(),
            current,
        }));
    }
    if let (Some(commit), Some(_)) = (current, update.new)
        && rule.create_only
    {
        return Err(Failure::Wire(remote::Error::RefMismatch {
            message: format!(
                "ref '{name}' is at {commit}, and the policy lets an update create the ref \
                 and not write to it"
            ),
            name: name.clone(),
            current,
        }));
    }
    match (current, update.new) {
        (None, None) => Ok(false),
        (Some(_), None) if !rule.allow_delete => Err(Failure::Wire(remote::Error::DeleteDenied(
            format!("the policy does not allow a delete of ref '{name}'"),
        ))),
        (Some(_), None) | (None, Some(_)) => Ok(true),
        (Some(current), Some(new)) if current == new => Ok(false),
        // A forced update that the rule allows needs no walk.
        (Some(_), Some(_)) if force && rule.allow_non_fast_forward => Ok(true),
        (Some(current), Some(new)) => {
            let chain = match chain {
                Some(chain) => chain,
                None => walks.chain(txn, new, current).await?,
            };
            if !walks.reaches(txn, chain, current).await? {
                return Err(Failure::Wire(remote::Error::NonFastForward(format!(
                    "commit {new} does not descend from {current}, the commit of ref '{name}'"
                ))));
            }
            Ok(true)
        }
    }
}

/// Drops `ostrya.related` from each incoming detached metadata dict if
/// `[ex-ostrya] keep-detached-related` of `repo` is `false`.
///
/// The result leaves out a dict that holds `ostrya.related` alone under that
/// rule, and the zero-length marker. Under `false`, the call parses the dicts
/// on the blocking pool. Under `true`, the call parses nothing, and the result
/// holds each other dict as it came in.
async fn filter_detached(
    repo: &Repo,
    mut commit_meta: HashMap<Checksum, Bytes>,
) -> Checked<HashMap<Checksum, Bytes>> {
    let rule = RelatedRule::of(repo.config()).map_err(Failure::Internal)?;
    if !rule.drop_related {
        commit_meta.retain(|_, bytes| !bytes.is_empty());
        return Ok(commit_meta);
    }
    ostrya_rt::unblock(move || -> Result<_> {
        let mut incoming = HashMap::with_capacity(commit_meta.len());
        for (commit, bytes) in commit_meta {
            let bytes = Arc::unwrap_or_clone(bytes);
            if let Some(bytes) = rule.apply(&commit, bytes)?
                && !bytes.is_empty()
            {
                incoming.insert(commit, Arc::new(bytes));
            }
        }
        Ok(incoming)
    })
    .await
    .map_err(Failure::Internal)
}

/// Returns the detached-metadata edits of the session.
///
/// A new commit gets an edit if it has a server key or a filtered incoming
/// dict. Each other commit with a filtered incoming dict, a staged attachment
/// included, also gets an edit, with no server key. Each commit gets one edit
/// at most. Each edit takes its stored dict out of `stored`.
fn plan<'a>(
    rules: &[UpdateRule<'a>],
    targets: &'a [Target],
    stored: &mut HashMap<Checksum, Option<Bytes>>,
    mut incoming: HashMap<Checksum, Bytes>,
) -> Vec<Edit<'a>> {
    let mut edit = |commit: Checksum, payload, incoming, signers| Edit {
        commit,
        payload,
        stored: stored.remove(&commit).flatten(),
        incoming,
        keep: Arc::default(),
        signers,
        signatures: Vec::new(),
        oversize: None,
    };
    let mut edits = Vec::new();
    for target in targets {
        let signers = target_signers(rules, &target.updates);
        let dict = incoming.remove(&target.checksum);
        if dict.is_some() || !signers.is_empty() {
            edits.push(edit(target.checksum, (&target.bytes).into(), dict, signers));
        }
    }
    for (commit, dict) in incoming {
        edits.push(edit(commit, Payload::Borrowed(&[]), Some(dict), Vec::new()));
    }
    edits
}

/// Returns the keys of [`SIGNATURE_KEYS`] among `keys`, as the flags of
/// [`check_stored`].
fn flagged<'k>(keys: impl IntoIterator<Item = &'k str>) -> [bool; SIGNATURE_KEYS.len()] {
    let mut flags = [false; SIGNATURE_KEYS.len()];
    for key in keys {
        if let Some(i) = SIGNATURE_KEYS.iter().position(|k| *k == key) {
            flags[i] = true;
        }
    }
    flags
}

/// Checks on the blocking pool that an edit accepts `stored`, with signatures
/// appended under `keys`.
///
/// If `build` is `true`, this function also returns the merge of `incoming`
/// into `stored`, with the stored value kept under each key of `keep`. If the
/// edit refuses a stored dict, the failure is on the server side.
async fn check_edit(
    stored: Option<Bytes>,
    incoming: Option<Bytes>,
    keys: [bool; SIGNATURE_KEYS.len()],
    build: bool,
    keep: Arc<Vec<String>>,
) -> Checked<Option<Value>> {
    // With no dict on either side, the edit accepts the absent stored dict
    // and builds the empty dict, so no trip to the blocking pool is needed.
    if stored.is_none() && incoming.is_none() {
        return Ok(build.then(empty_dict));
    }
    ostrya_rt::unblock(move || -> Result<Option<Value>> {
        let incoming = incoming.as_deref().map(Vec::as_slice);
        let stored = stored.as_deref().map(Vec::as_slice);
        if let Some(stored) = stored {
            let mut touched = match incoming {
                Some(incoming) => signature_keys_in(incoming)?,
                None => [false; SIGNATURE_KEYS.len()],
            };
            for (touched, key) in touched.iter_mut().zip(keys) {
                *touched |= key;
            }
            check_stored(stored, touched)?;
        }
        if !build {
            return Ok(None);
        }
        Ok(Some(
            merged_dict(stored, incoming, &keep)?.unwrap_or_else(empty_dict),
        ))
    })
    .await
    .map_err(Failure::Internal)
}

/// Returns the size of the dict that an edit writes, if the size is over
/// `limit` bytes.
///
/// The dict is the merge of `incoming` into `stored`, each a serialized dict.
/// The stored value stays under each key of `keep`, and `signatures` are
/// appended. If `written` is given, it is that dict, already built.
///
/// # Bound
///
/// A bound from the sizes of the inputs skips the serialization if the bound
/// shows that the dict fits. Each entry and each blob of the written dict
/// comes from the stored dict, from the incoming dict, or from a new
/// signature.
///
/// Relative to its place in its source, an entry gains at most 7 bytes of
/// padding and 7 bytes of framing offset. A blob gains at most 7 bytes of
/// framing offset. Each such element holds at least one byte of framing
/// offset in its source. As a result, the copied elements come to at most 15
/// times the source bytes.
///
/// A new signature adds its bytes and at most 8 bytes of offset. A signature
/// list that no source holds adds its key, its type, and their padding and
/// offsets. That is at most 64 bytes for each of the four keys.
///
/// The bound uses 16 times the source bytes, more than these 15 times. If the
/// bound is more than `limit`, this function builds and serializes the dict,
/// so the check is exact.
fn size_over(
    limit: u64,
    stored: Option<&[u8]>,
    incoming: Option<&[u8]>,
    signatures: &[(&str, &[u8])],
    written: Option<Value>,
    keep: &[String],
) -> Result<Option<u64>> {
    let sources = (stored.map_or(0, <[u8]>::len) + incoming.map_or(0, <[u8]>::len)) as u64;
    let bound = 16 * sources
        + signatures
            .iter()
            .map(|(_, signature)| signature.len() as u64 + 8)
            .sum::<u64>()
        + 64 * SIGNATURE_KEYS.len() as u64;
    if bound <= limit {
        return Ok(None);
    }
    let dict = match written {
        Some(dict) => dict,
        None => {
            let mut dict = merged_dict(stored, incoming, keep)?.unwrap_or_else(empty_dict);
            for (key, signature) in signatures {
                append_signature(&mut dict, key, signature.to_vec())?;
            }
            dict
        }
    };
    let size = serialize_signature_dict(&dict)?.len() as u64;
    Ok((size > limit).then_some(size))
}

/// Calls [`size_over`] for `edit` on the blocking pool.
///
/// The call uses `MAX_METADATA_SIZE`, the kept signatures, and the keys of the
/// edit that keep a stored value.
async fn oversize(edit: &Edit<'_>, written: Option<Value>) -> Checked<Option<u64>> {
    let stored = edit.stored.clone();
    let incoming = edit.incoming.clone();
    let keep = edit.keep.clone();
    let signatures: Vec<(String, Vec<u8>)> = edit
        .signatures
        .iter()
        .map(|p| {
            (
                p.signer.signer().metadata_key().to_owned(),
                p.signature.clone(),
            )
        })
        .collect();
    ostrya_rt::unblock(move || {
        let signatures: Vec<(&str, &[u8])> = signatures
            .iter()
            .map(|(key, signature)| (key.as_str(), signature.as_slice()))
            .collect();
        size_over(
            MAX_METADATA_SIZE,
            stored.as_deref().map(Vec::as_slice),
            incoming.as_deref().map(Vec::as_slice),
            &signatures,
            written,
            &keep,
        )
    })
    .await
    .map_err(Failure::Internal)
}

/// Returns the `limit-exceeded` failure of a merged dict of `size` bytes for
/// `commit`.
fn oversize_failure(commit: &Checksum, size: u64) -> Failure {
    Failure::Wire(remote::Error::LimitExceeded(format!(
        "the merged detached metadata of commit {commit} is {size} bytes, larger than \
         {MAX_METADATA_SIZE} bytes"
    )))
}

/// Signs the commit of each edit with each server key of the edit, before the
/// update lock.
///
/// A key makes no signature if it already signed the commit. The signature
/// can be in the merge of the filtered incoming dict into the stored dict.
/// It can also be a signature that a key before it made. As a result, two
/// keys that hold one secret sign once.
///
/// If `size` is `true`, this function then finds the size of the dict that
/// each edit writes. A session with hooks finds the size after the merge of
/// the host entries.
async fn prepare_signatures(mut edits: Vec<Edit<'_>>, size: bool) -> Checked<Vec<Edit<'_>>> {
    for edit in &mut edits {
        let signers = std::mem::take(&mut edit.signers);
        let keys = flagged(signers.iter().map(|s| s.signer().metadata_key()));
        let mut written = check_edit(
            edit.stored.clone(),
            edit.incoming.clone(),
            keys,
            !signers.is_empty(),
            edit.keep.clone(),
        )
        .await?;
        if let Some(dict) = written.as_mut() {
            for signer in signers {
                if signer.has_signed_payload(edit.payload, Some(dict)).await {
                    continue;
                }
                let key = signer.signer().metadata_key();
                let signature = signer
                    .signer()
                    .sign(edit.payload.bytes())
                    .await
                    .map_err(|e| Failure::Internal(e.into()))?;
                append_signature(dict, key, signature.clone())
                    .map_err(|e| Failure::Internal(e.into()))?;
                edit.signatures.push(Prepared {
                    signer: signer.as_ref(),
                    signature,
                });
            }
        }
        if size {
            edit.oversize = oversize(edit, written).await?;
        }
    }
    Ok(edits)
}

/// Returns the failure for a refusal of the plan of the host, a failure on
/// the server side.
///
/// This function cuts the message to the length of a hook refusal message, at
/// a character boundary.
fn invalid_plan(mut message: String) -> Failure {
    hooks::cut(&mut message);
    Failure::Internal(Error::InvalidInput(message))
}

/// Returns a key of the host in the form that a refusal quotes.
///
/// This function cuts the key to the length of a hook refusal message, at a
/// character boundary.
fn quoted(key: &str) -> String {
    let mut key = key.to_owned();
    hooks::cut(&mut key);
    key
}

/// Checks the detached-metadata entries of the host, with no encode and no
/// I/O.
///
/// The result holds the entries of each tuple with the index of its target in
/// `targets`, the new commits of the updates. The result leaves out a tuple
/// with no entry.
///
/// The checks of each tuple run in order. Its commit must be the new commit
/// of an update, and no tuple before it can name the commit. Then the checks
/// of each entry of the tuple run in order:
///
/// - Its key is not a signature key.
/// - No entry before it in the tuple has the key.
/// - Its value is a variant.
///
/// The first failure is the refusal.
fn check_plan(
    targets: &[Checksum],
    metadata: Vec<(Checksum, Vec<HostEntry>)>,
) -> Checked<Vec<(usize, Vec<HostEntry>)>> {
    let index: HashMap<Checksum, usize> = targets
        .iter()
        .enumerate()
        .map(|(i, target)| (*target, i))
        .collect();
    let mut seen = HashSet::with_capacity(metadata.len());
    let mut plan = Vec::with_capacity(metadata.len());
    for (commit, entries) in metadata {
        let Some(&target) = index.get(&commit) else {
            return Err(invalid_plan(format!(
                "the host gives detached metadata for commit {commit}, which no ref update \
                 names as its new commit"
            )));
        };
        if !seen.insert(commit) {
            return Err(invalid_plan(format!(
                "the host gives the detached metadata of commit {commit} in two tuples"
            )));
        }
        let mut keys = HashSet::with_capacity(entries.len());
        for entry in &entries {
            let key = entry.key.as_str();
            if SIGNATURE_KEYS.contains(&key) {
                return Err(invalid_plan(format!(
                    "the host gives the signature key '{}' for commit {commit}",
                    quoted(key)
                )));
            }
            if !keys.insert(key) {
                return Err(invalid_plan(format!(
                    "the host gives the key '{}' two times for commit {commit}",
                    quoted(key)
                )));
            }
            if !matches!(entry.value, Value::Variant(_)) {
                return Err(invalid_plan(format!(
                    "the host gives the key '{}' for commit {commit} a value that is not a \
                     variant",
                    quoted(key)
                )));
            }
        }
        if !entries.is_empty() {
            plan.push((target, entries));
        }
    }
    Ok(plan)
}

/// Takes the key of the one entry of `dict`, a dict built from one host
/// entry.
fn into_key(dict: Value) -> String {
    if let Value::Array(entries) = dict
        && let Some(Value::Tuple(fields)) = entries.into_iter().next()
        && let Some(Value::Str(key)) = fields.into_iter().next()
    {
        return key;
    }
    String::new()
}

/// One commit with host entries.
///
/// The tuple holds these values:
///
/// - the index of the target of the commit
/// - its incoming dict with the host entries merged in
/// - the keys whose stored value stays
type HostMerge = (usize, Vec<u8>, Arc<Vec<String>>);

/// Adds the host entries of the plan to `edits` and finds the size of each
/// dict.
///
/// One trip to the blocking pool runs the checks of [`check_plan`] over the
/// whole plan. The same trip then drops each dict of `leftover` whose commit
/// the plan does not name. It serializes each entry as a dict of one entry and
/// checks it as an `a{sv}` in normal form. It refuses an entry that does not
/// encode.
///
/// Each commit with entries then gets the merge of its incoming dict with the
/// host entries. A host entry replaces each client entry of the same key. The
/// merge builds no value tree.
///
/// A commit that has an edit takes the merged dict as its incoming dict. A
/// commit with no edit gets a new edit with no signer. Its stored dict comes
/// from `leftover`, the dicts that the plan read and no edit took. For a
/// commit that `leftover` does not hold, this function reads the stored dict.
///
/// This function checks the stored dict of each new edit. Then it finds the
/// size of the dict of each edit, once. The plan of a session with hooks
/// leaves this step to this function. A dict with host entries over the size
/// limit is `limit-exceeded`, before the update lock.
///
/// An empty plan adds no host entry and reads no stored dict. This function
/// still finds the size of the dict of each edit.
async fn add_host_entries<'a>(
    repo: &Repo,
    targets: &'a [Target],
    mut edits: Vec<Edit<'a>>,
    leftover: HashMap<Checksum, Option<Bytes>>,
    metadata: Vec<(Checksum, Vec<HostEntry>)>,
) -> Checked<Vec<Edit<'a>>> {
    let commits: Vec<Checksum> = targets.iter().map(|target| target.checksum).collect();
    let at: HashMap<Checksum, usize> = edits
        .iter()
        .enumerate()
        .map(|(i, edit)| (edit.commit, i))
        .collect();
    // The incoming dict of each edit that the plan gives entries. A plan the
    // checks refuse ends the commit, so each dict taken here is merged.
    let mut incoming: HashMap<Checksum, Bytes> = metadata
        .iter()
        .filter(|(_, entries)| !entries.is_empty())
        .filter_map(|(commit, _)| {
            let &i = at.get(commit)?;
            Some((*commit, edits[i].incoming.take()?))
        })
        .collect();
    let (merged, mut leftover) = ostrya_rt::unblock(move || {
        let plan = check_plan(&commits, metadata)?;
        let named: HashSet<Checksum> = plan.iter().map(|(target, _)| commits[*target]).collect();
        let mut leftover = leftover;
        leftover.retain(|commit, _| named.contains(commit));
        let ty = Type::parse("a{sv}")
            .map_err(|e| Failure::Internal(ostrya_core::Error::from(e).into()))?;
        let mut encoded = Vec::with_capacity(plan.len());
        for (target, entries) in plan {
            let commit = commits[target];
            let mut host = Vec::with_capacity(entries.len());
            let mut keep = Vec::new();
            for HostEntry {
                key,
                value,
                keep_existing,
            } in entries
            {
                let dict = Value::Array(vec![Value::Tuple(vec![Value::Str(key), value])]);
                // The serializer writes the signature of a variant as the
                // type gives it. As a result, the check of the bytes refuses
                // a type that the parser does not read.
                let bytes = match to_bytes(&ty, &dict)
                    .and_then(|bytes| validate(&ty, &bytes).map(|()| bytes))
                {
                    Ok(bytes) => bytes,
                    Err(e) => {
                        return Err(invalid_plan(format!(
                            "the host entry '{}' for commit {commit} does not encode: {e}",
                            quoted(&into_key(dict))
                        )));
                    }
                };
                if keep_existing {
                    keep.push(into_key(dict));
                }
                host.push(bytes);
            }
            encoded.push((target, host, keep));
        }
        let merged = encoded
            .into_iter()
            .map(|(target, host, keep)| {
                let incoming = incoming.remove(&commits[target]);
                let merged = replace_entries(incoming.as_deref().map(Vec::as_slice), &host)
                    .map_err(Failure::Internal)?;
                Ok((target, merged, Arc::new(keep)))
            })
            .collect::<Checked<Vec<HostMerge>>>()?;
        Ok((merged, leftover))
    })
    .await?;

    let reads: Vec<Checksum> = merged
        .iter()
        .map(|(target, ..)| targets[*target].checksum)
        .filter(|commit| !at.contains_key(commit) && !leftover.contains_key(commit))
        .collect();
    if !reads.is_empty() {
        let read = read_stored(repo, reads.clone()).await?;
        leftover.extend(reads.into_iter().zip(read));
    }
    let mut host = vec![false; edits.len()];
    let mut fresh = Vec::new();
    for (target, bytes, keep) in merged {
        let target = &targets[target];
        let incoming = Some(Arc::new(bytes));
        match at.get(&target.checksum) {
            Some(&i) => {
                edits[i].incoming = incoming;
                edits[i].keep = keep;
                host[i] = true;
            }
            None => {
                let stored = leftover.remove(&target.checksum).flatten();
                if let Some(stored) = &stored {
                    fresh.push(stored.clone());
                }
                host.push(true);
                edits.push(Edit {
                    commit: target.checksum,
                    payload: (&target.bytes).into(),
                    stored,
                    incoming,
                    keep,
                    signers: Vec::new(),
                    signatures: Vec::new(),
                    oversize: None,
                });
            }
        }
    }
    drop(leftover);
    if !fresh.is_empty() {
        ostrya_rt::unblock(move || {
            fresh
                .iter()
                .try_for_each(|stored| check_stored(stored, [false; SIGNATURE_KEYS.len()]))
        })
        .await
        .map_err(Failure::Internal)?;
    }
    for (edit, host) in edits.iter_mut().zip(host) {
        edit.oversize = match &edit.incoming {
            // If no stored dict and no signature exist, the written dict is
            // the merged dict less some blobs. It drops each blob of a
            // signature list that is byte-equal to a blob before it. As a
            // result, a merged dict that fits gives a written dict that fits.
            Some(merged)
                if host
                    && edit.stored.is_none()
                    && edit.signatures.is_empty()
                    && merged.len() as u64 <= MAX_METADATA_SIZE =>
            {
                None
            }
            _ => oversize(edit, None).await?,
        };
        if host && let Some(size) = edit.oversize {
            return Err(oversize_failure(&edit.commit, size));
        }
    }
    Ok(edits)
}

/// Queues the detached metadata of the session under the update lock.
///
/// This function reads the stored dict of each edit again, in one trip to the
/// blocking pool. If the dict holds the bytes that the plan read, the plan
/// stands. The kept signatures and the size then need no second check.
///
/// If the dict changed, this function drops some prepared signatures. It
/// drops each one whose key signed the commit in the new merge, or in a
/// signature kept before it. It then finds the size again.
///
/// Last, [`queue_edit`] queues each edit.
async fn queue_detached(repo: &Repo, txn: &Transaction, edits: Vec<Edit<'_>>) -> Checked<()> {
    let stored = read_stored(repo, edits.iter().map(|e| e.commit).collect()).await?;
    for (mut edit, stored) in edits.into_iter().zip(stored) {
        if stored != edit.stored {
            edit.stored = stored;
            let prepared = std::mem::take(&mut edit.signatures);
            let keys = flagged(prepared.iter().map(|p| p.signer.signer().metadata_key()));
            let mut written = check_edit(
                edit.stored.clone(),
                edit.incoming.clone(),
                keys,
                !prepared.is_empty(),
                edit.keep.clone(),
            )
            .await?;
            if let Some(dict) = written.as_mut() {
                for prepared in prepared {
                    if prepared
                        .signer
                        .has_signed_payload(edit.payload, Some(dict))
                        .await
                    {
                        continue;
                    }
                    let key = prepared.signer.signer().metadata_key();
                    append_signature(dict, key, prepared.signature.clone())
                        .map_err(|e| Failure::Internal(e.into()))?;
                    edit.signatures.push(prepared);
                }
            }
            edit.oversize = oversize(&edit, written).await?;
        }
        queue_edit(txn, edit)?;
    }
    Ok(())
}

/// Queues `edits`, which a plan under the update lock made, in `txn`, with
/// no second read of the stored dicts.
///
/// [`queue_edit`] queues each edit.
fn queue_edits(txn: &Transaction, edits: Vec<Edit<'_>>) -> Checked<()> {
    for edit in edits {
        queue_edit(txn, edit)?;
    }
    Ok(())
}

/// Queues one edit of the detached metadata in `txn`.
///
/// A dict over the size limit is `limit-exceeded`. Else the call queues the
/// merge of the filtered incoming dict, with the keys of the host entries
/// that keep a stored value, and then the kept signatures.
fn queue_edit(txn: &Transaction, edit: Edit<'_>) -> Checked<()> {
    if let Some(size) = edit.oversize {
        return Err(oversize_failure(&edit.commit, size));
    }
    if let Some(incoming) = edit.incoming {
        txn.merge_commit_detached(
            &edit.commit,
            Arc::unwrap_or_clone(incoming),
            Arc::unwrap_or_clone(edit.keep),
        );
    }
    for prepared in edit.signatures {
        txn.append_signature(
            &edit.commit,
            prepared.signer.signer().metadata_key(),
            prepared.signature,
        );
    }
    Ok(())
}

/// Writes each summary again and signs each one with `signers`, GPG keys
/// first.
///
/// The call reads the client groups of the config of `repo`, and writes the
/// root summary and the summary of each auth item as
/// [`regenerate_summaries`](Repo::regenerate_summaries) does, under the
/// update lock that the caller holds. Each summary gets the new signatures
/// alone. A failure of one summary leaves the summaries after it as they
/// were, and its step goes into the warning.
async fn write_summary(
    repo: &Repo,
    signers: &[Arc<SigningKey>],
) -> std::result::Result<(), ReceiveWarning> {
    let warning = |step, what: &str, e: Error| ReceiveWarning {
        step,
        message: format!("{what}: {e}"),
    };
    let access = ClientAccess::from_config(repo.config())
        .map_err(|e| warning(ReceiveStep::SummaryBuild, "the summary build", e))?;
    let is_gpg = |s: &&Arc<SigningKey>| s.signer().metadata_key() == GPG_KEY;
    let ordered: Vec<&dyn Signer> = signers
        .iter()
        .filter(is_gpg)
        .chain(signers.iter().filter(|s| !is_gpg(s)))
        .map(|s| s.signer())
        .collect();
    repo.write_summaries(Arc::new(access), &SummaryOptions::default(), &ordered)
        .await
        .map(drop)
        .map_err(|failure| match failure.step {
            SummaryStep::Build => warning(
                ReceiveStep::SummaryBuild,
                "the summary build",
                failure.error,
            ),
            SummaryStep::Sign => {
                let what = match &failure.key {
                    Some(key) => format!("the summary signature with the {key} key"),
                    None => "the summary signature".to_owned(),
                };
                warning(ReceiveStep::SummarySign, &what, failure.error)
            }
            SummaryStep::Write => warning(
                ReceiveStep::SummaryWrite,
                "the summary write",
                failure.error,
            ),
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    const KEY: &str = "ostree.sign.ed25519";

    /// A temporary directory that is removed on drop.
    struct Scratch(std::path::PathBuf);

    impl Scratch {
        fn new(tag: &str) -> Scratch {
            let dir = std::env::temp_dir().join(format!(
                "ostrya-finish-{tag}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            Scratch(dir)
        }
    }

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

    /// Returns `count` updates that expect their refs absent. The request does
    /// not state an old commit, and the reply can.
    fn absent_updates(count: usize) -> Vec<RefUpdate> {
        (0..count)
            .map(|i| RefUpdate {
                name: format!("refs-{i:015}"),
                expected: Expected::Absent,
                new: Some(Checksum::from_bytes([1; 32])),
            })
            .collect()
    }

    /// The check refuses a `Commit` that fits in a frame if its reply, with an
    /// old commit for each ref, does not fit (`limit-exceeded`). A reply that
    /// fits passes, and the check is exact at the limit.
    #[test]
    fn a_commit_whose_reply_cannot_fit_is_refused() {
        let updates = absent_updates(15_000);
        let request = Message::Commit(CommitRequest {
            updates: updates.clone(),
            force: false,
            server_commit: None,
        });
        let request_len = request.encode_body().unwrap().len() + 1;
        assert!(request_len <= MAX_FRAME as usize, "{request_len}");
        match check_reply_fits(&updates) {
            Err(Failure::Wire(remote::Error::LimitExceeded(m))) => {
                assert!(m.contains("15000 ref updates"), "{m}")
            }
            Err(Failure::Wire(e)) => panic!("expected limit-exceeded, got {e}"),
            Err(_) => panic!("expected limit-exceeded, got another failure"),
            Ok(()) => panic!("a reply over the limit passed"),
        }
        assert!(check_reply_fits(&absent_updates(100)).is_ok());

        // The longest reply of the largest count that passes fits.
        let (mut low, mut high) = (100, 15_000);
        while high - low > 1 {
            let mid = (low + high) / 2;
            if check_reply_fits(&absent_updates(mid)).is_ok() {
                low = mid;
            } else {
                high = mid;
            }
        }
        let longest = |count| {
            Message::CommitReply(
                absent_updates(count)
                    .into_iter()
                    .map(|u| RefOutcome {
                        name: u.name,
                        old: Some(Checksum::from_bytes([2; 32])),
                        new: u.new,
                    })
                    .collect(),
            )
            .encode_body()
            .unwrap()
            .len()
                + 1
        };
        assert!(longest(low) <= MAX_FRAME as usize);
        assert!(longest(high) > MAX_FRAME as usize);
    }

    fn serialized(dict: &Value) -> Vec<u8> {
        serialize_signature_dict(dict).unwrap()
    }

    /// Returns a dict with the blobs `blobs` under [`KEY`].
    fn signed(blobs: &[&[u8]]) -> Value {
        let mut dict = Value::Array(Vec::new());
        for blob in blobs {
            append_signature(&mut dict, KEY, blob.to_vec()).unwrap();
        }
        dict
    }

    /// The size check is exact at its limit. A dict of `n` bytes is over a
    /// limit of `n - 1` and not over a limit of `n`. The dict it measures is
    /// the merge with the appended signatures. A limit more than the bound of
    /// the input sizes needs no serialization.
    #[test]
    fn the_size_check_is_exact_at_the_limit() {
        let stored = serialized(&signed(&[b"one"]));
        let incoming = serialized(&signed(&[b"one", b"two"]));
        let signatures: [(&str, &[u8]); 1] = [(KEY, b"three")];
        let written = serialized(&signed(&[b"one", b"two", b"three"]));
        let n = written.len() as u64;
        let over = |limit| {
            size_over(
                limit,
                Some(&stored),
                Some(&incoming),
                &signatures,
                None,
                &[],
            )
            .unwrap()
        };
        assert_eq!(over(n - 1), Some(n));
        assert_eq!(over(n), None);
        assert_eq!(over(0), Some(n));
        assert_eq!(over(u64::MAX), None);
        // A dict built already is measured as it stands.
        assert_eq!(
            size_over(
                n - 1,
                None,
                None,
                &[],
                Some(signed(&[b"one", b"two", b"three"])),
                &[],
            )
            .unwrap(),
            Some(n)
        );
    }

    /// The size check applies the keys that keep a stored value: the dict it
    /// measures holds the stored value under each such key.
    #[test]
    fn the_size_check_keeps_the_stored_value() {
        let blob = |len| Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![7; len]));
        let dict = |len| {
            let mut dict = empty_dict();
            crate::commit::append_dict_entry(&mut dict, "k", blob(len)).unwrap();
            dict
        };
        let stored = serialized(&dict(100));
        let incoming = serialized(&dict(10));
        let keep = ["k".to_owned()];
        let over = |keep: &[String]| {
            size_over(0, Some(&stored), Some(&incoming), &[], None, keep).unwrap()
        };
        assert_eq!(over(&keep), Some(stored.len() as u64));
        assert_eq!(over(&[]), Some(incoming.len() as u64));
    }

    fn entry(key: &str, value: Value) -> HostEntry {
        HostEntry {
            key: key.into(),
            value,
            keep_existing: false,
        }
    }

    fn text(value: &str) -> Value {
        Value::variant(Type::Str, Value::Str(value.into()))
    }

    /// The checks of the plan of the host, in order, and the first failure
    /// is the refusal. A tuple with no entry is checked and left out.
    #[test]
    fn the_plan_checks_run_in_order() {
        let (a, b, c) = (
            Checksum::from_bytes([1; 32]),
            Checksum::from_bytes([2; 32]),
            Checksum::from_bytes([3; 32]),
        );
        let targets = [a, b];
        let sig = || entry("ostree.gpgsigs", text("x"));
        let bare = |key: &str| entry(key, Value::U32(1));
        let refused = |metadata: Vec<(Checksum, Vec<HostEntry>)>, needle: &str| match check_plan(
            &targets, metadata,
        ) {
            Err(Failure::Internal(Error::InvalidInput(m))) => {
                assert!(m.contains(needle), "{needle}: {m}")
            }
            Err(_) => panic!("{needle}: another failure"),
            Ok(_) => panic!("{needle}: the plan passed"),
        };

        let passed = |metadata| match check_plan(&targets, metadata) {
            Ok(plan) => plan,
            Err(_) => panic!("the plan was refused"),
        };
        let plan = passed(vec![
            (b, Vec::new()),
            (a, vec![entry("", text("empty key"))]),
        ]);
        assert_eq!(plan.len(), 1);
        assert_eq!(plan[0].0, 0);
        assert_eq!(plan[0].1, [entry("", text("empty key"))]);
        assert!(passed(Vec::new()).is_empty());

        // The checks of a tuple come before the checks of its entries.
        refused(vec![(c, vec![sig()])], "no ref update names");
        refused(vec![(c, Vec::new())], "no ref update names");
        refused(vec![(a, Vec::new()), (a, Vec::new())], "in two tuples");
        refused(vec![(a, Vec::new()), (a, vec![sig()])], "in two tuples");
        // The tuples are checked in order.
        refused(vec![(a, vec![sig()]), (c, Vec::new())], "signature key");
        refused(
            vec![(c, Vec::new()), (a, vec![sig()])],
            "no ref update names",
        );
        // The entries are checked in order, and each entry in the order of
        // its checks.
        refused(vec![(a, vec![bare("k"), sig()])], "not a variant");
        refused(vec![(a, vec![sig(), bare("k")])], "signature key");
        refused(
            vec![(a, vec![entry("k", text("x")), bare("k")])],
            "two times",
        );
        refused(vec![(a, vec![bare("ostree.sign.dummy")])], "signature key");
        for key in SIGNATURE_KEYS {
            refused(vec![(b, vec![entry(key, text("x"))])], "signature key");
        }
    }

    /// The bound of the input sizes is not less than the written size, for
    /// dicts whose framing offsets grow in the merge.
    #[test]
    fn the_size_bound_holds_when_the_offsets_grow() {
        let blobs: Vec<Vec<u8>> = (0..200u32).map(|i| i.to_le_bytes().to_vec()).collect();
        let half = blobs.len() / 2;
        let refs: Vec<&[u8]> = blobs.iter().map(Vec::as_slice).collect();
        let stored = serialized(&signed(&refs[..half]));
        let incoming = serialized(&signed(&refs[half..]));
        let signature = vec![7u8; 300];
        let signatures: [(&str, &[u8]); 1] = [(KEY, &signature)];
        let mut all = refs.clone();
        all.push(&signature);
        let written = serialized(&signed(&all)).len() as u64;
        let bound = 16 * (stored.len() + incoming.len()) as u64
            + signature.len() as u64
            + 8
            + 64 * SIGNATURE_KEYS.len() as u64;
        assert!(bound >= written, "bound {bound} < written {written}");
        assert_eq!(
            size_over(
                written - 1,
                Some(&stored),
                Some(&incoming),
                &signatures,
                None,
                &[],
            )
            .unwrap(),
            Some(written)
        );
    }

    /// The signature of a server commit gives the commit bytes to the
    /// verifier of each key with no copy. The second key reads the signature
    /// of the first key, so its verifier runs.
    #[test]
    fn the_server_commit_search_gets_the_bytes_with_no_copy() {
        use crate::sign::DummySigner;
        use crate::verify::trust::tests::ThreadRecorder;

        let scratch = Scratch::new("server-commit");
        let recorder = ThreadRecorder::new("ostree.sign.dummy");
        let server = || {
            Arc::new(
                SigningKey::new(
                    Box::new(DummySigner::new(b"k".to_vec())),
                    Box::new(recorder.clone()),
                )
                .unwrap(),
            )
        };
        let signers = [server(), server()];
        let payload = Arc::new(b"commit".to_vec());
        ostrya_rt::block_on(async {
            let repo = Repo::create(
                &scratch.0.join("repo"),
                crate::CreateOptions::new(crate::RepoMode::Archive),
            )
            .await
            .unwrap();
            let txn = repo.transaction().await.unwrap();
            let commit = Checksum::from_bytes([1; 32]);
            assert!(
                sign_server_commit(&repo, &txn, commit, &payload, &signers)
                    .await
                    .is_ok()
            );
            txn.abort().await.unwrap();
        });
        drop(scratch);
        recorder.assert_one_foreign_call();
        recorder.assert_no_copy_of(&payload);
    }
}