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
//! Checks of the integrity and the completeness of a repository.
//!
//! [`Repo::fsck`] runs the checks. [`FsckOptions`] selects the optional checks
//! and the actions on the findings. [`FsckReport`] holds the result.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;

use futures_lite::AsyncReadExt;
use ostrya_core::{
    Checksum, Commit, ContentHasher, DirMetaRef, DirTree, DirTreeRef, ObjectName, ObjectType,
};

use crate::error::{Error, Result};
use crate::refs::CollectionRefEntry;
use crate::related::{self, RelatedEntry, RelationField, RelationWarning};
use crate::repo::Repo;
use crate::tombstone::write_tombstone;
use crate::write::COPY_CHUNK;

/// The one byte that the `ostree` command writes into a `.commitpartial`
/// marker when its fsck finds a commit incomplete (observed).
const PARTIAL_STATE_BYTE: u8 = 0x66;

/// The options of a [`Repo::fsck`] run.
#[derive(Debug, Clone)]
pub struct FsckOptions {
    /// The switch that marks each commit that reaches an absent or a deleted
    /// object as partial.
    ///
    /// The mark is the `state/<commit>.commitpartial` marker of the commit, as
    /// the `ostree` command writes it. The default is `true`. The value `false`
    /// is an ostrya extension, which the `ostrya fsck` command spells
    /// `--no-mark-partial`.
    ///
    /// The run creates the marker with `O_EXCL` and writes the one byte `f`
    /// into it. An entry that is present at the name of the marker, of any
    /// type, stays as it is, and the run writes nothing into it. The run
    /// makes `state/` if it is absent. If `[core] fsync` is `true`, the run
    /// syncs `state/` after the create of each marker. It does not sync the
    /// content of a marker.
    ///
    /// If [`mark_attachments`](FsckOptions::mark_attachments) is also
    /// `true`, the switch marks each commit that has an
    /// [`Absent`](FsckAttachmentErrorKind::Absent) or a
    /// [`Partial`](FsckAttachmentErrorKind::Partial) attachment. An
    /// attachment is partial if an attachment below it is absent or partial,
    /// so the marks reach each commit above a broken attachment. A later pull
    /// of the top commit then fetches the full set of its attachments. A
    /// [`Defective`](FsckAttachmentErrorKind::Defective) entry marks no
    /// commit, because a pull cannot repair it.
    pub mark_partial: bool,
    /// The switch that marks each commit that has an
    /// [`Absent`](FsckAttachmentErrorKind::Absent) or a
    /// [`Partial`](FsckAttachmentErrorKind::Partial) attachment as partial.
    ///
    /// The switch has an effect only if
    /// [`mark_partial`](FsckOptions::mark_partial) is `true`. The default is
    /// `true`. The value `false` is an ostrya extension, which the
    /// `ostrya fsck` command spells `--no-mark-attachments`.
    ///
    /// With the value `true`, the marks reach each commit above a broken
    /// attachment, at each depth.
    ///
    /// With the value `false`, the run reports each finding in
    /// [`FsckReport::attachment_errors`] and marks no commit for an
    /// attachment. The marks for absent and deleted objects do not change.
    /// A later run verifies again each commit that the run did not mark, and
    /// gives the same finding.
    pub mark_attachments: bool,
    /// The switch that unlinks each object whose checksum differs from its name.
    ///
    /// The option of the `ostree fsck` command is `--delete`.
    ///
    /// The run also marks each commit that reaches a deleted object as
    /// partial. The run writes these markers first, and unlinks the objects
    /// after them. If the bytes of a metadata object do not parse as the type
    /// of its name, the run reports the object and does not unlink it. Such
    /// an object marks no commit as partial.
    ///
    /// The unlink follows no symlink at `objects/<xx>`. If `[core] fsync` is
    /// `true`, the run syncs the `objects/<xx>` directory after the unlink of
    /// each object.
    ///
    /// If this field is `false`, a checksum mismatch marks no commit, as with
    /// the `ostree` command. A commit stays complete while the wrong object is
    /// present.
    pub delete: bool,
    /// The switch that lets the tombstone step run after a walk with a corrupt
    /// object.
    ///
    /// The option of the `ostree fsck` command is `-a`.
    ///
    /// The object walk runs to its end with each value of this field. The
    /// field has one effect: it lets the
    /// [`add_tombstones`](FsckOptions::add_tombstones) step act after a walk
    /// that found an object whose bytes do not match its name.
    /// [`delete`](FsckOptions::delete) gives the same permission. A walk that
    /// found only absent objects needs neither field.
    pub all: bool,
    /// The switch that deletes each commit whose parent commit is absent.
    ///
    /// The option of the `ostree fsck` command is `--add-tombstones`.
    ///
    /// The step writes a `.tombstone-commit` object that names each deleted
    /// commit. [`Repo::fsck`] states when the step runs.
    ///
    /// The unlink of a commit follows no symlink at `objects/<xx>`. If
    /// `[core] fsync` is `true`, the step syncs the `objects/<xx>` directory
    /// after the unlink of each commit.
    pub add_tombstones: bool,
    /// The switch that checks that the commit of each ref is bound to the ref.
    ///
    /// The option of the `ostree fsck` command is `--verify-bindings`.
    ///
    /// The `ostree.ref-binding` of the commit of each ref must hold the name
    /// of the ref. A commit with no `ostree.ref-binding` key passes this
    /// check, as with the `ostree` command.
    ///
    /// The `ostree.collection-binding` of the commit of each collection ref
    /// must be the collection id of the ref. A commit with no
    /// `ostree.collection-binding` key passes this check.
    pub verify_bindings: bool,
    /// The switch that checks that the ref bindings of each commit resolve to it.
    ///
    /// The option of the `ostree fsck` command is `--verify-back-refs`.
    ///
    /// The check reads each commit object in the object store. Each name in
    /// the `ostree.ref-binding` of a commit must name a ref that resolves to
    /// the commit. A ref under `refs/remotes` counts by its bare name. If the
    /// commit has an `ostree.collection-binding`, the collection ref with that
    /// id and that name must also resolve to the commit.
    ///
    /// This check and [`verify_bindings`](FsckOptions::verify_bindings) are
    /// independent. Each field runs its own check only.
    pub verify_back_refs: bool,
}

impl Default for FsckOptions {
    fn default() -> Self {
        FsckOptions {
            mark_partial: true,
            mark_attachments: true,
            delete: false,
            all: false,
            add_tombstones: false,
            verify_bindings: false,
            verify_back_refs: false,
        }
    }
}

impl FsckOptions {
    /// Creates the default options.
    ///
    /// [`mark_partial`](FsckOptions::mark_partial) and
    /// [`mark_attachments`](FsckOptions::mark_attachments) are `true`, and
    /// each other field is `false`.
    pub fn new() -> FsckOptions {
        FsckOptions::default()
    }
}

/// The phases of a [`Repo::fsck`] run, in order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FsckPhase {
    /// The phase that loads the commit of each ref and verifies its checksum.
    ValidateRefs,
    /// The phase that reads the collection-qualified refs.
    ValidateCollectionRefs,
    /// The phase that lists the commit objects and separates the partial ones.
    EnumerateCommits,
    /// The phase that walks and verifies the objects of the verified commits.
    VerifyObjects,
}

/// The cause of a finding on one object.
#[derive(Debug, Clone)]
pub enum FsckErrorKind {
    /// The object is referenced and absent from the object store.
    Missing,
    /// The object is present, and its checksum differs from its name.
    ChecksumMismatch {
        /// The checksum of the bytes of the object.
        actual: Checksum,
    },
    /// The object is present, and a read or a parse of it failed.
    Corrupt(String),
}

/// One finding of a run: the object, the cause, and the commits that reach it.
#[derive(Debug, Clone)]
pub struct FsckError {
    /// The object of the finding.
    pub object: ObjectName,
    /// The cause of the finding.
    pub kind: FsckErrorKind,
    /// The verified commits that reach the object, sorted.
    ///
    /// The list is empty for a finding of the ref phase. That phase reads the
    /// commit object that a ref names, and it reaches no commit through it.
    pub in_commits: Vec<Checksum>,
}

impl std::fmt::Display for FsckError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            FsckErrorKind::Missing => write!(f, "missing object {}", self.object),
            FsckErrorKind::ChecksumMismatch { actual } => write!(
                f,
                "corrupted object {}: checksum expected {}, computed {}",
                self.object, self.object.checksum, actual
            ),
            FsckErrorKind::Corrupt(detail) => {
                write!(f, "corrupted object {}: {detail}", self.object)
            }
        }
    }
}

/// A failed binding check or back-reference check.
///
/// A finding of this type ends the run in the phase that made it.
#[derive(Debug, Clone)]
pub struct FsckBindingError {
    /// The commit of the finding.
    pub commit: Checksum,
    /// The check that failed.
    pub kind: FsckBindingErrorKind,
}

/// The binding check that failed.
#[derive(Debug, Clone)]
pub enum FsckBindingErrorKind {
    /// The `ostree.ref-binding` of the commit does not hold the ref (ref
    /// phase).
    RefNotBound {
        /// The bare name of the ref through which the run reached the commit.
        ref_name: String,
        /// The names in the `ostree.ref-binding` of the commit, in stored
        /// order.
        bindings: Vec<String>,
    },
    /// The `ostree.collection-binding` of the commit is not the collection id
    /// of the ref.
    ///
    /// The collection phase makes this finding.
    CollectionMismatch {
        /// The id in the `ostree.collection-binding` of the commit.
        bound: String,
        /// The collection id of the ref.
        found_under: String,
    },
    /// A bound ref name that names no ref (back-reference check).
    BackRefMissing {
        /// The bound name.
        ref_name: String,
    },
    /// A bound ref name that names another commit (back-reference check).
    BackRefMismatch {
        /// The bound name.
        ref_name: String,
    },
    /// A bound collection ref that does not exist (back-reference check).
    BackCollectionRefMissing {
        /// The `ostree.collection-binding` of the commit.
        collection_id: String,
        /// The bound name.
        ref_name: String,
    },
    /// A bound collection ref that names another commit (back-reference
    /// check).
    BackCollectionRefMismatch {
        /// The `ostree.collection-binding` of the commit.
        collection_id: String,
        /// The bound name.
        ref_name: String,
    },
}

/// An attachment of a commit that is absent, partial, or defective.
///
/// [`Repo::fsck`] gives one for each such entry in field 2 of a commit that
/// it checks. The [`Display`](std::fmt::Display) output is the text of
/// [`Error::InvalidRelations`] with the same commit, field 2, and reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FsckAttachmentError {
    /// The commit whose field 2 holds the entry.
    pub commit: Checksum,
    /// The name of the entry.
    pub name: String,
    /// The commit that the entry names, or `None` if the entry holds a
    /// checksum that is not 32 bytes.
    pub attachment: Option<Checksum>,
    /// The cause of the finding.
    pub kind: FsckAttachmentErrorKind,
}

/// The cause of a finding on an attachment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FsckAttachmentErrorKind {
    /// The repository does not hold the commit object of the attachment.
    Absent,
    /// The commit of the attachment is partial: it has a `.commitpartial`
    /// marker, or its tree is not complete, or an attachment of the commit is
    /// absent or partial.
    Partial,
    /// The entry has an empty name or a checksum that is not 32 bytes. The
    /// payload is the reason.
    Defective(String),
}

impl FsckAttachmentError {
    /// Returns the reason of the finding.
    pub(crate) fn reason(&self) -> String {
        let end = match &self.kind {
            FsckAttachmentErrorKind::Absent => related::ABSENT_REASON,
            FsckAttachmentErrorKind::Partial => related::PARTIAL_REASON,
            FsckAttachmentErrorKind::Defective(reason) => return reason.clone(),
        };
        match &self.attachment {
            Some(attachment) => related::attachment_reason(&self.name, attachment, end),
            None => format!("attachment {}, {end}", self.name),
        }
    }
}

impl std::fmt::Display for FsckAttachmentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        RelationWarning {
            commit: self.commit,
            field: RelationField::Attachments,
            reason: self.reason(),
        }
        .fmt(f)
    }
}

/// Returns the findings on the field 2 of each commit of `attachments`.
///
/// `attachments` holds each commit whose field 2 is not empty, with the
/// entries of its field 2, sorted by commit. `checked` tells if a commit gets
/// a check. `absent` and `partial` tell the state of an attachment.
///
/// The first rule that applies gives the finding of an entry: a defect of
/// the entry, an absent attachment, or a partial attachment. An entry with
/// no such finding gets a `Partial` finding if its attachment is in
/// `attachments` and has an `Absent` or a `Partial` finding of its own. The
/// function applies this rule again until no finding changes. A `Defective`
/// finding does not make the commit above it partial.
///
/// The findings are sorted by the naming commit, then by the stored order of
/// its field 2.
pub(crate) fn attachment_findings(
    attachments: &[(Checksum, Vec<RelatedEntry>)],
    checked: impl Fn(&Checksum) -> bool,
    absent: impl Fn(&Checksum) -> bool,
    partial: impl Fn(&Checksum) -> bool,
) -> Vec<FsckAttachmentError> {
    let finding = |commit: usize, index: usize, kind| {
        let (naming, entries) = &attachments[commit];
        let entry = &entries[index];
        (
            (commit, index),
            FsckAttachmentError {
                commit: *naming,
                name: entry.name.clone(),
                attachment: entry.checksum.ok(),
                kind,
            },
        )
    };
    let mut findings = Vec::new();
    // `broken` holds each commit with an `Absent` or a `Partial` finding.
    // `queue` holds each such commit whose naming entries are not checked
    // yet.
    let mut broken = vec![false; attachments.len()];
    let mut queue = Vec::new();
    // Each edge `(attachment, commit, index)` is an entry with no finding
    // whose attachment is in `attachments`.
    let mut edges = Vec::new();
    for (commit, (naming, entries)) in attachments.iter().enumerate() {
        if !checked(naming) {
            continue;
        }
        for (index, entry) in entries.iter().enumerate() {
            let kind = match (entry.defect(index), entry.checksum) {
                (Some(reason), _) => FsckAttachmentErrorKind::Defective(reason),
                (None, Ok(attachment)) if absent(&attachment) => FsckAttachmentErrorKind::Absent,
                (None, Ok(attachment)) if partial(&attachment) => FsckAttachmentErrorKind::Partial,
                (None, Ok(attachment)) => {
                    if let Ok(below) =
                        attachments.binary_search_by_key(&attachment, |(naming, _)| *naming)
                    {
                        edges.push((below, commit, index));
                    }
                    continue;
                }
                (None, Err(_)) => continue,
            };
            if !matches!(kind, FsckAttachmentErrorKind::Defective(_)) && !broken[commit] {
                broken[commit] = true;
                queue.push(commit);
            }
            findings.push(finding(commit, index, kind));
        }
    }
    edges.sort_unstable();
    while let Some(below) = queue.pop() {
        let start = edges.partition_point(|&(attachment, _, _)| attachment < below);
        for &(_, commit, index) in edges[start..]
            .iter()
            .take_while(|&&(attachment, _, _)| attachment == below)
        {
            findings.push(finding(commit, index, FsckAttachmentErrorKind::Partial));
            if !broken[commit] {
                broken[commit] = true;
                queue.push(commit);
            }
        }
    }
    findings.sort_unstable_by_key(|(position, _)| *position);
    findings.into_iter().map(|(_, finding)| finding).collect()
}

/// The condition that ended a run before the end of its last phase.
#[derive(Debug, Clone)]
pub enum FsckFailure {
    /// A ref names a commit object that the object store does not hold.
    RefTarget {
        /// The name of the ref, as a message gives it.
        ///
        /// A remote ref has its bare name, with no remote prefix, as in the
        /// message of the `ostree` command. A mirror ref has the form
        /// `(collection, name)`.
        ref_name: String,
        /// The commit that the ref names.
        commit: Checksum,
        /// `true` if the run removed the object itself.
        ///
        /// [`delete`](FsckOptions::delete) removes a ref target whose checksum
        /// does not match.
        removed: bool,
    },
    /// An absent dirtree that the walk must read.
    ///
    /// The run cannot read the subtree of this dirtree.
    MissingDirTree(Checksum),
    /// A failed binding check or back-reference check.
    Binding(FsckBindingError),
}

/// The result of a [`Repo::fsck`] run.
///
/// A corrupt repository does not fail the call. The report holds each faulty
/// object in [`errors`](FsckReport::errors), and the condition that ended the
/// run in [`failure`](FsckReport::failure). A caller, for example the
/// `ostrya fsck` command, turns a report with findings into a failure.
#[derive(Debug, Clone)]
pub struct FsckReport {
    /// The last phase that the run entered.
    pub reached: FsckPhase,
    /// The number of commit objects that the run verified.
    ///
    /// These are the commits in the object store that had no `.commitpartial`
    /// marker at the start of the run.
    pub commits_checked: usize,
    /// The number of commit objects that the run skipped as already partial.
    pub commits_partial: usize,
    /// The number of distinct objects that the verified commits reference.
    ///
    /// The count includes the present objects and the absent objects. It does
    /// not include detached commit metadata. If the run ended early, the count
    /// is `0`.
    pub objects_checked: usize,
    /// The findings, sorted by object checksum.
    ///
    /// A commit object that a ref names can have two findings: one from the
    /// ref phase and one from the object walk.
    pub errors: Vec<FsckError>,
    /// The commits that the run marked as partial, sorted.
    pub marked_partial: Vec<Checksum>,
    /// The objects that the run unlinked for [`delete`](FsckOptions::delete),
    /// sorted.
    pub deleted: Vec<ObjectName>,
    /// The commits that the run deleted for
    /// [`add_tombstones`](FsckOptions::add_tombstones), sorted.
    pub tombstoned: Vec<Checksum>,
    /// The condition that ended the run early, if one did.
    pub failure: Option<FsckFailure>,
    /// The attachments that are absent, partial, or defective, sorted by
    /// the commit that names them, then in the stored order of its field 2.
    ///
    /// An attachment with an `Absent` or a `Partial` finding of its own makes
    /// each entry that names it [`Partial`](FsckAttachmentErrorKind::Partial).
    /// Each such finding names the attachment one level below, and the
    /// finding on that attachment names the next level. The first rule that
    /// applies gives the finding of an entry, so an entry with an empty name
    /// gives [`Defective`](FsckAttachmentErrorKind::Defective).
    ///
    /// [`Repo::fsck`] states the check under "Attachments".
    pub attachment_errors: Vec<FsckAttachmentError>,
    /// The refs under `refs/mirrors/ID/` of the `[core] collection-id` of the
    /// repository, by their names below that directory, sorted.
    ///
    /// The ref resolve, the collection ref listings, and the summary ignore
    /// these refs. Such a ref is not an error. [`Repo::fsck`] states the rule under "Refs of the own
    /// collection id".
    pub own_mirror_refs: Vec<String>,
}

impl FsckReport {
    /// Returns `true` if the repository passed with no finding.
    ///
    /// A pass has no faulty object, no faulty attachment, no condition that
    /// ended the run, and no commit that the run skipped as already partial.
    /// A ref of [`own_mirror_refs`](FsckReport::own_mirror_refs) does not stop
    /// a pass.
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
            && self.attachment_errors.is_empty()
            && self.failure.is_none()
            && self.commits_partial == 0
    }
}

/// The mutable state of one fsck run.
#[derive(Default)]
struct Ctx {
    /// The findings, in the order of the run.
    errors: Vec<FsckError>,
    /// The objects of findings whose bytes do not parse as the type of their
    /// name. The run reports each one and acts on none.
    unparsable: HashSet<ObjectName>,
    /// The commits that this run marked as partial.
    marked_partial: HashSet<Checksum>,
    /// The objects that this run unlinked.
    deleted: HashSet<ObjectName>,
    /// The commits that this run tombstoned.
    tombstoned: HashSet<Checksum>,
    /// The number of leading entries of `errors` that the ref phase made.
    /// These keep an empty `in_commits`, because the ref phase reaches no
    /// commit through the object that it read.
    ref_findings: usize,
    /// The commit objects that the run verifies, sorted.
    verified: Vec<Checksum>,
    /// The number of commit objects skipped as already partial.
    commits_partial: usize,
    /// The commits that reach an absent or a deleted object, also when the
    /// run marks no commit.
    incomplete: HashSet<Checksum>,
    /// The findings of the attachment check, in the order of the run.
    attachment_errors: Vec<FsckAttachmentError>,
    /// The names of the refs under `refs/mirrors/ID/` of the own collection
    /// id, sorted.
    own_mirror_refs: Vec<String>,
}

impl Ctx {
    /// Records one finding. The run names the commits that reach the object
    /// after the walk, so the finding starts with no commit.
    fn record(&mut self, object: ObjectName, kind: FsckErrorKind) {
        self.errors.push(FsckError {
            object,
            kind,
            in_commits: Vec::new(),
        });
    }

    /// Builds the report.
    fn finish(
        mut self,
        reached: FsckPhase,
        objects_checked: usize,
        failure: Option<FsckFailure>,
    ) -> FsckReport {
        self.errors.sort_by_key(|e| {
            (
                e.object.checksum,
                e.object.ty as u32,
                e.in_commits.is_empty(),
            )
        });
        let mut marked_partial: Vec<Checksum> = self.marked_partial.into_iter().collect();
        marked_partial.sort();
        let mut deleted: Vec<ObjectName> = self.deleted.into_iter().collect();
        deleted.sort_by_key(|name| (name.checksum, name.ty as u32));
        let mut tombstoned: Vec<Checksum> = self.tombstoned.into_iter().collect();
        tombstoned.sort();
        FsckReport {
            reached,
            commits_checked: self.verified.len(),
            commits_partial: self.commits_partial,
            objects_checked,
            errors: self.errors,
            marked_partial,
            deleted,
            tombstoned,
            failure,
            attachment_errors: self.attachment_errors,
            own_mirror_refs: self.own_mirror_refs,
        }
    }
}

/// Methods that check the objects and the refs of a repository.
impl Repo {
    /// Checks the integrity and the completeness of the commits in a repository.
    ///
    /// The run has the four phases of the `ostree fsck` command, in the same
    /// order. A corrupt repository does not fail the call: the [`FsckReport`]
    /// holds the findings. [`FsckOptions`] selects the optional checks.
    ///
    /// # Phases
    ///
    /// 1. Validate refs ([`FsckPhase::ValidateRefs`]). The run loads the
    ///    commit object that each ref under `refs/heads` and `refs/remotes`
    ///    names, and verifies its checksum. If
    ///    [`verify_bindings`](FsckOptions::verify_bindings) is set, the
    ///    `ostree.ref-binding` of the commit must hold the name of the ref.
    /// 2. Validate refs in collections
    ///    ([`FsckPhase::ValidateCollectionRefs`]). The run loads the commit of
    ///    each mirror ref and verifies its checksum. If `verify_bindings` is
    ///    set, the `ostree.collection-binding` of the commit of each
    ///    collection-qualified ref must be the collection id of the ref. The
    ///    mirror refs include the refs under `refs/mirrors/ID/` of the
    ///    `[core] collection-id` of the repository.
    /// 3. Enumerate commits ([`FsckPhase::EnumerateCommits`]). The run lists
    ///    each commit object in the object store. It skips each commit that
    ///    has a `state/<commit>.commitpartial` marker at the start of the run.
    ///    If [`verify_back_refs`](FsckOptions::verify_back_refs) is set, each
    ///    name in the `ostree.ref-binding` of a commit must name a ref that
    ///    resolves to that commit. A ref under `refs/mirrors/ID/` of the
    ///    `[core] collection-id` of the repository resolves no name.
    /// 4. Verify objects ([`FsckPhase::VerifyObjects`]). The run reads each
    ///    object that the verified commits reference, once:
    ///
    ///    - Integrity: the checksum of each object must equal its name. The
    ///      hash of a metadata object covers its serialized bytes. The hash of
    ///      a content object covers its framed uncompressed header and its
    ///      uncompressed payload. Because of this, the run finds a corrupt
    ///      `.filez` or a changed `.file` in each repository mode.
    ///    - Completeness: each referenced object must be present. The run
    ///      reports each absent object. It marks each commit that reaches the
    ///      object as partial: it writes the `state/<commit>.commitpartial`
    ///      marker of the commit.
    ///
    /// [`mark_partial`](FsckOptions::mark_partial),
    /// [`mark_attachments`](FsckOptions::mark_attachments), and
    /// [`delete`](FsckOptions::delete) state the actions on a finding.
    ///
    /// # Refs of the own collection id
    ///
    /// The refs of the `[core] collection-id` of the repository are the
    /// local refs, under `refs/heads`. The port writes no ref under
    /// `refs/mirrors/ID/` of that id, and the ref resolve, the collection ref
    /// listings, and the summary ignore that directory. Such a ref comes from outside the port, for
    /// example from a hand edit or from the `ostree` command.
    /// [`FsckReport::own_mirror_refs`] holds the name of each such ref. The
    /// list is not an error, and the run repairs nothing for it. Remove such
    /// a ref by hand.
    ///
    /// A prune keeps the commit of such a ref, so phase 2 checks it: a
    /// commit object that the store does not hold ends the run with
    /// [`FsckFailure::RefTarget`], and a binding mismatch under
    /// `verify_bindings` ends the run with [`FsckFailure::Binding`].
    ///
    /// # Attachments
    ///
    /// After the four phases and the actions on their findings, the run
    /// checks field 2 of each verified commit that it did not delete. It
    /// reads field 2 from the read of phase 4, so it reads no object again.
    /// [`FsckReport::attachment_errors`] holds one [`FsckAttachmentError`]
    /// for each entry, in the stored order:
    ///
    /// - [`Defective`](FsckAttachmentErrorKind::Defective) if the entry has
    ///   an empty name or a checksum that is not 32 bytes.
    /// - [`Absent`](FsckAttachmentErrorKind::Absent) if the object store does
    ///   not hold the commit at the start of the run, or if the run deleted
    ///   it.
    /// - [`Partial`](FsckAttachmentErrorKind::Partial) if the commit has a
    ///   `.commitpartial` marker at the start of the run, or if it reaches an
    ///   absent or a deleted object. The run does not read field 2 of a
    ///   commit with a marker, and this rule gives the finding of each entry
    ///   that names it.
    /// - [`Partial`](FsckAttachmentErrorKind::Partial) if the commit has an
    ///   `Absent` or a `Partial` finding on an entry of its own field 2. The
    ///   run applies this rule again until no finding changes, so the rule
    ///   reaches each commit above a broken attachment.
    ///
    /// The first rule that applies gives the finding of an entry. An entry
    /// that no rule applies to gives no finding. A `Defective` finding does
    /// not make the commit above it partial. A checksum that field 2 names
    /// under two names gives two findings. Two entries with one name, and
    /// names that are not sorted, give no finding. If
    /// [`mark_partial`](FsckOptions::mark_partial) and
    /// [`mark_attachments`](FsckOptions::mark_attachments) are set, the run
    /// marks each commit with an `Absent` or a `Partial` finding as partial.
    /// The marks reach each commit above a broken attachment, so a later pull
    /// of the top commit fetches the full set of its attachments. Such a mark
    /// does not change the other findings of the run.
    ///
    /// A run that ends early does not reach this check.
    ///
    /// # Early end
    ///
    /// A run ends early at three conditions:
    ///
    /// - A ref names a commit object that the object store does not hold
    ///   ([`FsckFailure::RefTarget`]).
    /// - A dirtree that the walk must read is absent
    ///   ([`FsckFailure::MissingDirTree`]).
    /// - A binding check fails ([`FsckFailure::Binding`]).
    ///
    /// After the first two conditions, the run cannot read the next object
    /// that it must read. A failed binding check states a fact about the refs
    /// and marks nothing. The run records each other fault and continues, so
    /// one run reports each fault that it can reach.
    ///
    /// [`FsckReport::failure`] holds the condition, and
    /// [`FsckReport::reached`] holds the phase.
    ///
    /// # Tombstones
    ///
    /// If [`add_tombstones`](FsckOptions::add_tombstones) is set, one step
    /// follows the four phases and the attachment check.
    /// The step deletes each commit object whose parent commit object is
    /// absent. It writes a `.tombstone-commit` object that names each deleted
    /// commit. The step also deletes such a commit if another commit names it
    /// as an attachment.
    ///
    /// The step writes to the repository. After a walk that found a corrupt
    /// object, the step runs only if [`all`](FsckOptions::all) or
    /// [`delete`](FsckOptions::delete) is set. After a walk that found only
    /// absent objects, or no fault, the step runs without `all` and `delete`.
    /// A run that ends early does not reach the step.
    ///
    /// The step reads the parent of each commit against the commit list of
    /// the start of the run. As a result, one run removes one generation. If
    /// the run removes the parent of a commit, the next run removes that
    /// commit.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if a ref file is not UTF-8.
    /// - [`Error::Core`] if a ref file holds no checksum, if the header of a
    ///   content object does not serialize, or if `[core] fsync` is not a
    ///   boolean.
    /// - [`Error::Io`] if a read or a write on the file system fails. These
    ///   are the listing of the refs and of the objects, the read of a commit
    ///   that a ref names or of a dirtree, the check for a `.commitpartial`
    ///   marker, the unlink of an object, and the write of a marker or a
    ///   tombstone.
    /// - [`Error::InvalidFormat`] if a commit that a ref names, or a dirtree,
    ///   is larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is
    ///   not a regular file, or if a symlink is on its path. The listing of
    ///   the objects also gives this error for a symlink or an entry that is
    ///   not a directory at `objects/<xx>`, and so does the unlink of an
    ///   object.
    /// - [`Error::InvalidFormat`] if `state` is a symlink or is not a
    ///   directory.
    pub async fn fsck(&self, opts: &FsckOptions) -> Result<FsckReport> {
        let mut ctx = Ctx::default();
        // Every phase that reads a ref reads this one listing.
        let (ref_targets, collection_refs) = self.fsck_read_refs().await?;
        let own = self.config().collection_id();
        ctx.own_mirror_refs = collection_refs
            .iter()
            .filter(|entry| is_own_mirror(entry, own))
            .map(|entry| entry.name.clone())
            .collect();

        // Phase 1: the refs.
        if let Some(failure) = self
            .fsck_validate_refs(&ref_targets, opts, &mut ctx)
            .await?
        {
            return Ok(ctx.finish(FsckPhase::ValidateRefs, 0, Some(failure)));
        }
        ctx.ref_findings = ctx.errors.len();

        // Phase 2: the collection refs.
        if let Some(failure) = self
            .fsck_validate_collection_refs(&collection_refs, opts, &mut ctx)
            .await?
        {
            return Ok(ctx.finish(FsckPhase::ValidateCollectionRefs, 0, Some(failure)));
        }
        ctx.ref_findings = ctx.errors.len();

        // Phase 3: the commit objects.
        let commits = self.list_commits().await?;
        if let Some(failure) = self
            .fsck_enumerate_commits(&commits, &ref_targets, &collection_refs, opts, &mut ctx)
            .await?
        {
            return Ok(ctx.finish(
                FsckPhase::EnumerateCommits,
                0,
                Some(FsckFailure::Binding(failure)),
            ));
        }

        // Phase 4: collect the object set the verified commits reference, then
        // verify each object in it.
        let mut attachments = Vec::new();
        let order = match self
            .fsck_collect_objects(&ctx.verified, &mut attachments)
            .await?
        {
            Ok(order) => order,
            Err(failure) => return Ok(ctx.finish(FsckPhase::VerifyObjects, 0, Some(failure))),
        };
        let objects_checked = order.len();
        self.fsck_verify_objects(&order, &mut ctx).await?;

        // Name the commits that reach each finding, and act on the findings:
        // unlink if `delete` is set, and mark as partial. The naming step
        // reads the dirtrees again, so it runs before the first unlink.
        if !ctx.errors.is_empty() {
            self.fsck_attribute_findings(&mut ctx).await?;
            self.fsck_apply_findings(opts, &mut ctx).await?;
        }

        // The attachments, against the state after the actions above.
        self.fsck_check_attachments(&commits, &attachments, opts, &mut ctx)
            .await?;

        // The tombstone step writes to the repository, so it has the
        // condition of the `ostree` command: a walk that reached its end. A
        // corrupt object ends the walk of the `ostree` command unless `all` or
        // `delete` is set. An absent object never ends it.
        let corrupt = ctx
            .errors
            .iter()
            .any(|error| !matches!(error.kind, FsckErrorKind::Missing));
        if opts.add_tombstones && (opts.all || opts.delete || !corrupt) {
            self.fsck_add_tombstones(&commits, &mut ctx).await?;
        }

        Ok(ctx.finish(FsckPhase::VerifyObjects, objects_checked, None))
    }

    /// Reads the refs of the run, once.
    ///
    /// The result holds each ref under `refs/heads` and `refs/remotes`, by the
    /// bare name that a message gives it, and each collection-qualified ref.
    /// The refspec of a remote ref has the remote name before a `:`. The
    /// message of the `ostree` command drops it, so the function keeps the
    /// tail only.
    async fn fsck_read_refs(&self) -> Result<(Vec<(String, Checksum)>, Vec<CollectionRefEntry>)> {
        let heads = self.list_refs(None).await?;
        let collection_refs = self.collection_refs_over(&heads, None).await?;
        let mut targets = heads;
        for (refspec, commit) in self.list_remote_refs().await? {
            let name = match refspec.split_once(':') {
                Some((_, name)) => name.to_owned(),
                None => refspec,
            };
            targets.push((name, commit));
        }
        Ok((targets, collection_refs))
    }

    /// Runs phase 1: loads and verifies the commit that each ref under
    /// `refs/heads` and `refs/remotes` names. If `verify_bindings` is set, it
    /// checks each commit against the ref through which the run reached it.
    async fn fsck_validate_refs(
        &self,
        targets: &[(String, Checksum)],
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<Option<FsckFailure>> {
        let fsync = opts.delete && self.config().fsync()?;
        for (name, commit) in targets {
            let commit = *commit;
            let bytes = match self
                .fsck_check_ref_target(name, commit, opts, fsync, ctx)
                .await?
            {
                Err(failure) => return Ok(Some(failure)),
                Ok(bytes) => bytes,
            };
            if opts.verify_bindings
                && let Some(bytes) = bytes
                && let Ok(parsed) = Commit::parse(&bytes)
                && let Some(kind) = check_ref_binding(&parsed, name)
            {
                return Ok(Some(FsckFailure::Binding(FsckBindingError {
                    commit,
                    kind,
                })));
            }
        }
        Ok(None)
    }

    /// Loads the commit object that one ref names and verifies its checksum.
    ///
    /// `Err` ends the run. `Ok(None)` records a finding and leaves the commit
    /// unread. The caller decides if the run continues after it. `display` is
    /// the ref as a message names it. `fsync` is the value of `[core] fsync`
    /// for the unlink of a `delete` run.
    async fn fsck_check_ref_target(
        &self,
        display: &str,
        commit: Checksum,
        opts: &FsckOptions,
        fsync: bool,
        ctx: &mut Ctx,
    ) -> Result<std::result::Result<Option<Vec<u8>>, FsckFailure>> {
        let Some(bytes) = self.held_object_bytes(ObjectType::Commit, &commit).await? else {
            return Ok(Err(FsckFailure::RefTarget {
                ref_name: display.to_owned(),
                commit,
                removed: false,
            }));
        };
        let actual = Checksum::sha256(&bytes);
        if actual == commit {
            return Ok(Ok(Some(bytes)));
        }
        let object = ObjectName::new(commit, ObjectType::Commit);
        ctx.record(object, FsckErrorKind::ChecksumMismatch { actual });
        if opts.delete {
            self.fsck_unlink_object(object, fsync).await?;
            ctx.deleted.insert(object);
            return Ok(Err(FsckFailure::RefTarget {
                ref_name: display.to_owned(),
                commit,
                removed: true,
            }));
        }
        Ok(Ok(None))
    }

    /// Runs phase 2: loads and verifies the commit that each
    /// collection-qualified ref names. If `verify_bindings` is set, it checks
    /// each commit against the collection id of the ref.
    ///
    /// Phase 1 already read each local ref that the collection id of the
    /// repository qualifies. This phase reads such a ref for its binding only.
    async fn fsck_validate_collection_refs(
        &self,
        entries: &[CollectionRefEntry],
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<Option<FsckFailure>> {
        let fsync = opts.delete && self.config().fsync()?;
        for entry in entries {
            let bytes = if entry.local {
                self.load_object_bytes(ObjectType::Commit, &entry.commit)
                    .await
                    .ok()
            } else {
                let display = format!("({}, {})", entry.collection, entry.name);
                match self
                    .fsck_check_ref_target(&display, entry.commit, opts, fsync, ctx)
                    .await?
                {
                    Err(failure) => return Ok(Some(failure)),
                    Ok(bytes) => bytes,
                }
            };
            if opts.verify_bindings
                && let Some(bytes) = bytes
                && let Ok(parsed) = Commit::parse(&bytes)
                && let Some(bound) = parsed.collection_binding()
                && bound != entry.collection
            {
                return Ok(Some(FsckFailure::Binding(FsckBindingError {
                    commit: entry.commit,
                    kind: FsckBindingErrorKind::CollectionMismatch {
                        bound: bound.to_owned(),
                        found_under: entry.collection.clone(),
                    },
                })));
            }
        }
        Ok(None)
    }

    /// Runs phase 3: separates the commit objects that the run verifies from
    /// the commits already marked as partial. If `verify_back_refs` is set, it
    /// checks each commit in the store against the refs that its bindings name.
    async fn fsck_enumerate_commits(
        &self,
        commits: &[Checksum],
        targets: &[(String, Checksum)],
        collection_refs: &[CollectionRefEntry],
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<Option<FsckBindingError>> {
        for commit in commits {
            if self.commit_state(commit).await? == crate::read::CommitState::Partial {
                ctx.commits_partial += 1;
            } else {
                ctx.verified.push(*commit);
            }
        }

        if !opts.verify_back_refs {
            return Ok(None);
        }
        let by_name = index_first(
            targets
                .iter()
                .map(|(name, commit)| (name.as_str(), *commit)),
        );
        // The refs of the own collection id are the local refs. A ref under
        // `refs/mirrors/` of that id gives no pair.
        let own = self.config().collection_id();
        let by_pair = index_first(
            collection_refs
                .iter()
                .filter(|entry| !is_own_mirror(entry, own))
                .map(|entry| {
                    (
                        (entry.collection.as_str(), entry.name.as_str()),
                        entry.commit,
                    )
                }),
        );
        for commit in commits {
            let Ok(bytes) = self.load_object_bytes(ObjectType::Commit, commit).await else {
                continue;
            };
            let Ok(parsed) = Commit::parse(&bytes) else {
                continue;
            };
            if let Some(kind) = check_back_refs(&parsed, commit, &by_name, &by_pair) {
                return Ok(Some(FsckBindingError {
                    commit: *commit,
                    kind,
                }));
            }
        }
        Ok(None)
    }

    /// Runs the first half of phase 4: returns the distinct objects that the
    /// verified commits reference, in the order of the walk.
    ///
    /// An absent dirtree ends the run, because its subtree is unreadable. An
    /// absent dirmeta or content object is in the set, and the second half
    /// reports it.
    ///
    /// For each commit whose field 2 is not empty, the function adds the
    /// commit and the entries of field 2 to `attachments`, in the order of
    /// `commits`.
    async fn fsck_collect_objects(
        &self,
        commits: &[Checksum],
        attachments: &mut Vec<(Checksum, Vec<RelatedEntry>)>,
    ) -> Result<std::result::Result<Vec<ObjectName>, FsckFailure>> {
        let mut order = Vec::new();
        let mut seen = HashSet::new();
        let mut walked = HashSet::new();
        for commit in commits {
            let name = ObjectName::new(*commit, ObjectType::Commit);
            push_object(&mut order, &mut seen, name);
            let Ok(bytes) = self.load_object_bytes(ObjectType::Commit, commit).await else {
                continue;
            };
            let Ok(mut parsed) = Commit::parse(&bytes) else {
                continue;
            };
            if !parsed.related.is_empty() {
                attachments.push((
                    *commit,
                    related::into_entries(std::mem::take(&mut parsed.related)),
                ));
            }
            push_object(
                &mut order,
                &mut seen,
                ObjectName::new(parsed.root_dirmeta, ObjectType::DirMeta),
            );
            let mut sink = CollectSink {
                order: &mut order,
                seen: &mut seen,
            };
            if let Err(absent) =
                walk_subtree(self, parsed.root_dirtree, &mut walked, &mut sink).await?
            {
                return Ok(Err(FsckFailure::MissingDirTree(absent)));
            }
        }
        Ok(Ok(order))
    }

    /// Runs the second half of phase 4: reads each object in the set once.
    ///
    /// The function records a checksum mismatch, an unreadable object, or an
    /// absent object. It reads each object in the set, whatever the findings
    /// before it. One read buffer serves each content object in the set, so a
    /// store of many small objects allocates once.
    async fn fsck_verify_objects(&self, order: &[ObjectName], ctx: &mut Ctx) -> Result<()> {
        let mut buf: Vec<u8> = Vec::new();
        for name in order {
            if name.ty == ObjectType::File {
                if buf.len() < COPY_CHUNK {
                    buf.resize(COPY_CHUNK, 0);
                }
                self.fsck_hash_content(*name, &mut buf, ctx).await?;
            } else {
                self.fsck_hash_metadata(*name, ctx).await?;
            }
        }
        Ok(())
    }

    /// Verifies the checksum of the bytes of one metadata object.
    ///
    /// If the checksum does not match, the function also parses the bytes as
    /// the type of the object. If the parse fails, the run reports the object
    /// and does not act on it. `delete` does not unlink it, and no commit is
    /// marked as partial because of it.
    async fn fsck_hash_metadata(&self, name: ObjectName, ctx: &mut Ctx) -> Result<()> {
        match self.load_object_bytes(name.ty, &name.checksum).await {
            Ok(bytes) => {
                let actual = Checksum::sha256(&bytes);
                if actual != name.checksum {
                    ctx.record(name, FsckErrorKind::ChecksumMismatch { actual });
                    if !parses_as(name.ty, &bytes) {
                        ctx.unparsable.insert(name);
                    }
                }
            }
            Err(Error::ObjectNotFound { .. }) => ctx.record(name, FsckErrorKind::Missing),
            // The run records a read failure as corruption and continues.
            Err(Error::Io(e)) => ctx.record(name, FsckErrorKind::Corrupt(e.to_string())),
            Err(e) => return Err(e),
        }
        Ok(())
    }

    /// Verifies the checksum of a content object over its framed header and
    /// its streamed payload, and records each fault.
    ///
    /// The load keeps the object file open, and the payload streams from it,
    /// so the object opens once.
    async fn fsck_hash_content(
        &self,
        name: ObjectName,
        buf: &mut [u8],
        ctx: &mut Ctx,
    ) -> Result<()> {
        let checksum = name.checksum;
        let (file, payload) = match self.open_file(&checksum).await {
            Ok(opened) => opened,
            Err(Error::ObjectNotFound { .. }) => {
                ctx.record(name, FsckErrorKind::Missing);
                return Ok(());
            }
            Err(Error::Io(e)) => {
                ctx.record(name, FsckErrorKind::Corrupt(e.to_string()));
                return Ok(());
            }
            Err(Error::InvalidFormat(m)) => {
                ctx.record(name, FsckErrorKind::Corrupt(m));
                return Ok(());
            }
            Err(Error::Core(e)) => {
                ctx.record(name, FsckErrorKind::Corrupt(e.to_string()));
                return Ok(());
            }
            Err(e) => return Err(e),
        };

        let mut hasher = ContentHasher::new(&file.header())?;

        let mut reader = file.reader_over(payload);
        loop {
            match reader.read(buf).await {
                Ok(0) => break,
                Ok(n) => hasher.update(&buf[..n]),
                Err(e) => {
                    ctx.record(
                        name,
                        FsckErrorKind::Corrupt(format!("payload read failed: {e}")),
                    );
                    return Ok(());
                }
            }
        }

        let actual = hasher.finish();
        if actual != checksum {
            ctx.record(name, FsckErrorKind::ChecksumMismatch { actual });
        }
        Ok(())
    }

    /// Names the verified commits that reach each faulty object.
    ///
    /// The walk reads the dirtrees a second time, once for each verified
    /// commit, so it runs before `delete` unlinks an object. A finding of the
    /// ref phase keeps its empty list, because the ref phase reaches no commit
    /// through the object that it read.
    async fn fsck_attribute_findings(&self, ctx: &mut Ctx) -> Result<()> {
        let faulty: HashSet<ObjectName> = ctx.errors[ctx.ref_findings..]
            .iter()
            .map(|e| e.object)
            .collect();
        if faulty.is_empty() {
            return Ok(());
        }
        // The walk records only the faulty objects that it reaches, so the
        // memory of one commit grows with the count of findings. The size of
        // its tree does not change it.
        let mut found: HashMap<ObjectName, Vec<Checksum>> = HashMap::new();
        for commit in &ctx.verified {
            let mut sink = ReachSink {
                faulty: &faulty,
                commit: *commit,
                found: &mut found,
            };
            sink.take(ObjectName::new(*commit, ObjectType::Commit));
            if let Ok(bytes) = self.load_object_bytes(ObjectType::Commit, commit).await
                && let Ok(parsed) = Commit::parse(&bytes)
            {
                sink.take(ObjectName::new(parsed.root_dirmeta, ObjectType::DirMeta));
                let mut walked = HashSet::new();
                walk_subtree(self, parsed.root_dirtree, &mut walked, &mut sink)
                    .await?
                    .ok();
            }
        }
        // `ctx.verified` is sorted, so each list is sorted.
        let ref_findings = ctx.ref_findings;
        for error in &mut ctx.errors[ref_findings..] {
            if let Some(commits) = found.remove(&error.object) {
                error.in_commits = commits;
            }
        }
        Ok(())
    }

    /// Acts on the findings. If `delete` is set, the function unlinks each
    /// faulty object. It marks each commit that reaches a deleted or an
    /// absent object as partial. The markers go first, and the unlinks
    /// follow. If `[core] fsync` is on, the sync of `state/` after each
    /// marker comes before the first unlink.
    ///
    /// A checksum mismatch alone marks no commit, as with the `ostree`
    /// command. The commits of an object that is present and wrong stay
    /// complete until the object is removed.
    async fn fsck_apply_findings(&self, opts: &FsckOptions, ctx: &mut Ctx) -> Result<()> {
        let mut doomed = Vec::new();
        let mut incomplete: Vec<Checksum> = Vec::new();
        for error in &ctx.errors {
            let absent = matches!(error.kind, FsckErrorKind::Missing);
            if (!absent && !opts.delete) || ctx.unparsable.contains(&error.object) {
                continue;
            }
            if !absent {
                doomed.push(error.object);
            }
            for commit in &error.in_commits {
                if ctx.incomplete.insert(*commit) {
                    incomplete.push(*commit);
                }
            }
        }
        let fsync = self.config().fsync()?;
        // The markers go first, so a commit whose object goes is partial
        // before the object goes.
        if opts.mark_partial {
            ctx.marked_partial.extend(incomplete.iter().copied());
            self.mark_commits_partial(incomplete, fsync).await?;
        }
        for object in doomed {
            if !ctx.deleted.insert(object) {
                continue;
            }
            self.fsck_unlink_object(object, fsync).await?;
        }
        Ok(())
    }

    /// Checks the attachments of each verified commit that the run did not
    /// delete, and under `mark_partial` and `mark_attachments` marks each
    /// commit with an absent or a partial attachment as partial.
    ///
    /// `all` is the commit listing of the start of the run. `attachments`
    /// holds each verified commit whose field 2 is not empty, with its
    /// entries, sorted by commit. An attachment is also partial if it has an
    /// absent or a partial attachment of its own, at each depth. The function
    /// reads no object.
    async fn fsck_check_attachments(
        &self,
        all: &[Checksum],
        attachments: &[(Checksum, Vec<RelatedEntry>)],
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<()> {
        let deleted = |commit: &Checksum| {
            ctx.deleted
                .contains(&ObjectName::new(*commit, ObjectType::Commit))
        };
        let findings = attachment_findings(
            attachments,
            |commit| !deleted(commit),
            |attachment| all.binary_search(attachment).is_err() || deleted(attachment),
            |attachment| {
                ctx.verified.binary_search(attachment).is_err()
                    || ctx.incomplete.contains(attachment)
            },
        );
        if opts.mark_partial && opts.mark_attachments {
            let mut marked = HashSet::new();
            let mut to_mark = Vec::new();
            for finding in &findings {
                let commit = finding.commit;
                if matches!(finding.kind, FsckAttachmentErrorKind::Defective(_))
                    || ctx.incomplete.contains(&commit)
                    || !marked.insert(commit)
                {
                    continue;
                }
                to_mark.push(commit);
            }
            if !to_mark.is_empty() {
                let fsync = self.config().fsync()?;
                ctx.marked_partial.extend(to_mark.iter().copied());
                self.mark_commits_partial(to_mark, fsync).await?;
            }
        }
        ctx.attachment_errors = findings;
        Ok(())
    }

    /// Deletes each commit object whose parent commit object is absent from
    /// the store, and writes a `.tombstone-commit` that names it.
    ///
    /// The function reads the absence against the listing of the start of the
    /// run, so one run removes one generation. If this run removed the parent
    /// of a commit, the next run removes the commit.
    async fn fsck_add_tombstones(&self, all: &[Checksum], ctx: &mut Ctx) -> Result<()> {
        let present: HashSet<Checksum> = all.iter().copied().collect();
        let fsync = self.config().fsync()?;
        for commit in all.iter().copied() {
            let Ok(bytes) = self.load_object_bytes(ObjectType::Commit, &commit).await else {
                continue;
            };
            let Ok(parsed) = Commit::parse(&bytes) else {
                continue;
            };
            let Some(parent) = parsed.parent else {
                continue;
            };
            if present.contains(&parent) {
                continue;
            }
            let mode = self.mode();
            let repo = self.clone();
            ostrya_rt::unblock(move || write_tombstone(repo.objects(), &commit, mode, fsync))
                .await?;
            self.fsck_unlink_object(ObjectName::new(commit, ObjectType::Commit), fsync)
                .await?;
            ctx.tombstoned.insert(commit);
        }
        Ok(())
    }

    /// Unlinks one loose object. An absent file counts as a success. With
    /// `fsync`, the call syncs the `objects/<xx>` directory of the object
    /// after the unlink.
    ///
    /// The unlink follows no symlink at `objects/<xx>`. Such a symlink gives
    /// [`Error::InvalidFormat`], and the run stops.
    async fn fsck_unlink_object(&self, name: ObjectName, fsync: bool) -> Result<()> {
        let repo = self.clone();
        let path = name.loose_path(repo.mode());
        ostrya_rt::unblock(move || {
            repo.objects()
                .remove_file(&path, fsync)
                .map(drop)
                .map_err(|e| crate::read::object_path_error(e, &path).into())
        })
        .await
    }

    /// Writes the `state/<commit>.commitpartial` marker of each of
    /// `commits`, which holds the one state byte of the `ostree` command, in
    /// one trip to the blocking pool.
    ///
    /// The call opens `state/` one time, and makes it if it is absent. It
    /// creates each marker with `O_EXCL` and writes the byte into the new
    /// file. An entry that is present at the name of a marker, of any type,
    /// stays as it is, and the call writes nothing into it. A symlink at the
    /// name is such an entry, so the call does not write through it. With
    /// `fsync`, the call syncs `state/` after the create of each marker. It
    /// does not sync the content of a marker.
    ///
    /// A symlink or an entry that is not a directory at `state` gives
    /// [`Error::InvalidFormat`].
    async fn mark_commits_partial(&self, commits: Vec<Checksum>, fsync: bool) -> Result<()> {
        self.create_partial_markers(commits, &[PARTIAL_STATE_BYTE], fsync)
            .await
    }
}

/// Returns the failure if the binding check of the ref phase refuses this
/// commit under this ref.
///
/// A commit with no `ostree.ref-binding` key is older than the convention and
/// passes, as with the `ostree` command. A commit with a binding list that
/// does not hold the ref fails.
fn check_ref_binding(commit: &Commit, ref_name: &str) -> Option<FsckBindingErrorKind> {
    commit.metadata_value("ostree.ref-binding")?;
    let bindings = commit.ref_bindings();
    if bindings.contains(&ref_name) {
        return None;
    }
    Some(FsckBindingErrorKind::RefNotBound {
        ref_name: ref_name.to_owned(),
        bindings: bindings.into_iter().map(str::to_owned).collect(),
    })
}

/// Returns the failure if the back-reference check refuses this commit.
///
/// Each name in the `ostree.ref-binding` of the commit must name a ref that
/// resolves to the commit. A ref under `refs/remotes` counts by its bare name.
/// If the commit has an `ostree.collection-binding`, the collection ref
/// `(binding, name)` must also exist and resolve to it. The function reads the
/// names in stored order and returns the first failure.
fn check_back_refs(
    commit: &Commit,
    checksum: &Checksum,
    by_name: &HashMap<&str, Checksum>,
    by_pair: &HashMap<(&str, &str), Checksum>,
) -> Option<FsckBindingErrorKind> {
    let collection = commit.collection_binding();
    for name in commit.ref_bindings() {
        match by_name.get(name) {
            None => {
                return Some(FsckBindingErrorKind::BackRefMissing {
                    ref_name: name.to_owned(),
                });
            }
            Some(target) if target != checksum => {
                return Some(FsckBindingErrorKind::BackRefMismatch {
                    ref_name: name.to_owned(),
                });
            }
            Some(_) => {}
        }
        let Some(collection) = collection else {
            continue;
        };
        match by_pair.get(&(collection, name)) {
            None => {
                return Some(FsckBindingErrorKind::BackCollectionRefMissing {
                    collection_id: collection.to_owned(),
                    ref_name: name.to_owned(),
                });
            }
            Some(target) if target != checksum => {
                return Some(FsckBindingErrorKind::BackCollectionRefMismatch {
                    collection_id: collection.to_owned(),
                    ref_name: name.to_owned(),
                });
            }
            Some(_) => {}
        }
    }
    None
}

/// Returns `true` if `entry` is a ref under `refs/mirrors/ID/` of `own`, the
/// `[core] collection-id` of the repository.
fn is_own_mirror(entry: &CollectionRefEntry, own: Option<&str>) -> bool {
    !entry.local && Some(entry.collection.as_str()) == own
}

/// Indexes `entries` by key and keeps the first value of each key. A linear
/// scan in the same order finds the same value.
fn index_first<K: std::hash::Hash + Eq, V>(entries: impl Iterator<Item = (K, V)>) -> HashMap<K, V> {
    let mut map = HashMap::new();
    for (key, value) in entries {
        map.entry(key).or_insert(value);
    }
    map
}

/// Returns `true` if `bytes` parse as the type `ty`. The run acts on a
/// metadata object with a wrong checksum only if this check passes.
fn parses_as(ty: ObjectType, bytes: &[u8]) -> bool {
    match ty {
        ObjectType::Commit => Commit::parse(bytes).is_ok(),
        ObjectType::DirTree => DirTreeRef::parse(bytes).is_ok(),
        ObjectType::DirMeta => DirMetaRef::parse(bytes).is_ok(),
        _ => true,
    }
}

/// What one subtree walk does with each object it reaches.
trait WalkSink {
    /// Takes one object that the walk reached.
    fn take(&mut self, object: ObjectName);
}

/// The sink that collects the distinct objects in the order of the walk.
struct CollectSink<'a> {
    order: &'a mut Vec<ObjectName>,
    seen: &'a mut HashSet<ObjectName>,
}

impl WalkSink for CollectSink<'_> {
    fn take(&mut self, object: ObjectName) {
        push_object(self.order, self.seen, object);
    }
}

/// The sink that names one commit against each faulty object it reaches.
///
/// If the walk reaches an object more than once under one commit, the sink
/// records it once. It appends the commit only if the commit is not already
/// the last name on the list of the object.
struct ReachSink<'a> {
    faulty: &'a HashSet<ObjectName>,
    commit: Checksum,
    found: &'a mut HashMap<ObjectName, Vec<Checksum>>,
}

impl WalkSink for ReachSink<'_> {
    fn take(&mut self, object: ObjectName) {
        if !self.faulty.contains(&object) {
            return;
        }
        let commits = self.found.entry(object).or_default();
        if commits.last() != Some(&self.commit) {
            commits.push(self.commit);
        }
    }
}

/// Appends one object if the walk did not take it before.
fn push_object(order: &mut Vec<ObjectName>, seen: &mut HashSet<ObjectName>, object: ObjectName) {
    if seen.insert(object) {
        order.push(object);
    }
}

/// The boxed future of the recursive subtree walk. Async recursion needs
/// indirection, so each level returns a boxed future.
type SubtreeFuture<'a> = Pin<Box<dyn Future<Output = Result<WalkOutcome>> + Send + 'a>>;

/// The result of a subtree walk: `Ok` if the walk reached each dirtree in the
/// subtree, or the first absent dirtree.
type WalkOutcome = std::result::Result<(), Checksum>;

/// Walks a dirtree and its full subtree, and gives each object to `sink`.
///
/// The walk enters each dirtree once in a pass, so it reads a subtree that two
/// directories share once. An absent dirtree ends the walk, and the result
/// names it. A present dirtree that does not parse gives itself and no child.
/// The verification pass then reports its checksum.
fn walk_subtree<'a, S: WalkSink + Send>(
    repo: &'a Repo,
    dirtree: Checksum,
    walked: &'a mut HashSet<Checksum>,
    sink: &'a mut S,
) -> SubtreeFuture<'a> {
    Box::pin(async move {
        let name = ObjectName::new(dirtree, ObjectType::DirTree);
        sink.take(name);
        if !walked.insert(dirtree) {
            return Ok(Ok(()));
        }
        let Some(bytes) = repo
            .held_object_bytes(ObjectType::DirTree, &dirtree)
            .await?
        else {
            return Ok(Err(dirtree));
        };
        let Ok(parsed) = DirTree::parse(&bytes) else {
            return Ok(Ok(()));
        };
        for (_, file) in parsed.files {
            sink.take(ObjectName::new(file, ObjectType::File));
        }
        for (_, subtree, submeta) in parsed.dirs {
            sink.take(ObjectName::new(submeta, ObjectType::DirMeta));
            if let Err(absent) = walk_subtree(repo, subtree, walked, sink).await? {
                return Ok(Err(absent));
            }
        }
        Ok(Ok(()))
    })
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::{MetadataExt, OpenOptionsExt, symlink};
    use std::path::{Path, PathBuf};

    use ostrya_core::RepoMode;

    use super::*;

    /// A temp directory that the drop removes.
    struct Scratch {
        path: PathBuf,
    }

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

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

    /// Creates an `archive` repository at `repo` below `base`.
    fn repo_in(base: &Path) -> Repo {
        ostrya_rt::block_on(Repo::create(
            &base.join("repo"),
            crate::CreateOptions::new(RepoMode::Archive),
        ))
        .unwrap()
    }

    /// Returns the path of the marker of `commit` in the repository at
    /// `repo` below `base`.
    fn marker_of(base: &Path, commit: &Checksum) -> PathBuf {
        base.join("repo/state")
            .join(crate::pull::partial_name(commit))
    }

    /// Makes a FIFO at `path`.
    fn mkfifo(path: &Path) {
        rustix::fs::mknodat(
            rustix::fs::CWD,
            path,
            rustix::fs::FileType::Fifo,
            rustix::fs::Mode::from_raw_mode(0o644),
            0,
        )
        .unwrap();
    }

    #[test]
    fn a_marker_holds_the_state_byte_with_the_mode_of_a_new_file() {
        let scratch = Scratch::new("marker-new");
        let repo = repo_in(&scratch.path);
        let commit = Checksum::sha256(b"commit");
        let _ = std::fs::remove_dir_all(scratch.path.join("repo/state"));

        ostrya_rt::block_on(repo.mark_commits_partial(vec![commit], true)).unwrap();
        let marker = marker_of(&scratch.path, &commit);
        assert_eq!(std::fs::read(&marker).unwrap(), b"f");
        let reference = scratch.path.join("repo/state/reference");
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o644)
            .open(&reference)
            .unwrap();
        let mode = |path: &Path| std::fs::metadata(path).unwrap().mode() & 0o7777;
        assert_eq!(mode(&marker), mode(&reference));
    }

    /// An entry at the name of the marker stays as it is, and the marking
    /// succeeds with no write. A symlink is not followed, and a FIFO is not
    /// opened.
    #[test]
    fn an_entry_at_the_marker_name_stays_and_the_marking_succeeds() {
        for case in ["empty", "symlink", "dangling", "fifo", "directory"] {
            let scratch = Scratch::new("marker-entry");
            let repo = repo_in(&scratch.path);
            let commit = Checksum::sha256(b"commit");
            let marker = marker_of(&scratch.path, &commit);
            std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
            let target = scratch.path.join("target");
            std::fs::write(&target, b"target").unwrap();
            match case {
                "empty" => std::fs::write(&marker, b"").unwrap(),
                "symlink" => symlink(&target, &marker).unwrap(),
                "dangling" => symlink(scratch.path.join("missing"), &marker).unwrap(),
                "fifo" => mkfifo(&marker),
                _ => std::fs::create_dir(&marker).unwrap(),
            }
            let before = std::fs::symlink_metadata(&marker).unwrap();

            ostrya_rt::block_on(repo.mark_commits_partial(vec![commit], true)).unwrap();
            let after = std::fs::symlink_metadata(&marker).unwrap();
            assert_eq!(after.ino(), before.ino(), "{case}");
            assert_eq!(after.file_type(), before.file_type(), "{case}");
            assert_eq!(after.len(), before.len(), "{case}");
            assert_eq!(std::fs::read(&target).unwrap(), b"target", "{case}");
            assert!(!scratch.path.join("missing").exists(), "{case}");
        }
    }

    #[test]
    fn a_symlink_at_state_fails_the_marking() {
        let scratch = Scratch::new("marker-state-link");
        let repo = repo_in(&scratch.path);
        let commit = Checksum::sha256(b"commit");
        let outside = scratch.path.join("outside");
        std::fs::create_dir(&outside).unwrap();
        let state = scratch.path.join("repo/state");
        let _ = std::fs::remove_dir_all(&state);
        symlink(&outside, &state).unwrap();

        let err = ostrya_rt::block_on(repo.mark_commits_partial(vec![commit], false)).unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
        assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
    }

    #[test]
    fn the_unlink_of_an_object_refuses_a_symlinked_fanout() {
        let scratch = Scratch::new("unlink-fanout-link");
        let repo = repo_in(&scratch.path);
        let name = ObjectName::new(Checksum::sha256(b"object"), ObjectType::File);
        let path = name.loose_path(RepoMode::Archive);
        let (fanout, leaf) = path.split_once('/').unwrap();
        let outside = scratch.path.join("outside");
        std::fs::create_dir(&outside).unwrap();
        std::fs::write(outside.join(leaf), b"object").unwrap();
        let link = scratch.path.join("repo/objects").join(fanout);
        let _ = std::fs::remove_dir_all(&link);
        symlink(&outside, &link).unwrap();

        let err = ostrya_rt::block_on(repo.fsck_unlink_object(name, true)).unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
        assert_eq!(std::fs::read(outside.join(leaf)).unwrap(), b"object");
    }

    /// One finding of [`attachment_findings`]: the naming commit, the name
    /// of the entry, and the kind.
    type Found = (Checksum, String, FsckAttachmentErrorKind);

    /// Returns an entry of field 2 with `name` that names `commit`.
    fn entry(name: &str, commit: Checksum) -> RelatedEntry {
        RelatedEntry {
            name: name.to_owned(),
            checksum: Ok(commit),
        }
    }

    /// Runs [`attachment_findings`] over `graph`, after a sort by commit.
    /// Each commit gets a check except those in `skipped`. `absent` and
    /// `partial` give the state of an attachment.
    fn run(
        mut graph: Vec<(Checksum, Vec<RelatedEntry>)>,
        skipped: &[Checksum],
        absent: &[Checksum],
        partial: &[Checksum],
    ) -> Vec<Found> {
        graph.sort_by_key(|(commit, _)| *commit);
        attachment_findings(
            &graph,
            |commit| !skipped.contains(commit),
            |commit| absent.contains(commit),
            |commit| partial.contains(commit),
        )
        .into_iter()
        .map(|finding| (finding.commit, finding.name, finding.kind))
        .collect()
    }

    /// Sorts `expected` by the naming commit, and keeps the order of the
    /// entries of one commit.
    fn by_commit(mut expected: Vec<Found>) -> Vec<Found> {
        expected.sort_by_key(|(commit, _, _)| *commit);
        expected
    }

    #[test]
    fn an_absent_commit_at_depth_four_makes_each_commit_above_partial() {
        let [a, b, c, d, e] = ["a", "b", "c", "d", "e"].map(|s| Checksum::sha256(s.as_bytes()));
        let graph = vec![
            (a, vec![entry("b", b)]),
            (b, vec![entry("c", c)]),
            (c, vec![entry("d", d)]),
            (d, vec![entry("e", e)]),
        ];

        let found = run(graph, &[], &[e], &[]);

        use FsckAttachmentErrorKind::{Absent, Partial};
        assert_eq!(
            found,
            by_commit(vec![
                (a, "b".to_owned(), Partial),
                (b, "c".to_owned(), Partial),
                (c, "d".to_owned(), Partial),
                (d, "e".to_owned(), Absent),
            ])
        );
    }

    #[test]
    fn a_partial_commit_below_a_diamond_gives_one_finding_for_each_entry() {
        let [r, a, b, d] = ["r", "a", "b", "d"].map(|s| Checksum::sha256(s.as_bytes()));
        let graph = vec![
            (r, vec![entry("lib/a", a), entry("lib/b", b)]),
            (a, vec![entry("d", d)]),
            (b, vec![entry("d", d)]),
        ];

        let found = run(graph, &[], &[], &[d]);

        use FsckAttachmentErrorKind::Partial;
        assert_eq!(
            found,
            by_commit(vec![
                (r, "lib/a".to_owned(), Partial),
                (r, "lib/b".to_owned(), Partial),
                (a, "d".to_owned(), Partial),
                (b, "d".to_owned(), Partial),
            ])
        );
    }

    #[test]
    fn a_defective_entry_does_not_make_the_commit_above_it_partial() {
        let [r, c] = ["r", "c"].map(|s| Checksum::sha256(s.as_bytes()));
        let graph = vec![
            (r, vec![entry("c", c)]),
            (
                c,
                vec![RelatedEntry {
                    name: "d".to_owned(),
                    checksum: Err(20),
                }],
            ),
        ];

        let found = run(graph, &[], &[], &[]);

        assert_eq!(
            found,
            vec![(
                c,
                "d".to_owned(),
                FsckAttachmentErrorKind::Defective(
                    "entry 0 (d) has a checksum of 20 bytes, not 32".to_owned()
                ),
            )]
        );
    }

    #[test]
    fn a_skipped_commit_gets_no_finding_and_gives_none_to_the_commit_above_it() {
        let [r, c, d] = ["r", "c", "d"].map(|s| Checksum::sha256(s.as_bytes()));
        let graph = vec![(r, vec![entry("c", c)]), (c, vec![entry("d", d)])];

        // The run deleted `c`: it gets no check, and the entry that names it
        // is absent.
        assert_eq!(
            run(graph.clone(), &[c], &[c, d], &[]),
            vec![(r, "c".to_owned(), FsckAttachmentErrorKind::Absent)]
        );
        // A skipped commit that is not absent makes no commit above it
        // partial.
        assert_eq!(run(graph, &[c], &[d], &[]), Vec::<Found>::new());
    }

    #[test]
    fn a_direct_and_a_propagated_finding_keep_the_stored_order() {
        let [r, c, d, x, y] = ["r", "c", "d", "x", "y"].map(|s| Checksum::sha256(s.as_bytes()));
        let graph = vec![
            (
                r,
                vec![
                    entry("a/first", c),
                    entry("b/second", x),
                    entry("c/third", c),
                    entry("d/fourth", y),
                ],
            ),
            (c, vec![entry("d", d)]),
        ];

        let found = run(graph, &[], &[d, x], &[y]);

        use FsckAttachmentErrorKind::{Absent, Partial};
        assert_eq!(
            found,
            by_commit(vec![
                (r, "a/first".to_owned(), Partial),
                (r, "b/second".to_owned(), Absent),
                (r, "c/third".to_owned(), Partial),
                (r, "d/fourth".to_owned(), Partial),
                (c, "d".to_owned(), Absent),
            ])
        );
    }

    #[test]
    fn the_order_of_the_commits_does_not_change_the_findings() {
        use FsckAttachmentErrorKind::{Absent, Partial};
        // Each seed gives other checksums, so the commits sort, and the
        // queue takes them, in another order.
        for seed in 0..32 {
            let [t, r, a, b, c, d] = ["t", "r", "a", "b", "c", "d"]
                .map(|s| Checksum::sha256(format!("{seed}-{s}").as_bytes()));
            let graph = vec![
                (t, vec![entry("r", r), entry("c", c)]),
                (r, vec![entry("a", a), entry("b", b)]),
                (a, vec![entry("c", c)]),
                (b, vec![entry("d", d)]),
                (c, vec![entry("d", d)]),
            ];

            let found = run(graph, &[], &[d], &[]);

            assert_eq!(
                found,
                by_commit(vec![
                    (t, "r".to_owned(), Partial),
                    (t, "c".to_owned(), Partial),
                    (r, "a".to_owned(), Partial),
                    (r, "b".to_owned(), Partial),
                    (a, "c".to_owned(), Partial),
                    (b, "d".to_owned(), Absent),
                    (c, "d".to_owned(), Absent),
                ]),
                "seed {seed}"
            );
        }
    }
}