ostrya 0.9.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
//! 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::io::Write;
use std::os::fd::{AsFd, BorrowedFd};
use std::pin::Pin;

use futures_lite::AsyncReadExt;
use ostrya_core::{
    Checksum, Commit, ContentHasher, DirMetaRef, DirTree, DirTreeRef, ObjectName, ObjectType,
    RepoMode,
};
use rustix::fs::{AtFlags, Mode, OFlags};
use rustix::io::Errno;

use crate::error::{Error, Result};
use crate::perm;
use crate::refs::CollectionRefEntry;
use crate::related::{self, RelatedEntry, RelatedField, RelatedWarning};
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`.
    ///
    /// If [`mark_dependencies`](FsckOptions::mark_dependencies) is also
    /// `true`, the switch marks each commit that has an
    /// [`Absent`](FsckDependencyErrorKind::Absent) or a
    /// [`Partial`](FsckDependencyErrorKind::Partial) dependency, so a later
    /// pull of the commit fetches its dependencies. A
    /// [`Defective`](FsckDependencyErrorKind::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`](FsckDependencyErrorKind::Absent) or a
    /// [`Partial`](FsckDependencyErrorKind::Partial) dependency 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-dependencies`.
    ///
    /// With the value `false`, the run reports each finding in
    /// [`FsckReport::dependency_errors`] and marks no commit for a
    /// dependency. 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_dependencies: 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. 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.
    ///
    /// 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.
    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_dependencies: 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_dependencies`](FsckOptions::mark_dependencies) 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,
    },
}

/// A composefs image that fails the image check of [`Repo::fsck`].
#[derive(Debug, Clone)]
pub struct FsckImageError {
    /// The commit of the image. It is also the name of the image object.
    pub commit: Checksum,
    /// The cause of the finding.
    pub kind: FsckImageErrorKind,
}

/// The cause of a finding on a composefs image.
#[derive(Debug, Clone)]
pub enum FsckImageErrorKind {
    /// The commit does not carry `ostree.composefs.digest.v0`.
    NoKey,
    /// The commit does not parse, or the first entry of
    /// `ostree.composefs.digest.v0` is not a variant of type `ay` with 32
    /// bytes. The payload is the reason.
    BadKey(String),
    /// The fs-verity digest of the image is not the value of the key.
    Mismatch {
        /// The digest that the commit records.
        expected: [u8; 32],
        /// The fs-verity digest of the image.
        actual: [u8; 32],
    },
    /// The commit object is present and does not load. The payload is the
    /// reason.
    CommitUnreadable(String),
    /// The image does not read. The payload is the reason.
    ImageUnreadable(String),
}

impl std::fmt::Display for FsckImageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "composefs image of commit {}: ", self.commit)?;
        match &self.kind {
            FsckImageErrorKind::NoKey => {
                write!(f, "the commit does not carry ostree.composefs.digest.v0")
            }
            FsckImageErrorKind::BadKey(reason)
            | FsckImageErrorKind::CommitUnreadable(reason)
            | FsckImageErrorKind::ImageUnreadable(reason) => f.write_str(reason),
            FsckImageErrorKind::Mismatch { expected, actual } => write!(
                f,
                "the commit records the digest {}, the image has {}",
                crate::composefs::digest_hex(expected),
                crate::composefs::digest_hex(actual)
            ),
        }
    }
}

/// The key of the commit of a composefs image, as the image check of
/// [`Repo::fsck`] reads it.
enum ImageKey {
    /// The commit object is absent.
    CommitAbsent,
    /// The commit gives a finding before the check reads the image.
    Fault(FsckImageErrorKind),
    /// The digest that the commit records, or `None` if the commit does not
    /// carry the key.
    Read(Option<[u8; 32]>),
}

/// A dependency 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::InvalidRelated`] with the same commit, field 2, and reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FsckDependencyError {
    /// 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 dependency: Option<Checksum>,
    /// The cause of the finding.
    pub kind: FsckDependencyErrorKind,
}

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

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

impl std::fmt::Display for FsckDependencyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        RelatedWarning {
            commit: self.commit,
            field: RelatedField::Dependencies,
            reason: self.reason(),
        }
        .fmt(f)
    }
}

/// Returns the finding on each entry of `entries`, the field 2 of `commit`,
/// in the stored order.
///
/// `absent` and `partial` tell the state of a dependency. `nested` tells if
/// the field 2 of a dependency is not empty.
pub(crate) fn dependency_findings(
    commit: Checksum,
    entries: &[RelatedEntry],
    absent: impl Fn(&Checksum) -> bool,
    partial: impl Fn(&Checksum) -> bool,
    nested: impl Fn(&Checksum) -> bool,
) -> Vec<FsckDependencyError> {
    let mut findings = Vec::new();
    for (index, entry) in entries.iter().enumerate() {
        let kind = match (entry.defect(index), entry.checksum) {
            (Some(reason), _) => FsckDependencyErrorKind::Defective(reason),
            (None, Ok(dependency)) if absent(&dependency) => FsckDependencyErrorKind::Absent,
            (None, Ok(dependency)) if partial(&dependency) => FsckDependencyErrorKind::Partial,
            (None, Ok(dependency)) if nested(&dependency) => FsckDependencyErrorKind::Defective(
                related::dependency_reason(&entry.name, &dependency, related::NESTED_REASON),
            ),
            (None, _) => continue,
        };
        findings.push(FsckDependencyError {
            commit,
            name: entry.name.clone(),
            dependency: entry.checksum.ok(),
            kind,
        });
    }
    findings
}

/// 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 number of composefs images whose commit object is present.
    ///
    /// The run checks each of these images against the key of its commit.
    pub images_checked: usize,
    /// The composefs images that fail the image check, sorted by commit.
    pub image_errors: Vec<FsckImageError>,
    /// The composefs images whose commit object is absent, sorted.
    ///
    /// Such an image is not an error. The next prune removes it.
    pub orphan_images: Vec<Checksum>,
    /// The dependencies that are absent, partial, or defective, sorted by
    /// the commit that names them, then in the stored order of its field 2.
    ///
    /// [`Repo::fsck`] states the check under "Dependencies".
    pub dependency_errors: Vec<FsckDependencyError>,
}

impl FsckReport {
    /// Returns `true` if the repository passed with no finding.
    ///
    /// A pass has no faulty object, no faulty composefs image, no faulty
    /// dependency, no condition that ended the run, and no commit that the
    /// run skipped as already partial. A composefs image with no commit does
    /// not stop a pass.
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
            && self.image_errors.is_empty()
            && self.dependency_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: Vec<Checksum>,
    /// The objects that this run unlinked.
    deleted: HashSet<ObjectName>,
    /// The commits that this run tombstoned.
    tombstoned: Vec<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 number of composefs images that the image check read.
    images_checked: usize,
    /// The findings of the image check.
    image_errors: Vec<FsckImageError>,
    /// The composefs images with no commit object.
    orphan_images: Vec<Checksum>,
    /// The commits that reach an absent or a deleted object, also when the
    /// run marks no commit.
    incomplete: HashSet<Checksum>,
    /// The findings of the dependency check, in the order of the run.
    dependency_errors: Vec<FsckDependencyError>,
}

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(),
            )
        });
        self.marked_partial.sort();
        let mut deleted: Vec<ObjectName> = self.deleted.into_iter().collect();
        deleted.sort_by_key(|name| (name.checksum, name.ty as u32));
        self.tombstoned.sort();
        self.image_errors.sort_by_key(|e| e.commit);
        self.orphan_images.sort();
        FsckReport {
            reached,
            commits_checked: self.verified.len(),
            commits_partial: self.commits_partial,
            objects_checked,
            errors: self.errors,
            marked_partial: self.marked_partial,
            deleted,
            tombstoned: self.tombstoned,
            failure,
            images_checked: self.images_checked,
            image_errors: self.image_errors,
            orphan_images: self.orphan_images,
            dependency_errors: self.dependency_errors,
        }
    }
}

/// 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.
    /// 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.
    /// 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_dependencies`](FsckOptions::mark_dependencies), and
    /// [`delete`](FsckOptions::delete) state the actions on a finding.
    ///
    /// # Dependencies
    ///
    /// 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::dependency_errors`] holds one [`FsckDependencyError`]
    /// for each entry, in the stored order:
    ///
    /// - [`Defective`](FsckDependencyErrorKind::Defective) if the entry has
    ///   an empty name or a checksum that is not 32 bytes.
    /// - [`Absent`](FsckDependencyErrorKind::Absent) if the object store does
    ///   not hold the commit at the start of the run, or if the run deleted
    ///   it.
    /// - [`Partial`](FsckDependencyErrorKind::Partial) if the commit has a
    ///   `.commitpartial` marker at the start of the run, or if it reaches an
    ///   absent or a deleted object.
    /// - [`Defective`](FsckDependencyErrorKind::Defective) if the field 2 of
    ///   the commit is not empty.
    ///
    /// The first rule that applies gives the finding of an entry. An entry
    /// that no rule applies to gives no finding. 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_dependencies`](FsckOptions::mark_dependencies) are set, the run
    /// marks each commit with an `Absent` or a `Partial` finding as partial.
    /// Such a mark does not change the other findings of the run.
    ///
    /// A run that ends early does not reach this check.
    ///
    /// # Composefs images
    ///
    /// After the four phases, the run checks each composefs image object
    /// (`.cfs`) in the store. It checks the image of each commit object that
    /// is present, the partial commits included. It streams the image through
    /// the fs-verity hasher and compares the digest with the key
    /// `ostree.composefs.digest.v0` of the commit.
    ///
    /// - [`FsckReport::image_errors`] holds each image whose digest is not the
    ///   key, each image that does not read, and each image whose commit has
    ///   no key or a malformed key. If [`delete`](FsckOptions::delete) is set,
    ///   the run unlinks each of these images and names it in
    ///   [`FsckReport::deleted`]. An image finding marks no commit as partial.
    /// - [`FsckReport::image_errors`] also holds each image whose commit
    ///   object is present and does not load. The run does not unlink such an
    ///   image.
    /// - [`FsckReport::orphan_images`] holds each image whose commit object is
    ///   absent. Such an image is not an error.
    ///
    /// The run reads the key of a commit that phase 4 walked from the read of
    /// that walk, so it reads each of these commit objects once.
    ///
    /// 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, the dependency check, and the image 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 a dependency.
    ///
    /// 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. A commit that a ref names, or a dirtree, larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) also gives this
    ///   error.
    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?;

        // 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. The same listing pass gives the
        // composefs images.
        let (commits, images) = self.list_commits_and_images().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 image_keys = HashMap::new();
        let mut dependencies = Vec::new();
        let order = match self
            .fsck_collect_objects(&ctx.verified, &images, &mut image_keys, &mut dependencies)
            .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 dependencies, against the state after the actions above.
        self.fsck_check_dependencies(&commits, &dependencies, opts, &mut ctx)
            .await?;

        // The composefs images, against the commits that are still present.
        self.fsck_check_images(&commits, &images, image_keys, 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).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>> {
        for (name, commit) in targets {
            let commit = *commit;
            let bytes = match self.fsck_check_ref_target(name, commit, opts, 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.
    async fn fsck_check_ref_target(
        &self,
        display: &str,
        commit: Checksum,
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<std::result::Result<Option<Vec<u8>>, FsckFailure>> {
        let bytes = match self.load_object_bytes(ObjectType::Commit, &commit).await {
            Ok(bytes) => bytes,
            Err(Error::ObjectNotFound { .. }) => {
                return Ok(Err(FsckFailure::RefTarget {
                    ref_name: display.to_owned(),
                    commit,
                    removed: false,
                }));
            }
            Err(e) => return Err(e),
        };
        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).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>> {
        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, 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)),
        );
        let by_pair = index_first(collection_refs.iter().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 in `images`, the sorted list of the commits that have
    /// a composefs image, the function adds the key
    /// `ostree.composefs.digest.v0` of the commit to `image_keys`, if the key
    /// reads. The image check then does not read the commit again.
    ///
    /// For each commit whose field 2 is not empty, the function adds the
    /// commit and the entries of field 2 to `dependencies`, in the order of
    /// `commits`.
    async fn fsck_collect_objects(
        &self,
        commits: &[Checksum],
        images: &[Checksum],
        image_keys: &mut HashMap<Checksum, Option<[u8; 32]>>,
        dependencies: &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 images.binary_search(commit).is_ok()
                && let Ok(key) = crate::composefs::recorded_digest(&parsed)
            {
                image_keys.insert(*commit, key);
            }
            if !parsed.related.is_empty() {
                dependencies.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.
    async fn fsck_hash_content(
        &self,
        name: ObjectName,
        buf: &mut [u8],
        ctx: &mut Ctx,
    ) -> Result<()> {
        let checksum = name.checksum;
        let file = match self.load_file(&checksum).await {
            Ok(file) => file,
            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().await?;
        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.
    ///
    /// 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);
                }
            }
        }
        for object in doomed {
            if !ctx.deleted.insert(object) {
                continue;
            }
            self.fsck_unlink_object(object).await?;
        }
        if opts.mark_partial {
            for commit in incomplete {
                self.mark_commit_partial(&commit).await?;
                ctx.marked_partial.push(commit);
            }
        }
        Ok(())
    }

    /// Checks the dependencies of each verified commit that the run did not
    /// delete, and under `mark_partial` and `mark_dependencies` marks each
    /// commit with an absent or a partial dependency as partial.
    ///
    /// `all` is the commit listing of the start of the run. `dependencies`
    /// holds each verified commit whose field 2 is not empty, with its
    /// entries, sorted by commit. A dependency in that list has dependencies
    /// of its own. The function reads no object.
    async fn fsck_check_dependencies(
        &self,
        all: &[Checksum],
        dependencies: &[(Checksum, Vec<RelatedEntry>)],
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<()> {
        let deleted = |commit: &Checksum| {
            ctx.deleted
                .contains(&ObjectName::new(*commit, ObjectType::Commit))
        };
        let nested = |commit: &Checksum| {
            dependencies
                .binary_search_by_key(commit, |(naming, _)| *naming)
                .is_ok()
        };
        let mut findings = Vec::new();
        for (commit, entries) in dependencies {
            if deleted(commit) {
                continue;
            }
            findings.extend(dependency_findings(
                *commit,
                entries,
                |dependency| all.binary_search(dependency).is_err() || deleted(dependency),
                |dependency| {
                    ctx.verified.binary_search(dependency).is_err()
                        || ctx.incomplete.contains(dependency)
                },
                nested,
            ));
        }
        if opts.mark_partial && opts.mark_dependencies {
            let mut marked = HashSet::new();
            for finding in &findings {
                let commit = finding.commit;
                if matches!(finding.kind, FsckDependencyErrorKind::Defective(_))
                    || ctx.incomplete.contains(&commit)
                    || !marked.insert(commit)
                {
                    continue;
                }
                self.mark_commit_partial(&commit).await?;
                ctx.marked_partial.push(commit);
            }
        }
        ctx.dependency_errors = findings;
        Ok(())
    }

    /// Checks each composefs image against the key of its commit.
    ///
    /// `all` is the commit listing of the start of the run, and `images` is
    /// the image listing of the same pass. A commit that the run unlinked is
    /// absent, so its image is an orphan. `image_keys` holds the keys that
    /// phase 4 read. The function reads each other commit of an image.
    async fn fsck_check_images(
        &self,
        all: &[Checksum],
        images: &[Checksum],
        mut image_keys: HashMap<Checksum, Option<[u8; 32]>>,
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<()> {
        if images.is_empty() {
            return Ok(());
        }
        let present: HashSet<Checksum> = all
            .iter()
            .copied()
            .filter(|c| {
                !ctx.deleted
                    .contains(&ObjectName::new(*c, ObjectType::Commit))
            })
            .collect();
        for &commit in images {
            if !present.contains(&commit) {
                ctx.orphan_images.push(commit);
                continue;
            }
            let key = match image_keys.remove(&commit) {
                Some(key) => ImageKey::Read(key),
                None => self.fsck_image_key(&commit).await,
            };
            let finding = match key {
                // A concurrent prune removed the commit before its image.
                ImageKey::CommitAbsent => {
                    ctx.orphan_images.push(commit);
                    continue;
                }
                ImageKey::Fault(kind) => Some(kind),
                ImageKey::Read(None) => Some(FsckImageErrorKind::NoKey),
                ImageKey::Read(Some(expected)) => self.fsck_image_finding(&commit, expected).await,
            };
            ctx.images_checked += 1;
            let Some(kind) = finding else {
                continue;
            };
            let commit_fault = matches!(kind, FsckImageErrorKind::CommitUnreadable(_));
            ctx.image_errors.push(FsckImageError { commit, kind });
            let name = ObjectName::new(commit, ObjectType::ComposefsImage);
            if opts.delete && !commit_fault && ctx.deleted.insert(name) {
                self.fsck_unlink_object(name).await?;
            }
        }
        Ok(())
    }

    /// Reads the key `ostree.composefs.digest.v0` of the commit of a
    /// composefs image.
    async fn fsck_image_key(&self, commit: &Checksum) -> ImageKey {
        let bytes = match self.load_object_bytes(ObjectType::Commit, commit).await {
            Ok(bytes) => bytes,
            Err(Error::ObjectNotFound { .. }) => return ImageKey::CommitAbsent,
            Err(e) => {
                return ImageKey::Fault(FsckImageErrorKind::CommitUnreadable(format!(
                    "the commit does not load: {e}"
                )));
            }
        };
        let commit_obj = match Commit::parse(&bytes) {
            Ok(parsed) => parsed,
            Err(e) => {
                return ImageKey::Fault(FsckImageErrorKind::BadKey(format!(
                    "the commit does not parse: {e}"
                )));
            }
        };
        match crate::composefs::recorded_digest(&commit_obj) {
            Ok(key) => ImageKey::Read(key),
            Err(e) => ImageKey::Fault(FsckImageErrorKind::BadKey(e.to_string())),
        }
    }

    /// Returns the finding on the composefs image of `commit` against the
    /// digest `expected` that the commit records, or `None` if the image is
    /// valid or absent.
    async fn fsck_image_finding(
        &self,
        commit: &Checksum,
        expected: [u8; 32],
    ) -> Option<FsckImageErrorKind> {
        match self.stored_image_digest(commit).await {
            Ok(Some(actual)) if actual == expected => None,
            Ok(Some(actual)) => Some(FsckImageErrorKind::Mismatch { expected, actual }),
            // A concurrent prune removed the image.
            Ok(None) => None,
            Err(e) => Some(FsckImageErrorKind::ImageUnreadable(format!(
                "the image does not read: {e}"
            ))),
        }
    }

    /// 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 || {
                let tmp_fd = crate::staging::open_tmp_dir(repo.repo_fd(), mode)?;
                write_tombstone(tmp_fd.as_fd(), repo.objects_fd(), &commit, mode, fsync)
            })
            .await?;
            self.fsck_unlink_object(ObjectName::new(commit, ObjectType::Commit))
                .await?;
            ctx.tombstoned.push(commit);
        }
        Ok(())
    }

    /// Unlinks one loose object. An absent file counts as a success.
    async fn fsck_unlink_object(&self, name: ObjectName) -> Result<()> {
        let repo = self.clone();
        let path = name.loose_path(repo.mode());
        ostrya_rt::unblock(move || {
            match rustix::fs::unlinkat(repo.objects_fd(), path.as_str(), AtFlags::empty()) {
                Ok(()) | Err(Errno::NOENT) => Ok(()),
                Err(e) => Err(Error::Io(e.into())),
            }
        })
        .await
    }

    /// Writes the `state/<commit>.commitpartial` marker of a commit.
    async fn mark_commit_partial(&self, commit: &Checksum) -> Result<()> {
        let path = crate::pull::partial_path(commit);
        let repo = self.clone();
        ostrya_rt::unblock(move || write_partial_marker(repo.repo_fd(), &path, repo.mode())).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
}

/// 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 bytes = match repo.load_object_bytes(ObjectType::DirTree, &dirtree).await {
            Ok(bytes) => bytes,
            Err(Error::ObjectNotFound { .. }) => return Ok(Err(dirtree)),
            Err(e) => return Err(e),
        };
        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(()))
    })
}

/// Creates or truncates a `.commitpartial` marker that holds the one state
/// byte of the `ostree` command.
///
/// In a `bare-user-shared` repository, a marker that this call creates gets
/// the mode [`perm::SHARED_FILE_MODE`]. For this reason the create attempt
/// has `O_EXCL`, which separates the arm that made the file from the arm that
/// found one. A marker that another member of the repository group owns keeps
/// its mode, and the call truncates it in place.
///
/// The second open also has `O_CREAT`. A concurrent pull or prune removes the
/// marker of a commit that it completes or deletes, and the name can be free
/// again when this call reaches it.
fn write_partial_marker(repo_fd: BorrowedFd<'_>, path: &str, repo_mode: RepoMode) -> Result<()> {
    let mode = Mode::from_raw_mode(crate::pull::PARTIAL_MARKER_MODE);
    let fd = match rustix::fs::openat(
        repo_fd,
        path,
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
        mode,
    ) {
        Ok(fd) => {
            perm::force_created_mode(&fd, repo_mode, perm::SHARED_FILE_MODE)?;
            fd
        }
        Err(Errno::EXIST) => rustix::fs::openat(
            repo_fd,
            path,
            OFlags::WRONLY | OFlags::CREATE | OFlags::TRUNC | OFlags::CLOEXEC,
            mode,
        )?,
        Err(e) => return Err(e.into()),
    };
    std::fs::File::from(fd)
        .write_all(&[PARTIAL_STATE_BYTE])
        .map_err(Error::Io)
}