ostrya 0.19.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
//! Removal of unreachable objects.
//!
//! [`Repo::prune`] walks from a set of roots and removes each loose object
//! that the walk does not reach. The walk also keeps the related commits of
//! each commit that it reaches: the attachments and the supplements. If
//! the two ostrya extensions of [`PruneOptions`] keep their defaults and no
//! reached commit names a related commit, a run deletes the same objects as
//! the `ostree prune` command, as observed. The run also reads the
//! `.commitmeta` of each commit that the walk reaches. A `.commitmeta` that
//! holds the key `ostrya.related` and does not parse fails the run.
//!
//! - [`PruneOptions`] sets the roots, the bounds, and the dry run.
//! - [`PruneStats`] holds the counts of a run, the refs that it deleted, and
//!   the warnings of the defective related values that it read.
//! - [`WeakRefFilter`] marks refs weak, so that a run can delete them. It
//!   gets each ref that it classifies as a [`Ref`].

use std::collections::{BTreeSet, HashMap, HashSet};
use std::ops::ControlFlow;
use std::sync::Arc;

use ostrya_core::{Checksum, ObjectName, ObjectType, Ref, RepoMode, loose_path};
use rustix::fs::FileType;
use rustix::io::Errno;

use crate::config::repo;
use crate::error::{Error, Result};
use crate::lock::LockKind;
use crate::related::RelationWarning;
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, RepoDir, RepoLayout};
use crate::tombstone::write_tombstone;
use crate::traverse::{ListedRef, ParentBound, RefSpace, WeakBounds};

/// The callback of a [`WeakRefFilter`]: a verdict on one ref.
///
/// The arguments are the ref and the commit that it resolves to. If the
/// callback returns `true`, the ref is strong: it roots the walk under the
/// bound of the ref. If the callback returns `false`, the ref is weak and
/// roots nothing. A weak ref survives if the walk reaches its commit
/// over some other edge. Otherwise the run deletes it.
pub type WeakRefFilterFn = Arc<dyn Fn(&Ref, &Checksum) -> bool + Send + Sync>;

/// The ref classifier of a prune, unset by default.
///
/// An unset filter marks every ref strong, so a prune with no filter deletes no
/// ref. The filter gets each ref that it classifies as a [`Ref`]. A ref that
/// gets no [`Ref`] is never offered to the filter and is always strong.
/// [`PruneOptions::weak_ref_filter`] states which refs the filter classifies
/// and how a run uses the verdicts.
///
/// The callback is in an [`Arc`], so a caller can share one classifier across
/// more than one [`PruneOptions`]. A classifier that keeps state must supply
/// its own interior mutability.
///
/// # Callback rules
///
/// The callback runs on the executor thread while the run holds the repository
/// lock exclusive, so it must call no [`Repo`] method:
///
/// - A call to [`Repo::transaction`] inside it waits until `[core]
///   lock-timeout-secs` passes and then fails. If the value is `-1`, the wait
///   has no end.
/// - A `block_on` call into the async runtime inside it re-enters the runtime.
///
/// The result of the callback must depend only on its two arguments and on the
/// state that the caller captured before the call.
///
/// If a classifier moves a ref as a side effect of its call, the hazard belongs
/// to the caller. The compare-and-delete guard stops the run from unlinking a
/// ref that moved. The run walks once, so the objects under the new commit of
/// that ref can still go.
#[derive(Clone, Default)]
pub struct WeakRefFilter(Option<WeakRefFilterFn>);

impl WeakRefFilter {
    /// Creates a filter that calls `f` for each ref that it classifies.
    ///
    /// # Examples
    ///
    /// A filter that marks each ref of the collection `org.example.Cache`
    /// weak. Each other ref stays strong.
    ///
    /// ```
    /// use ostrya::{PruneOptions, Ref, WeakRefFilter};
    ///
    /// let filter = WeakRefFilter::new(|r, _| match r {
    ///     Ref::Collection { id, .. } => id != "org.example.Cache",
    ///     _ => true,
    /// });
    /// let opts = PruneOptions {
    ///     refs_only: true,
    ///     weak_ref_filter: filter,
    ///     ..PruneOptions::default()
    /// };
    /// # let _ = opts;
    /// ```
    pub fn new<F>(f: F) -> WeakRefFilter
    where
        F: Fn(&Ref, &Checksum) -> bool + Send + Sync + 'static,
    {
        WeakRefFilter(Some(Arc::new(f)))
    }

    /// Creates a filter from a callback that the caller already holds.
    ///
    /// The caller can share the callback with another [`PruneOptions`].
    pub fn from_fn(f: WeakRefFilterFn) -> WeakRefFilter {
        WeakRefFilter(Some(f))
    }

    /// Returns `true` if the filter holds a callback.
    pub(crate) fn is_set(&self) -> bool {
        self.0.is_some()
    }

    /// Returns `true` if the ref is strong. An unset filter returns `true` for
    /// each ref.
    pub(crate) fn is_strong(&self, r: &Ref, target: &Checksum) -> bool {
        match &self.0 {
            Some(f) => f(r, target),
            None => true,
        }
    }
}

impl std::fmt::Debug for WeakRefFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            Some(_) => f.write_str("WeakRefFilter(set)"),
            None => f.write_str("WeakRefFilter(unset)"),
        }
    }
}

/// The options of [`Repo::prune`].
///
/// [`PruneOptions::default`] gives a run that keeps each object that a commit
/// in the store reaches. [`Repo::prune`] states how the options set the roots
/// and the bounds of the walk.
///
/// # Extensions
///
/// Two options are ostrya extensions. The `ostree` command has no
/// counterpart for them:
///
/// - [`traverse_parent`](PruneOptions::traverse_parent): the switch that makes
///   the `parent` of a commit reachable from it.
/// - [`weak_ref_filter`](PruneOptions::weak_ref_filter): the classifier that
///   marks each ref strong or weak.
///
/// The default of each one is the behavior without the option. A prune that
/// keeps both at their defaults deletes the same objects as the `ostree`
/// command, if no commit that the run reaches names a related commit. The run
/// also reads the `.commitmeta` of each commit that it reaches. A
/// `.commitmeta` that holds the key `ostrya.related` and does not parse fails
/// the run ([`Repo::prune`], "Related commits").
///
/// The roots on the related commits of a commit are also an ostrya
/// extension, with no option. [`Repo::prune`], "Related commits", states
/// them.
#[derive(Debug, Clone)]
pub struct PruneOptions {
    /// The switch that roots the walk on the refs alone.
    ///
    /// If it is `false` (the default), each commit object in the store is also
    /// a root. A commit that no ref names then survives with its objects. If
    /// it is `true`, only the commits that a ref reaches survive.
    pub refs_only: bool,
    /// The number of parent commits that the run keeps for each ref.
    ///
    /// - `-1` (the default) keeps the whole ancestry.
    /// - `0` keeps only the commit that the ref names.
    /// - `N` keeps `N` parents.
    /// - Each other negative value keeps only the commit that the ref names.
    pub depth: i32,
    /// The switch for a dry run that computes the statistics and deletes
    /// nothing.
    ///
    /// The run also keeps the commit that
    /// [`delete_commit`](PruneOptions::delete_commit) names.
    ///
    /// The dry run checks the weak refs to delete as a real run does. If the
    /// path of such a ref passes through an alias, the dry run fails with
    /// [`Error::RefNotWritable`].
    pub no_prune: bool,
    /// A commit object that the run removes before the sweep.
    ///
    /// No ref can name the commit. The walk reads the commit as absent, so the
    /// sweep removes each object that only this commit reached. The run unlinks
    /// the commit object after the walk succeeds. The counts cover only the
    /// swept objects, as the counts of the `ostree` command do.
    ///
    /// The run can delete a commit that the related field of another commit
    /// names, as it can delete the parent of a commit. The entry then names a
    /// commit that the repository does not hold, and a later run reads
    /// nothing below it. The run also reads no related value of the deleted commit,
    /// so the commits that only it named are swept.
    ///
    /// If [`no_prune`](PruneOptions::no_prune) is set, the commit stays, and
    /// the statistics report the sweep that its removal causes. The
    /// `ostree` command refuses the two options together, and so does the
    /// `ostrya` CLI.
    pub delete_commit: Option<Checksum>,
    /// The oldest commit time that the run keeps, in seconds since the Unix
    /// epoch.
    ///
    /// If it is `Some`, the run roots the walk on the refs alone, as
    /// [`refs_only`](PruneOptions::refs_only) does. A commit that the walk
    /// reaches over a `parent` edge survives if its own timestamp is at or
    /// after the bound. The commit that a ref names survives whatever its
    /// timestamp.
    ///
    /// The time bound replaces [`depth`](PruneOptions::depth) for each branch
    /// that [`retain_branch_depth`](PruneOptions::retain_branch_depth) leaves
    /// at the global value. A ref that
    /// [`weak_ref_filter`](PruneOptions::weak_ref_filter) marks weak gets no
    /// guarantee, because it roots the walk under no bound.
    pub keep_younger_than: Option<u64>,
    /// The branches that the run prunes.
    ///
    /// Each value names one ref: a local ref, a remote ref, or a collection
    /// ref. A collection ref of the `[core] collection-id` of the repository
    /// names the local ref of the same name. An empty list prunes every
    /// branch.
    ///
    /// A non-empty list roots the walk on the refs alone. The run keeps in full
    /// each branch that neither this list nor
    /// [`retain_branch_depth`](PruneOptions::retain_branch_depth) names.
    ///
    /// Each run reads each value as a ref from the ref store, as
    /// [`resolve_ref_tip`](Repo::resolve_ref_tip) does. The run does not read
    /// a value as a full checksum, as an abbreviated checksum, or with a `^`
    /// suffix. A [`static_deltas_only`](PruneOptions::static_deltas_only) run
    /// reads the values too. The read comes before the run takes the lock, so
    /// a value that names no ref fails the prune, and the run removes nothing.
    /// A value selects the ref that the run reads as an equal [`Ref`].
    /// [`weak_ref_filter`](PruneOptions::weak_ref_filter) states which refs
    /// the run reads as a [`Ref`]. A ref that the ref listing does not give,
    /// for example through a symlink that the port does not write, selects no
    /// branch. If no value selects a branch, the run keeps every branch in
    /// full. No value
    /// selects a ref under `refs/mirrors/ID/` of the `[core] collection-id`
    /// of the repository, so the run keeps such a ref in full under a
    /// non-empty list.
    ///
    /// A ref that [`weak_ref_filter`](PruneOptions::weak_ref_filter) marks weak
    /// gets no retention from this list, because it roots the walk under no
    /// bound.
    pub only_branch: Vec<Ref>,
    /// Depths for single branches, each in place of
    /// [`depth`](PruneOptions::depth) for its branch.
    ///
    /// A non-empty list roots the walk on the refs alone, as
    /// [`refs_only`](PruneOptions::refs_only) does. The run reads the entries
    /// in order, and the last entry that names a branch decides its depth. An
    /// entry with the depth `0` leaves the branch at the global
    /// [`depth`](PruneOptions::depth) and still counts as a name.
    ///
    /// Each entry names one ref as a value of
    /// [`only_branch`](PruneOptions::only_branch) does, and selects it by the
    /// same rule. [`only_branch`](PruneOptions::only_branch) never keeps in
    /// full a branch that this list names. No entry names a ref under
    /// `refs/mirrors/ID/` of the `[core] collection-id` of the repository.
    pub retain_branch_depth: Vec<(Ref, i32)>,
    /// The switch that deletes commit objects alone.
    ///
    /// The objects that a deleted commit reached stay in place, and the
    /// statistics count commit objects alone.
    pub commit_only: bool,
    /// The switch that deletes only the static deltas that target
    /// [`delete_commit`](PruneOptions::delete_commit).
    ///
    /// The run leaves every loose object in place. The switch needs
    /// [`delete_commit`](PruneOptions::delete_commit). If `delete_commit` is
    /// `None`, the prune fails with [`Error::InvalidFormat`].
    pub static_deltas_only: bool,
    /// The switch that makes the `parent` of a commit reachable from it.
    ///
    /// The default is `true`, which is the behavior of the `ostree` command.
    /// [`depth`](PruneOptions::depth) bounds the edge. If it is `false`, the
    /// ancestry of a commit survives only where something else names it. An
    /// application that tracks its own roots through the related commits uses
    /// this setting.
    ///
    /// The switch acts on the `parent` edge alone. If it is `false`, the run
    /// still keeps the related commits of each reached commit
    /// ([`Repo::prune`], "Related commits"), and a related commit keeps no
    /// parent.
    ///
    /// This field is an ostrya extension. The repository config has no key for
    /// it, so a prune that the `ostrya` CLI runs always follows the `parent`
    /// edge.
    pub traverse_parent: bool,
    /// The classifier that marks each ref strong or weak.
    ///
    /// The default is unset, which marks every ref strong and deletes no ref.
    /// A set filter needs [`refs_only`](PruneOptions::refs_only). If
    /// `refs_only` is `false`, the prune fails with [`Error::InvalidFormat`]
    /// before the run reads anything. This field is an ostrya extension.
    /// [`Repo::prune`] reads no config key for the filter.
    /// [`RepoConfig::gc_weak_references`](crate::RepoConfig::gc_weak_references)
    /// reads the list of weak refs that the `ostrya prune` command uses.
    ///
    /// The run reads a ref as a [`Ref`] by these rules, and the filter gets
    /// that [`Ref`] for each ref that it classifies:
    ///
    /// - [`Ref::Local`] for a ref under `refs/heads`, with its path in that
    ///   directory as the name. The path must pass the ref-name rule and hold
    ///   no `:`.
    /// - [`Ref::Remote`] for a ref under `refs/remotes`, with the remote and
    ///   the name of its `<remote>:<name>` refspec. The refspec must pass the
    ///   ref-name rule, and the first `/` of the path in `refs/remotes` must
    ///   be the first `:` of the refspec.
    /// - [`Ref::Collection`] for a ref under `refs/mirrors`. The part of the
    ///   path before its first `/` is the collection id, and the rest is the
    ///   name. The id must pass
    ///   [`is_collection_id`](crate::is_collection_id) and be at most 255
    ///   bytes, and the name must pass the ref-name rule. The id must not be
    ///   the `[core] collection-id` of the repository.
    ///
    /// Each other ref is strong, and the filter never sees it. Examples are a
    /// ref whose name fails the ref-name rule, a file directly under
    /// `refs/mirrors`, a ref under `refs/mirrors/ID/` of the
    /// `[core] collection-id` of the repository, and a remote ref whose
    /// refspec maps to a different file. The run reads `[core] collection-id`
    /// from the config that the handle read at the open.
    ///
    /// A repository can hold a directory of `refs/mirrors/` whose name fails
    /// the collection id rule above. A ref under that directory is strong,
    /// so a prune never deletes it. Remove such a ref by hand.
    ///
    /// A ref under `refs/mirrors/ID/` of the `[core] collection-id` of the
    /// repository is a strong ref with no name. The ref resolve, the
    /// collection ref listings, and the summary ignore it. No value of
    /// [`only_branch`](PruneOptions::only_branch) or
    /// [`retain_branch_depth`](PruneOptions::retain_branch_depth) selects
    /// it, so it takes the bound of a ref that no list names. The run never
    /// deletes it. Remove such a ref by hand.
    ///
    /// A strong ref roots the walk under the bound that
    /// [`retain_branch_depth`](PruneOptions::retain_branch_depth),
    /// [`only_branch`](PruneOptions::only_branch), and
    /// [`depth`](PruneOptions::depth) give its [`Ref`]. A ref that gets no
    /// [`Ref`] takes the bound of a ref that no list names. A weak ref roots
    /// nothing. It survives if the walk reaches its commit over some other
    /// edge:
    ///
    /// - An arrival over a `parent` edge gives the commit the bound of the weak
    ///   ref. That bound replaces the bound that the edge left. The
    ///   target of a strong ref gets the same rule.
    /// - An arrival over another edge carries a bound of its own. The commit
    ///   expands under that bound and under the bound of the weak ref.
    ///
    /// The run deletes each weak ref that the walk did not reach, and names it
    /// in [`PruneStats::deleted_refs`]. The run leaves an emptied directory
    /// under `refs/` in place, for example `refs/mirrors/ID/`. If the path of
    /// such a ref passes through an alias, the run fails with
    /// [`Error::RefNotWritable`] and deletes no ref and no object. A
    /// [`no_prune`](PruneOptions::no_prune) dry run fails in the same way.
    ///
    /// The branch selection has nothing to select for a weak ref, because a
    /// weak ref roots nothing. The filter also classifies a weak ref outside an
    /// [`only_branch`](PruneOptions::only_branch) selection. If the walk does
    /// not reach its commit, the run deletes the ref and sweeps its objects.
    /// [`keep_younger_than`](PruneOptions::keep_younger_than) keeps only the
    /// target of a strong ref. The run deletes a weak ref that the walk does
    /// not reach, whatever the timestamp of its commit.
    pub weak_ref_filter: WeakRefFilter,
}

impl Default for PruneOptions {
    fn default() -> Self {
        PruneOptions {
            refs_only: false,
            depth: -1,
            no_prune: false,
            delete_commit: None,
            keep_younger_than: None,
            only_branch: Vec::new(),
            retain_branch_depth: Vec::new(),
            commit_only: false,
            static_deltas_only: false,
            traverse_parent: true,
            weak_ref_filter: WeakRefFilter::default(),
        }
    }
}

impl PruneOptions {
    /// Creates the default options.
    ///
    /// A run with these options keeps each object that a commit in the store
    /// reaches. In a repository with no unreachable objects, it removes
    /// nothing.
    pub fn new() -> PruneOptions {
        PruneOptions::default()
    }

    /// Returns the bound of a branch that no `retain_branch_depth` entry names
    /// and that `only_branch` leaves at the global setting.
    pub(crate) fn global_bound(&self) -> ParentBound {
        match self.keep_younger_than {
            Some(since) => ParentBound::Since(since),
            None => ParentBound::depth(self.depth),
        }
    }

    /// Returns `true` if the options root the walk of [`Repo::prune`] on the
    /// refs alone.
    ///
    /// The method returns `true` if one or more of these options is set:
    ///
    /// - [`refs_only`](PruneOptions::refs_only) if it is `true`.
    /// - [`keep_younger_than`](PruneOptions::keep_younger_than) if it is
    ///   `Some`.
    /// - [`only_branch`](PruneOptions::only_branch) if it is not empty.
    /// - [`retain_branch_depth`](PruneOptions::retain_branch_depth) if it is
    ///   not empty.
    ///
    /// If it returns `false`, each commit object in the store is also a root.
    /// [`Repo::prune`], "Roots", states the roots of the walk.
    ///
    /// A set [`weak_ref_filter`](PruneOptions::weak_ref_filter) needs
    /// [`refs_only`](PruneOptions::refs_only) set to `true`, also if this
    /// method returns `true`. If the filter is set and `refs_only` is `false`,
    /// [`Repo::prune`] fails with [`Error::InvalidFormat`]. If this method
    /// returns `true`, the change of `refs_only` to `true` changes no root.
    ///
    /// # Examples
    ///
    /// The function `add_filter` adds a weak ref filter only if the options
    /// root the walk on the refs alone. It sets `refs_only` to `true` with the
    /// filter, so the roots of the walk do not change. A time bound roots the
    /// walk on the refs alone, so the function adds the filter. The default
    /// options root each commit in the store, so the function adds no filter.
    ///
    /// ```
    /// use ostrya::{PruneOptions, Ref, WeakRefFilter};
    ///
    /// fn add_filter(opts: &mut PruneOptions) -> bool {
    ///     if !opts.roots_on_refs_alone() {
    ///         return false;
    ///     }
    ///     opts.refs_only = true;
    ///     opts.weak_ref_filter =
    ///         WeakRefFilter::new(|r, _| !matches!(r, Ref::Collection { .. }));
    ///     true
    /// }
    ///
    /// let mut bounded = PruneOptions {
    ///     keep_younger_than: Some(1_700_000_000),
    ///     ..PruneOptions::default()
    /// };
    /// assert!(add_filter(&mut bounded));
    /// assert!(bounded.refs_only);
    ///
    /// let mut default = PruneOptions::default();
    /// assert!(!add_filter(&mut default));
    /// assert!(!default.refs_only);
    /// ```
    pub fn roots_on_refs_alone(&self) -> bool {
        // The pattern names each field. A new field then fails to compile
        // here until its author decides if the field roots the walk on the
        // refs alone.
        let PruneOptions {
            refs_only,
            depth: _,
            no_prune: _,
            delete_commit: _,
            keep_younger_than,
            only_branch,
            retain_branch_depth,
            commit_only: _,
            static_deltas_only: _,
            traverse_parent: _,
            weak_ref_filter: _,
        } = self;
        *refs_only
            || keep_younger_than.is_some()
            || !only_branch.is_empty()
            || !retain_branch_depth.is_empty()
    }

    /// Returns the options with each collection ref of the own collection id
    /// `own` in the two branch lists read as the local ref of the same name.
    ///
    /// The run reads each listed ref as a canonical [`Ref`], so a value of the
    /// caller must be canonical to be equal to it.
    fn with_canonical_branches(&self, own: Option<&str>) -> PruneOptions {
        PruneOptions {
            only_branch: self
                .only_branch
                .iter()
                .map(|r| r.clone().canonical(own))
                .collect(),
            retain_branch_depth: self
                .retain_branch_depth
                .iter()
                .map(|(r, depth)| (r.clone().canonical(own), *depth))
                .collect(),
            ..self.clone()
        }
    }

    /// Returns the bound of the history of one listed ref, or of a listed ref
    /// that the run reads as no [`Ref`] if `r` is `None`.
    ///
    /// The last `retain_branch_depth` entry that names the ref decides the
    /// bound. If the depth of that entry is `0`, the ref takes the global
    /// bound. A ref that no entry names takes the global bound if
    /// `only_branch` is empty or names it. Otherwise the run keeps the ref in
    /// full. No entry names `None`.
    ///
    /// Both lists hold the values that the caller gave, so the run selects a
    /// ref by an equal value. The commit that a ref names has no effect on
    /// the selection.
    fn ref_bound(&self, r: Option<&Ref>) -> ParentBound {
        let Some(r) = r else {
            return self.unnamed_bound();
        };
        let entry = self
            .retain_branch_depth
            .iter()
            .rev()
            .find(|(branch, _)| branch == r)
            .map(|(_, depth)| *depth);
        match entry {
            Some(depth) if depth != 0 => ParentBound::depth(depth),
            entry => {
                let named = entry.is_some() || self.only_branch.contains(r);
                if named {
                    self.global_bound()
                } else {
                    self.unnamed_bound()
                }
            }
        }
    }

    /// Returns the bound of the history of a ref that no list names: the
    /// global bound if `only_branch` is empty, and else no bound, so the run
    /// keeps the ref in full.
    fn unnamed_bound(&self) -> ParentBound {
        if self.only_branch.is_empty() {
            self.global_bound()
        } else {
            ParentBound::Depth(-1)
        }
    }
}

/// Returns `true` if an object of this type is in the counts of a run.
///
/// Detached commit metadata and tombstone markers are outside both counts.
/// `commit_only` narrows the counts to commit objects, which is what the
/// `ostree` command reports. Static deltas are not loose objects, so they are
/// outside both counts.
pub(crate) fn counted(ty: ObjectType, commit_only: bool) -> bool {
    if commit_only {
        ty == ObjectType::Commit
    } else {
        !ty.is_commit_sidecar() && ty != ObjectType::TombstoneCommit
    }
}

/// The statistics of a [`Repo::prune`] run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PruneStats {
    /// The number of loose objects that the run considered.
    ///
    /// It is the total of the store after a
    /// [`delete_commit`](PruneOptions::delete_commit) removal. It leaves out
    /// detached commit metadata and tombstone markers. Static deltas are not
    /// loose objects, so they are outside it. If
    /// [`commit_only`](PruneOptions::commit_only) is set, it counts commit
    /// objects alone.
    pub total_objects: usize,
    /// The number of objects that the run deleted.
    ///
    /// If [`no_prune`](PruneOptions::no_prune) is set, it is the number that
    /// the run deletes without `no_prune`. It counts on the terms of
    /// [`total_objects`](PruneStats::total_objects). A `.commitmeta` removed
    /// with its commit or as an orphan is not in the number, and a static
    /// delta is not in it.
    pub pruned_objects: usize,
    /// The on-disk bytes of the objects that
    /// [`pruned_objects`](PruneStats::pruned_objects) counts.
    ///
    /// The bytes of a removed `.commitmeta` are not in the number.
    ///
    /// If [`no_prune`](PruneOptions::no_prune) is set, it is the number of
    /// bytes that the run frees without `no_prune`.
    pub freed_bytes: u64,
    /// The weak refs that the run deleted, sorted by the order of [`Ref`]:
    /// the local refs first, the remote refs next, and the collection refs
    /// last. The local refs are in the byte order of the name, the remote
    /// refs in the byte order of the remote and then of the name, and the
    /// collection refs in the byte order of the collection id and then of
    /// the name.
    ///
    /// Each entry is the [`Ref`] that
    /// [`weak_ref_filter`](PruneOptions::weak_ref_filter) got for the ref.
    ///
    /// If [`no_prune`](PruneOptions::no_prune) is set, the list names the refs
    /// that the run deletes without `no_prune`, and the run removes no ref. The
    /// list does not name a ref that the compare-and-delete guard skipped,
    /// because the run left that ref in place.
    ///
    /// A [`static_deltas_only`](PruneOptions::static_deltas_only) run returns
    /// before it lists the refs, so it classifies no ref. The list is then
    /// empty, whatever [`weak_ref_filter`](PruneOptions::weak_ref_filter)
    /// holds.
    ///
    /// If the run fails part way through the deletions, the refs that it
    /// already removed stay removed. The caller gets the error and no list.
    pub deleted_refs: Vec<Ref>,
    /// The defective related values that the walk read, as
    /// [`Repo::prune`], "Related commits", states.
    ///
    /// The list holds one warning for each defective entry and one for each
    /// defective `ostrya.related` value. It is sorted by commit and then by
    /// field, attachments first. The warnings of one field keep the order of
    /// its entries. A [`no_prune`](PruneOptions::no_prune) run gives the same
    /// list as a run without it. A
    /// [`static_deltas_only`](PruneOptions::static_deltas_only) run walks
    /// nothing, so its list is empty.
    pub warnings: Vec<RelationWarning>,
}

/// Returns the [`Ref`] that a run reads for a listed ref, or `None` if the
/// run reads the ref as no [`Ref`].
///
/// - A ref in `refs/heads` is [`Ref::Local`] if its listed name addresses the
///   file that the listing read.
/// - A ref in `refs/remotes` is [`Ref::Remote`] on the same condition. Its
///   listed name is its `<remote>:<name>` refspec.
/// - A ref in `refs/mirrors` is [`Ref::Collection`] if the part of its path
///   before the first `/` is a collection id that the ref store takes
///   ([`is_valid_collection_id`](ostrya_core::is_valid_collection_id)) and
///   the rest is a valid ref name. The listing gives a mirror ref no
///   addressability, so the call does not read it.
///
/// [`ref_relpath`](crate::refs::ref_relpath) with no own id maps each result
/// back to the file that the listing read.
fn listed_ref(space: RefSpace, mut name: String, addressable: bool) -> Option<Ref> {
    match space {
        RefSpace::Heads => addressable.then(|| Ref::local(name)),
        RefSpace::Remotes => {
            let colon = name.find(':').filter(|_| addressable)?;
            let ref_name = name.split_off(colon + 1);
            name.truncate(colon);
            Some(Ref::remote(name, ref_name))
        }
        RefSpace::Mirrors => {
            let (id, ref_name) = name.split_once('/')?;
            if !ostrya_core::is_valid_collection_id(id) || !ostrya_core::is_ref_name(ref_name) {
                return None;
            }
            let slash = id.len();
            let ref_name = name.split_off(slash + 1);
            name.truncate(slash);
            Some(Ref::collection(name, ref_name))
        }
    }
}

/// The settings that the blocking half of a prune applies to each object that
/// it removes.
#[derive(Debug, Clone, Copy)]
struct Sweep {
    /// The repository mode, which sets the loose path of each object.
    mode: RepoMode,
    /// The switch for a dry run: delete nothing and report what a real run
    /// frees.
    no_prune: bool,
    /// The switch that writes a `.tombstone-commit` for each removed commit.
    tombstones: bool,
    /// The switch that syncs each tombstone before its link into place. It
    /// also syncs the directories that the commit removals changed before the
    /// first content object goes, and the directories that the content
    /// removals changed at the end of the sweep.
    fsync: bool,
    /// The switch that counts commit objects alone.
    commit_only: bool,
}

/// Methods that remove unreachable objects.
impl Repo {
    /// Removes the objects that no root reaches and returns the statistics.
    ///
    /// The run walks from the roots, keeps each object that the walk reaches,
    /// and removes each other loose object. A kept commit keeps its detached
    /// metadata (`.commitmeta`). The run removes the detached metadata of each
    /// commit that it removes. It also removes each detached metadata whose
    /// commit is absent, if the walk does not reach the name of that commit.
    /// The walk reaches the name of an absent
    /// commit that a reached commit names as its parent within the bound, or
    /// as a related commit. [`PruneOptions`] sets the roots, the bounds, and
    /// the dry run.
    ///
    /// The run reads four keys of the repository config, in this order:
    ///
    /// 1. `[core] locking` and `[core] lock-timeout-secs`, when it takes the
    ///    repository lock.
    /// 2. `[core] tombstone-commits` and `[core] fsync`, during the run. A
    ///    [`static_deltas_only`](PruneOptions::static_deltas_only) run stops
    ///    before this step and reads neither key. Another run with
    ///    [`delete_commit`](PruneOptions::delete_commit) set writes tombstones
    ///    and does not read `[core] tombstone-commits`.
    ///
    /// The run also reads `[core] collection-id` from the config that the
    /// handle read at the open, to find the refs of `refs/mirrors/ID/` of
    /// that id. The options decide all other behavior.
    ///
    /// # Roots
    ///
    /// The commits that the refs name are always roots. These include the
    /// refs under `refs/mirrors/ID/` of the `[core] collection-id` of the
    /// repository, which the ref resolve, the collection ref listings, and
    /// the summary ignore. Such a ref is a strong ref with no name, as
    /// [`weak_ref_filter`](PruneOptions::weak_ref_filter) states.
    /// [`refs_only`](PruneOptions::refs_only) states when each other commit in
    /// the store is also a root. Each of these options roots the walk on the
    /// refs alone, as `refs_only` does:
    ///
    /// - [`keep_younger_than`](PruneOptions::keep_younger_than) if it is
    ///   `Some`.
    /// - [`only_branch`](PruneOptions::only_branch) if it is not empty.
    /// - [`retain_branch_depth`](PruneOptions::retain_branch_depth) if it is
    ///   not empty.
    ///
    /// The related commits of each commit that the walk reaches are also
    /// roots. "Related commits" states them.
    ///
    /// # Related commits
    ///
    /// A commit names its related commits in two fields:
    ///
    /// - Field 2 of the commit object holds the attachments
    ///   ([`CommitOptions::attachments`](crate::CommitOptions::attachments)).
    /// - The key `ostrya.related` of the detached metadata holds the
    ///   supplements ([`Repo::add_supplement`]). If the key occurs more than
    ///   one time, the run reads the first entry alone.
    ///
    /// The run reads both fields of each commit that the walk reaches, and
    /// walks each commit that they name as a root of its own. Such a commit
    /// gets the global bound of the run, [`depth`](PruneOptions::depth) or
    /// [`keep_younger_than`](PruneOptions::keep_younger_than), because the
    /// bound counts `parent` edges. The run reads the two fields of a related
    /// commit too, so it keeps the attachments of an attachment and the
    /// supplements of a supplement. A cycle of supplements ends the walk,
    /// because the walk reads the fields of each commit one time.
    ///
    /// A related entry that names a commit that the repository does not hold
    /// gives no error, and the walk reads nothing below it. The run keeps the
    /// name of that commit, as it keeps the name of an absent parent. So the
    /// run keeps the `.commitmeta` of that commit if the store holds it. A weak ref
    /// ([`weak_ref_filter`](PruneOptions::weak_ref_filter)) whose commit a
    /// related field names survives.
    ///
    /// A defective related value gives a warning in
    /// [`PruneStats::warnings`], and the run continues. A value is defective
    /// if an entry of either field has an empty name or a checksum that is
    /// not 32 bytes, or if the value of `ostrya.related` is not a variant of
    /// type `a(say)`. The defective entry or value roots nothing, and the
    /// other entries of the field root as usual. Entries that are not sorted,
    /// two entries with the same name, and an attachment with attachments of
    /// its own are not defective.
    ///
    /// The run reads the related values also if each commit in the store is
    /// a root, so it gives the same warnings.
    ///
    /// The run parses a `.commitmeta` only if its bytes hold the key
    /// `ostrya.related` and its terminating NUL. In a serialized `a{sv}`
    /// dict, the key of each entry is a NUL-terminated string at contiguous
    /// bytes, so a file that does not hold these bytes has no
    /// `ostrya.related` entry. The run parses no such file. So such a file
    /// that does not parse gives no error and no warning, and the run does
    /// not parse the signatures of a commit whose `.commitmeta` does not hold
    /// these bytes. A `.commitmeta` that holds the key and does not parse
    /// fails the prune before it deletes an object. The key can also be in a
    /// value of another entry, for example in a string. Then the run parses
    /// the file, and a file that does not parse fails the prune.
    ///
    /// A `.commitmeta` that is larger than
    /// [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) fails the prune, also
    /// if it does not hold the key. The open of a `.commitmeta` follows no
    /// symlink, in each open mode. A symlink at the `.commitmeta` or at its
    /// fan-out directory, and a `.commitmeta` that is not a regular file,
    /// fail the prune.
    ///
    /// # Bounds
    ///
    /// [`depth`](PruneOptions::depth),
    /// [`retain_branch_depth`](PruneOptions::retain_branch_depth), and
    /// [`keep_younger_than`](PruneOptions::keep_younger_than) bound the history
    /// of each ref. A bound belongs to the commit that a ref names, whatever
    /// path the walk took to that commit.
    ///
    /// The walk can arrive at the target of a ref over a `parent` edge. Then
    /// the walk drops the bound that it carried and continues under the bound
    /// of that ref. As a result, a branch cut short also cuts each history that
    /// runs through its head. If two refs name one commit, the walk expands the
    /// commit under each of the two bounds, and the commit keeps what either
    /// bound reaches.
    ///
    /// # Static deltas and markers
    ///
    /// A run removes each static delta whose target commit it deleted. It
    /// removes the whole delta directory and leaves the fanout parent
    /// directory in place. A delta whose source commit the run deleted stays.
    ///
    /// After the sweep, a run that is neither a
    /// [`no_prune`](PruneOptions::no_prune) dry run nor a
    /// [`static_deltas_only`](PruneOptions::static_deltas_only) run also
    /// removes these entries:
    ///
    /// - each static delta whose target commit is absent from the store.
    /// - each `state/<commit>.commitpartial` marker whose commit is absent.
    ///
    /// This pass removes the marker of each commit that the run removes. If a
    /// run stops part way through, it leaves these entries behind, and the
    /// next run removes them. The run holds the repository lock exclusive, so
    /// no pull stands between the write of a marker and the store of its
    /// commit. This pass is ostrya behavior. As observed, the `ostree`
    /// command unlinks the marker of each commit that it deletes, before the
    /// commit object.
    ///
    /// The pass lists `state/` one time. It unlinks each entry at the name of
    /// a marker whose commit is absent, also a symlink, whose target stays,
    /// and a FIFO. A directory, a name that is not UTF-8, and a name that is
    /// not a marker name in lowercase hex stay. If `[core] fsync` is `true`,
    /// the pass syncs `state/` one time after the last unlink.
    ///
    /// Each run, a dry run too, opens `state/` after the walk and before it
    /// removes anything. A symlink or an entry that is not a directory at
    /// `state` fails the run before it deletes a ref or an object. A
    /// repository with no `state/` has no marker to remove.
    ///
    /// Each delta sweep skips a delta name that does not decode and leaves that
    /// entry in place. This includes the sweep of a `static_deltas_only` run.
    ///
    /// # Sweep order
    ///
    /// The sweep removes the doomed commits first, and their content after
    /// them. For each commit, it writes the tombstone, unlinks the commit
    /// object, and then unlinks its detached metadata. Next, it removes each
    /// detached metadata whose commit is absent.
    ///
    /// If `[core] fsync` is `true`, the run syncs the `objects/` directories
    /// that these removals changed before it removes the first dirtree,
    /// dirmeta, or file object. As a result, a run that stops at an error or a
    /// crash leaves no commit object whose tree it started to remove. If
    /// `[core] fsync` is `false`, a crash gives no guarantee of the order in
    /// which the removals reach the disk.
    ///
    /// If `[core] fsync` is `true`, the run syncs each `objects/<xx>`
    /// directory from which it removed a dirtree, dirmeta, or file object one
    /// time at the end of the sweep. This sync comes before the pass that
    /// removes the static deltas and the markers.
    ///
    /// A [`delete_commit`](PruneOptions::delete_commit) run removes and syncs
    /// the named commit in the same way before the sweep.
    ///
    /// # Tombstones
    ///
    /// If [`delete_commit`](PruneOptions::delete_commit) is set or the
    /// repository config sets `[core] tombstone-commits`, the run writes a
    /// `.tombstone-commit` for each commit that it removes. The run never
    /// removes a tombstone-commit marker.
    ///
    /// # Lock
    ///
    /// The run holds the repository lock exclusive
    /// ([`LockKind`]) from start to end. This includes a
    /// [`no_prune`](PruneOptions::no_prune) dry run and a
    /// [`static_deltas_only`](PruneOptions::static_deltas_only) run. The run
    /// waits for each other holder, a held
    /// [`UpdateGuard`](crate::UpdateGuard) included. If the caller holds its
    /// own transaction open across the call, the run waits until `[core]
    /// lock-timeout-secs` passes and then fails. The refusals of the options
    /// come before the lock.
    ///
    /// If the repository config sets `[core] locking` to `false`, no lock
    /// excludes a concurrent writer. Another writer can store a commit after
    /// the run lists the store. The run reads that commit as absent, so it can
    /// remove the marker and the static delta of that commit.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if
    ///   [`static_deltas_only`](PruneOptions::static_deltas_only) is set and
    ///   [`delete_commit`](PruneOptions::delete_commit) is `None`.
    /// - [`Error::InvalidFormat`] if
    ///   [`weak_ref_filter`](PruneOptions::weak_ref_filter) is set and
    ///   [`refs_only`](PruneOptions::refs_only) is `false`.
    /// - [`Error::InvalidFormat`] if a ref names the commit that
    ///   [`delete_commit`](PruneOptions::delete_commit) names. The run checks
    ///   this before the walk and again before the unlink.
    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than `-1`,
    ///   or if a ref file holds bytes that are not UTF-8.
    /// - [`Error::Core`] if a `[core]` key that the run reads holds a value of
    ///   the wrong type.
    /// - [`Error::Core`] if a ref file holds no valid checksum.
    /// - [`Error::Core`] if a commit object does not parse, or if its detached
    ///   metadata holds the key `ostrya.related` and does not parse. The run
    ///   reads the detached metadata of each commit that the walk reaches.
    /// - [`Error::Core`] if a dirtree that the walk reads does not parse. A
    ///   run with [`commit_only`](PruneOptions::commit_only) reads no dirtree.
    /// - [`Error::LockTimeout`] if the wait for the lock passes `[core]
    ///   lock-timeout-secs`.
    /// - [`Error::RefNotFound`] if no ref has the name of a value of
    ///   [`only_branch`](PruneOptions::only_branch), for example a checksum.
    /// - [`Error::InvalidRefspec`] if a value of
    ///   [`only_branch`](PruneOptions::only_branch) fails [`Ref::validate`],
    ///   for example `main^`.
    /// - [`Error::InvalidFormat`] if `refs`, `refs/heads`, `refs/remotes`, or
    ///   `refs/mirrors` is a symlink. The ref listing fails before the run
    ///   deletes anything.
    /// - [`Error::RefNotWritable`] if the path of a weak ref to delete passes
    ///   through an alias: a symlink at a component above the ref that a
    ///   writer put there after the listing. The reason is `passes through an
    ///   alias`. The run checks each weak ref to delete before the first
    ///   unlink, so it then deletes no ref and no object. A
    ///   [`no_prune`](PruneOptions::no_prune) dry run runs the same check.
    /// - An error of [`resolve_ref_tip`](Repo::resolve_ref_tip) if the read
    ///   of a value of [`only_branch`](PruneOptions::only_branch) fails. Each
    ///   run, a [`static_deltas_only`](PruneOptions::static_deltas_only) run
    ///   too, reads the values before it takes the lock and removes anything.
    /// - [`Error::Io`] if a read, a write, or a removal on the file system
    ///   fails.
    /// - [`Error::InvalidFormat`] if a metadata object 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>`. The unlink of an object gives it for a symlink at
    ///   `objects/<xx>` too, and the run then stops.
    /// - [`Error::InvalidFormat`] if `state` is a symlink or is not a
    ///   directory. The run checks this after the walk and before it deletes
    ///   a ref or an object, and a dry run checks it too.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// use ostrya::{PruneOptions, Repo};
    ///
    /// let repo = Repo::open("/srv/repo".as_ref()).await?;
    /// let stats = repo.prune(&PruneOptions::default()).await?;
    /// println!(
    ///     "removed {} of {} objects, {} bytes",
    ///     stats.pruned_objects, stats.total_objects, stats.freed_bytes
    /// );
    /// # Ok(()) }
    /// ```
    pub async fn prune(&self, opts: &PruneOptions) -> Result<PruneStats> {
        let mode = self.mode();

        // The delta-only run needs the commit that it keys on. The run refuses
        // the pair before the lock, so a contended repository gives the same
        // refusal as a free one.
        if opts.static_deltas_only && opts.delete_commit.is_none() {
            return Err(Error::InvalidFormat(
                "static_deltas_only requires delete_commit".into(),
            ));
        }

        // The classifier decides which refs the run deletes, and a run that
        // roots every commit in the store deletes none of them. The run refuses
        // the pair before the lock, so a contended repository gives the same
        // refusal as a free one. The refusal also comes before every read, so
        // the run never calls the classifier.
        if opts.weak_ref_filter.is_set() && !opts.refs_only {
            return Err(Error::InvalidFormat(
                "weak_ref_filter requires refs_only".into(),
            ));
        }

        // The run reads each branch selection from the ref store before the
        // lock, as it refuses the pairs above, so a value that names no ref
        // fails each run, the delta-only run too. A checksum or a `^` suffix
        // names no ref. The run does not read the commit of the ref.
        for r in &opts.only_branch {
            if self.resolve_ref_tip(r).await?.is_none() {
                return Err(Error::RefNotFound(r.to_string()));
            }
        }

        let _lock = self.lock_repo(LockKind::Exclusive).await?;

        let Some(delta_target) = opts.delete_commit else {
            return self.prune_objects(opts, mode).await;
        };
        if opts.static_deltas_only {
            // The run removes the deltas of the named commit and nothing else.
            // So the counts report the store as it is, and the ref check that
            // guards a commit deletion does not apply.
            let commit_only = opts.commit_only;
            let total_objects = self
                .count_objects(move |ty| counted(ty, commit_only))
                .await?;
            if !opts.no_prune {
                let fsync = self.config().get::<repo::Fsync>()?;
                let root = self.root_dir().clone();
                ostrya_rt::unblock(move || {
                    crate::delta::prune_delta_dirs(&root, fsync, |to| *to == delta_target)
                })
                .await?;
            }
            return Ok(PruneStats {
                total_objects,
                pruned_objects: 0,
                freed_bytes: 0,
                // A delta-only run lists no ref, so it deletes none.
                deleted_refs: Vec::new(),
                // A delta-only run walks nothing, so it reads no related value.
                warnings: Vec::new(),
            });
        }
        self.prune_objects(opts, mode).await
    }

    /// Runs the object sweep: the walk, the deletions, and the removal of the
    /// static deltas that the deletions left with no target.
    async fn prune_objects(&self, opts: &PruneOptions, mode: RepoMode) -> Result<PruneStats> {
        // The run cannot delete a commit that a ref names. Refuse it here, so a
        // prune that cannot succeed fails before the walk. The unlink checks
        // again, because a writer that takes no repository lock can publish a
        // ref that names the commit while the walk runs.
        if let Some(commit) = opts.delete_commit {
            self.refuse_referenced_commit(&commit).await?;
        }

        // Assemble the roots: the target of each ref under the bound of its
        // branch. Unless the roots are the refs alone, each commit in the store
        // is also a root. The view of the store drops a commit named for
        // deletion here, and the run unlinks it after the walk succeeds. So it
        // roots nothing, and the sweep, which runs over this same view, does
        // not name it a second time.
        let named_refs = self.list_all_refs().await?;
        // The run reads each listed ref as a canonical `Ref`, so a value of a
        // branch list selects a ref by an equal value only in its canonical
        // form. A ref that the listing does not give, for example through a
        // symlink that the port does not write, selects nothing.
        let own = self.config().collection_id();
        let opts = &opts.with_canonical_branches(own);
        // Classify the ref space in one pass, so the strong roots and the weak
        // targets cannot disagree. A ref is weak if both hold:
        //
        // - `listed_ref` gives it a `Ref`. A ref in `refs/heads` or
        //   `refs/remotes` gets one if its listed name addresses the file that
        //   it was listed from. A ref in `refs/mirrors` gets one if its path
        //   splits into a valid collection id and a valid ref name.
        // - the classifier returns false for that `Ref`.
        //
        // Every other ref is strong and never reaches the classifier.
        //
        // A ref of `refs/mirrors/ID/` of the own collection id is a strong
        // ref with no name. No list selects it, so it takes the bound of a
        // name that no list names, and the run never deletes it.
        //
        // A weak target stays out of `ref_targets`: the walk needs a seed for
        // every checksum that set names, and a weak ref supplies none. The weak
        // targets go in `GcRoots::weak_roots`, and the walk seeds one on the
        // arrival that reaches it.
        //
        // If a strong ref and a weak ref name one commit, the commit enters
        // through the strong ref. So the commit is reachable, and the weak ref
        // survives.
        //
        // An unset classifier makes every ref strong, so the unset case tests
        // one boolean for each ref.
        let filtering = opts.weak_ref_filter.is_set();
        let mut roots: Vec<(Checksum, ParentBound)> = Vec::new();
        let mut ref_targets: HashSet<Checksum> = HashSet::new();
        let mut weak_refs: Vec<(Ref, Checksum)> = Vec::new();
        let mut weak_roots: HashMap<Checksum, WeakBounds> = HashMap::new();
        for ListedRef {
            space,
            name,
            addressable,
            checksum,
        } in named_refs
        {
            let own_mirror = space == RefSpace::Mirrors
                && name.split_once('/').is_some_and(|(id, _)| Some(id) == own);
            if own_mirror {
                roots.push((checksum, opts.unnamed_bound()));
                ref_targets.insert(checksum);
                continue;
            }
            let listed = listed_ref(space, name, addressable);
            let bound = opts.ref_bound(listed.as_ref());
            if let Some(r) =
                listed.filter(|r| filtering && !opts.weak_ref_filter.is_strong(r, &checksum))
            {
                weak_roots.entry(checksum).or_default().add(bound);
                weak_refs.push((r, checksum));
                continue;
            }
            // The bound of a ref belongs to the commit that it names, whatever
            // path the walk took to that commit. So the walk replaces an
            // inherited bound at each ref target that it arrives at. If two refs
            // name one commit, both roots stand, and the walk expands the commit
            // under each of the two bounds.
            roots.push((checksum, bound));
            ref_targets.insert(checksum);
        }

        let mut all_objects = self.list_objects().await?;
        if let Some(commit) = opts.delete_commit {
            all_objects.remove(&ObjectName::new(commit, ObjectType::Commit));
            all_objects.remove(&ObjectName::new(commit, ObjectType::CommitMeta));
        }
        let global_bound = opts.global_bound();
        if !opts.roots_on_refs_alone() {
            roots.extend(
                all_objects
                    .iter()
                    .filter(|o| o.ty == ObjectType::Commit)
                    .map(|o| (o.checksum, global_bound)),
            );
        }

        let gc = crate::traverse::GcRoots {
            attachments: true,
            supplements: true,
            traverse_parent: opts.traverse_parent,
            // A `commit_only` run reads only the commit names of the reachable
            // set, so the walk neither reads nor collects the trees.
            traverse_tree: !opts.commit_only,
            weak_roots,
        };
        let (keep, warnings) = self
            .traverse_reachable_gc(
                roots,
                global_bound,
                &gc,
                &ref_targets,
                opts.delete_commit,
                &all_objects,
            )
            .await?;
        // A kept commit keeps its detached metadata.
        let kept = |o: &ObjectName| {
            keep.contains(o)
                || (o.ty.is_commit_sidecar()
                    && keep.contains(&ObjectName::new(o.checksum, ObjectType::Commit)))
        };

        // Each present object that the walk did not reach is a candidate,
        // except tombstone markers, which the `ostree` command never prunes.
        // `commit_only` narrows the candidates to commit objects and the
        // detached metadata removed with one.
        // The objects of the store less the reachable ones is the largest size
        // of the list, so one allocation holds it.
        let mut doomed: Vec<ObjectName> =
            Vec::with_capacity(all_objects.len().saturating_sub(keep.len()));
        doomed.extend(
            all_objects
                .iter()
                .filter(|o| o.ty != ObjectType::TombstoneCommit && !kept(o))
                .filter(|o| {
                    !opts.commit_only || o.ty == ObjectType::Commit || o.ty.is_commit_sidecar()
                })
                .copied(),
        );

        let total_objects = all_objects
            .iter()
            .filter(|o| counted(o.ty, opts.commit_only))
            .count();

        let sweep = Sweep {
            mode,
            no_prune: opts.no_prune,
            // `delete_commit` turns tombstone writing on for the whole run, as
            // the config key does for a run that names no commit.
            tombstones: opts.delete_commit.is_some()
                || self.config().get::<repo::TombstoneCommits>()?,
            fsync: self.config().get::<repo::Fsync>()?,
            commit_only: opts.commit_only,
        };

        // Delete each weak ref that the walk did not reach. This pass runs
        // after the walk, because a walk that fails must leave the repository
        // as it was. It runs before the commit deletion and the sweep.
        // `refuse_referenced_commit` ran over the whole ref listing and refused
        // a `delete_commit` that a weak ref names, so the two cannot meet.
        //
        // The pass unlinks ref files alone and takes no lock of its own, so it
        // cannot deadlock against the hold of the run. An emptied parent
        // directory under `refs/` stays in place, because an rmdir walk races
        // a writer that creates a sibling ref. This includes an emptied
        // `refs/mirrors/ID/`.
        //
        // The whole pass runs in one blocking hop, as the object sweep does.
        // One hop covers the refs of each space. The pass reads each ref
        // immediately before its unlink, and it calls `fsync` once at the end
        // on the directories that held a removed ref.
        // The doomed list is the weak list less the refs that the walk reached,
        // in the order of the listing. So the code narrows the weak list in
        // place.
        let mut doomed_refs = weak_refs;
        doomed_refs
            .retain(|(_, target)| !keep.contains(&ObjectName::new(*target, ObjectType::Commit)));
        // The run opens `state/` in the hop of the refs, before its first
        // removal, in the dry run too. A symlink or an entry that is not a
        // directory at `state` then fails the run before it removes anything.
        // The leftover sweep reads the markers through this handle.
        //
        // A dry run reports what the walk decided and touches nothing. It
        // runs the check of the real run, so it fails where the real run
        // fails before its first unlink.
        let (state, mut deleted_refs): (Option<RepoDir>, Vec<Ref>) = if opts.no_prune {
            let repo = self.clone();
            let (state, doomed_refs) = ostrya_rt::unblock(move || {
                let state = repo.root_dir().open_layout(RepoLayout::State).optional()?;
                crate::refs::check_refs_to_delete_blocking(repo.root_dir(), &doomed_refs, |r| {
                    crate::refs::ref_relpath(None, r)
                })?;
                Ok::<_, Error>((state, doomed_refs))
            })
            .await?;
            (state, doomed_refs.into_iter().map(|(r, _)| r).collect())
        } else {
            let repo = self.clone();
            let fsync = sweep.fsync;
            ostrya_rt::unblock(move || {
                let state = repo.root_dir().open_layout(RepoLayout::State).optional()?;
                let deleted = crate::refs::delete_matching_refs_blocking(
                    repo.root_dir(),
                    doomed_refs,
                    |r| crate::refs::ref_relpath(None, r),
                    fsync,
                )?;
                Ok::<_, Error>((state, deleted))
            })
            .await?
        };
        deleted_refs.sort();

        // The walk succeeded, so no data that the prune reads can refuse it
        // now. Remove the named commit, then sweep what it orphaned. A dry run
        // keeps the commit and reports the sweep that its removal causes.
        if !opts.no_prune
            && let Some(commit) = opts.delete_commit
        {
            self.delete_commit_object(&commit, &sweep).await?;
        }

        // The commits that the store holds after the sweep are the listed ones
        // that the walk kept. Each listed commit that the walk did not keep is
        // doomed. The listing already leaves out the commit that
        // `delete_commit` names. The set comes from the listing in memory, so
        // the leftover sweep reads no object to learn it.
        let present_commits: HashSet<Checksum> = if opts.no_prune {
            HashSet::new()
        } else {
            all_objects
                .iter()
                .filter(|o| o.ty == ObjectType::Commit && keep.contains(o))
                .map(|o| o.checksum)
                .collect()
        };
        drop(all_objects);
        drop(keep);

        let fsync = sweep.fsync;
        let repo = self.clone();
        let (pruned_objects, freed_bytes) =
            ostrya_rt::unblock(move || sweep_blocking(&repo, &sweep, &doomed)).await?;

        // Remove what refers to an absent commit: each static delta whose
        // target commit is absent and each `.commitpartial` marker whose commit
        // is absent. This covers the commits that this run removed, whose
        // markers the object sweep leaves for this pass. It also covers the
        // commits that a run that stopped part way through removed, which no
        // later walk finds. The run holds the repository lock exclusive, so no
        // pull stands between the write of a marker and the store of its
        // commit.
        if !opts.no_prune {
            let repo = self.clone();
            ostrya_rt::unblock(move || {
                crate::delta::prune_delta_dirs(repo.root_dir(), fsync, |to| {
                    !present_commits.contains(to)
                })?;
                sweep_orphan_markers_blocking(state.as_ref(), &present_commits, fsync)
            })
            .await?;
        }

        Ok(PruneStats {
            total_objects,
            pruned_objects,
            freed_bytes,
            deleted_refs,
            warnings,
        })
    }

    /// Refuses a commit that a ref names, so that a prune cannot leave a
    /// dangling ref.
    async fn refuse_referenced_commit(&self, commit: &Checksum) -> Result<()> {
        let referenced = self.list_all_ref_targets().await?;
        if referenced.contains(commit) {
            return Err(Error::InvalidFormat(format!(
                "cannot delete commit {commit}: it is the target of a ref"
            )));
        }
        Ok(())
    }

    /// Removes the object and the detached metadata of a named commit with
    /// [`remove_commit`]. If the run writes tombstones, the tombstone comes
    /// before the commit.
    ///
    /// The ref check runs again next to the unlink, so a ref published while
    /// the prune walked the store still refuses the deletion. If the run
    /// syncs, the call syncs the directory that held the removed entries before
    /// it returns. The removal is then durable before the sweep removes an
    /// object that the commit reached. The partial marker of the commit stays.
    /// The run removes it with the orphan markers after the sweep, because the
    /// commit is absent from the listing that this pass reads.
    async fn delete_commit_object(&self, commit: &Checksum, sweep: &Sweep) -> Result<()> {
        self.refuse_referenced_commit(commit).await?;
        let commit = *commit;
        let sweep = *sweep;
        let repo = self.clone();
        ostrya_rt::unblock(move || {
            let path = loose_path(&commit, ObjectType::Commit, sweep.mode);
            let fanout = open_fanout(repo.objects(), &path)?;
            let mut touched = BTreeSet::new();
            remove_commit(
                repo.objects(),
                fanout.as_ref(),
                &sweep,
                &commit,
                true,
                &mut touched,
            )?;
            sync_dirs(repo.objects(), &touched)
        })
        .await
    }
}

/// Removes each `state/<commit>.commitpartial` marker whose commit is not in
/// `present`. `state` is the `state/` handle that the run opened, or `None`
/// if the repository has no `state/`, and then nothing is to remove.
///
/// The function lists `state/` one time. It leaves in place a directory, a
/// name that is not UTF-8, and a name that is not a marker name in lowercase
/// hex. It unlinks each other entry at a marker name, also a symlink, whose
/// target stays, and a FIFO. An entry that is a directory at the unlink stays
/// too. With `fsync`, the function syncs `state/` one time after the last
/// unlink, if it unlinked an entry.
fn sweep_orphan_markers_blocking(
    state: Option<&RepoDir>,
    present: &HashSet<Checksum>,
    fsync: bool,
) -> Result<()> {
    let Some(state) = state else {
        return Ok(());
    };
    let mut orphans = Vec::new();
    state.for_each_entry(|name, file_type| {
        if file_type != FileType::Directory
            && let Some(commit) = name
                .to_str()
                .ok()
                .and_then(|name| name.strip_suffix(".commitpartial"))
                .and_then(|hex| Checksum::from_hex_lower(hex).ok())
            && !present.contains(&commit)
        {
            orphans.push(commit);
        }
        ControlFlow::Continue(())
    })?;
    let mut removed = false;
    for commit in orphans {
        match state.remove_file(&crate::pull::partial_name(&commit), false) {
            Ok(unlinked) => removed |= unlinked,
            Err(FsError::Io(e)) if e.raw_os_error() == Some(Errno::ISDIR.raw_os_error()) => {}
            Err(e) => return Err(e.into()),
        }
    }
    if removed && fsync {
        state.sync()?;
    }
    Ok(())
}

/// Removes one commit, in this order:
///
/// 1. If the run writes tombstones, writes the tombstone of the commit.
///    `objects` is the `objects/` handle of the repository.
/// 2. Unlinks the commit object.
/// 3. If `meta` is true, unlinks its detached metadata.
///
/// `fanout` is the handle of the `objects/<xx>` directory of the commit, which
/// the caller opened for this commit alone, or `None` if that directory is
/// absent. The two unlinks go through this one handle. With `None`, the
/// function writes the tombstone and unlinks nothing.
///
/// If the run syncs and the function unlinked an entry, it adds the first
/// byte of the commit checksum to `touched`. That byte names the fanout
/// directory.
///
/// The `state/<commit>.commitpartial` marker of the commit stays. The commit
/// can already be partial. If a crash makes the marker unlink durable and
/// leaves the commit unlink not durable, a partial commit looks complete. The
/// run removes the marker after the object sweep, with the markers whose
/// commit is absent. The next run removes a marker that a failed or crashed
/// run leaves.
///
/// The commit goes before its detached metadata. Detached metadata with no
/// commit is unreachable, and the next prune removes it. The reverse order
/// leaves a commit with no signatures.
fn remove_commit(
    objects: &RepoDir,
    fanout: Option<&RepoDir>,
    sweep: &Sweep,
    commit: &Checksum,
    meta: bool,
    touched: &mut BTreeSet<u8>,
) -> Result<()> {
    if sweep.tombstones {
        write_tombstone(objects, commit, sweep.mode, sweep.fsync)?;
    }
    let Some(fanout) = fanout else {
        return Ok(());
    };
    let path = loose_path(commit, ObjectType::Commit, sweep.mode);
    let mut unlinked = fanout.remove_file(leaf_of(&path), false)?;
    if meta {
        let path = loose_path(commit, ObjectType::CommitMeta, sweep.mode);
        unlinked |= fanout.remove_file(leaf_of(&path), false)?;
    }
    if unlinked && sweep.fsync {
        touched.insert(commit.as_bytes()[0]);
    }
    Ok(())
}

/// Calls `fsync` on each `objects/<xx>` directory in `fanouts`, each named by
/// the first byte of the checksums of its objects. `objects` is the
/// `objects/` handle.
fn sync_dirs(objects: &RepoDir, fanouts: &BTreeSet<u8>) -> Result<()> {
    for fanout in fanouts {
        objects.sync_dir(&format!("{fanout:02x}"))?;
    }
    Ok(())
}

/// Opens the `objects/<xx>` directory of the loose object at `path`, relative
/// to `objects`, the `objects/` handle. Returns `None` if the directory is
/// absent, and then the object is absent too.
///
/// The caller keeps the handle for one object alone, and drops it before the
/// next object. A symlink or an entry that is not a directory at
/// `objects/<xx>` gives [`Error::InvalidFormat`], which names the object.
fn open_fanout(objects: &RepoDir, path: &str) -> Result<Option<RepoDir>> {
    let fanout = path.split_once('/').map_or(path, |(fanout, _)| fanout);
    objects
        .open_dir(fanout)
        .optional()
        .map_err(|e| crate::read::object_path_error(e, path).into())
}

/// Returns the name of the loose object at `path` in its `objects/<xx>`
/// directory.
fn leaf_of(path: &str) -> &str {
    path.split_once('/').map_or(path, |(_, leaf)| leaf)
}

/// Stats the loose object `name` and unlinks it, through one handle of its
/// `objects/<xx>` directory, with no sync. Returns its size, or `None` if it
/// is absent at the stat.
///
/// If the run syncs and the call unlinked the object, the call adds the
/// first byte of the checksum of the object to `touched`.
fn remove_object(
    objects: &RepoDir,
    sweep: &Sweep,
    name: &ObjectName,
    touched: &mut BTreeSet<u8>,
) -> Result<Option<u64>> {
    let path = name.loose_path(sweep.mode);
    let Some(fanout) = open_fanout(objects, &path)? else {
        return Ok(None);
    };
    let leaf = leaf_of(&path);
    let Some(stat) = fanout.lstat(leaf).optional()? else {
        return Ok(None);
    };
    if fanout.remove_file(leaf, false)? && sweep.fsync {
        touched.insert(name.checksum.as_bytes()[0]);
    }
    Ok(Some(stat.size))
}

/// Stats each doomed object, unlinks it unless `no_prune` is set, and returns
/// the count and the sum of the freed bytes.
///
/// The sweep runs in two phases:
///
/// 1. The commit phase removes each doomed commit with [`remove_commit`]:
///    the commit, and then its detached metadata if that is doomed too. Then
///    it removes each doomed detached metadata whose commit the phase did not
///    remove.
/// 2. The content phase removes every other doomed object, in any order.
///
/// If the run syncs, the sweep syncs the `objects/` directories that the
/// commit phase changed between the commit phase and the content phase. A
/// sweep that stops at an error or a crash then leaves no commit object whose
/// tree it started to remove. If the run syncs, the sweep also syncs one time
/// each `objects/<xx>` directory that the content phase changed, at the end
/// of the content phase. If the run does not sync, a crash gives no
/// guarantee of which removals reached the disk, in which order. The sweep
/// removes no `.commitpartial` marker.
///
/// The sweep stats each doomed object before its unlink. The detached metadata
/// that the commit phase removes with its commit is the exception. A real run
/// opens the `objects/<xx>` directory of each object, stats and unlinks the
/// object through that handle, and closes the handle before the next object.
/// A commit and its detached metadata share one handle. A dry run stats each
/// object relative to `objects/`. Neither
/// number counts detached metadata. The sweep skips an
/// object that is already absent at its stat and counts it in neither
/// number.
fn sweep_blocking(repo: &Repo, sweep: &Sweep, doomed: &[ObjectName]) -> Result<(usize, u64)> {
    let mut count = 0usize;
    let mut freed = 0u64;
    let mut tally = |ty: ObjectType, size: u64| {
        if counted(ty, sweep.commit_only) {
            count += 1;
            freed += size;
        }
    };

    // The commit phase.
    let doomed_meta: HashSet<Checksum> = doomed
        .iter()
        .filter(|o| o.ty == ObjectType::CommitMeta)
        .map(|o| o.checksum)
        .collect();
    let objects = repo.objects();
    let mut touched = BTreeSet::new();
    let mut removed_commits = HashSet::new();
    for name in doomed.iter().filter(|o| o.ty == ObjectType::Commit) {
        let path = name.loose_path(sweep.mode);
        let size = if sweep.no_prune {
            objects.lstat(&path).optional()?.map(|stat| stat.size)
        } else {
            let Some(fanout) = open_fanout(objects, &path)? else {
                continue;
            };
            let size = fanout
                .lstat(leaf_of(&path))
                .optional()?
                .map(|stat| stat.size);
            if size.is_some() {
                remove_commit(
                    objects,
                    Some(&fanout),
                    sweep,
                    &name.checksum,
                    doomed_meta.contains(&name.checksum),
                    &mut touched,
                )?;
            }
            size
        };
        let Some(size) = size else {
            continue;
        };
        removed_commits.insert(name.checksum);
        tally(name.ty, size);
    }
    // Detached metadata whose commit is absent, which no commit removal took
    // with it.
    for name in doomed
        .iter()
        .filter(|o| o.ty.is_commit_sidecar() && !removed_commits.contains(&o.checksum))
    {
        let size = if sweep.no_prune {
            objects
                .lstat(&name.loose_path(sweep.mode))
                .optional()?
                .map(|stat| stat.size)
        } else {
            remove_object(objects, sweep, name, &mut touched)?
        };
        if let Some(size) = size {
            tally(name.ty, size);
        }
    }

    // The barrier: the commit removals are durable before any content goes.
    sync_dirs(objects, &touched)?;

    // The content phase.
    let mut touched = BTreeSet::new();
    for name in doomed
        .iter()
        .filter(|o| o.ty != ObjectType::Commit && !o.ty.is_commit_sidecar())
    {
        let size = if sweep.no_prune {
            objects
                .lstat(&name.loose_path(sweep.mode))
                .optional()?
                .map(|stat| stat.size)
        } else {
            remove_object(objects, sweep, name, &mut touched)?
        };
        if let Some(size) = size {
            tally(name.ty, size);
        }
    }
    sync_dirs(objects, &touched)?;
    Ok((count, freed))
}