ostrya 0.7.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
//! Integration tests of the commit path, of refs, and of detached metadata.
//!
//! The tests write the fixture source tree through the write path. Then they
//! compare the commit object byte for byte with the fixtures of the `ostree`
//! command. The tests cover:
//!
//! - the commit without `ostree.sizes` in archive, bare-user, and
//!   bare-user-shared (the commit object is the same in each mode)
//! - the archive commit of `--generate-sizes`
//! - the ref files that the `ostree` command resolves
//! - round trips of detached metadata, and the error of a corrupt
//!   `.commitmeta`
//! - immediate ref writes
//! - concurrent commits
//! - a repository that ostrya writes and the `ostree` command accepts
//! - a bare-user-only commit of a non-canonical tree, compared with the
//!   objects of the `ostree` command

mod common;

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;

use common::{
    COMMIT, CONTENT, ROOT_DIRMETA, ROOT_DIRTREE, SIZES_COMMIT, TmpDir, fixture_repo,
    ostree_available,
};
use ostrya::{
    Checksum, CollectionRef, CommitModifier, CommitModifierFlags, CommitOptions, CreateOptions,
    DirMeta, FileMeta, MutableTree, ObjectType, Repo, RepoMode, RepoTree, Transaction, TreeEntry,
    Type, Value,
};
use ostrya_core::{Xattrs, loose_path};
use ostrya_rt::block_on;
use std::os::fd::AsFd;

const SUBJECT: &str = "fixture commit";

fn csum(hex: &str) -> Checksum {
    Checksum::from_hex(hex).unwrap()
}

/// The `ostree.ref-binding` metadata dict that the `ostree` command writes for
/// a branch commit: one `as` entry that names the branch. A byte-identical
/// copy of the fixture commit needs this dict in the key order of the `ostree`
/// command.
fn ref_binding(refs: &[&str]) -> Value {
    let names = refs.iter().map(|r| Value::Str((*r).to_owned())).collect();
    Value::Array(vec![Value::Tuple(vec![
        Value::Str("ostree.ref-binding".to_owned()),
        Value::variant(Type::parse("as").unwrap(), Value::Array(names)),
    ])])
}

/// The commit options that reproduce the fixture commit: the branch binding,
/// the fixture subject, and the fixed timestamp.
fn fixture_commit_options() -> CommitOptions {
    CommitOptions {
        subject: Some(SUBJECT.to_owned()),
        timestamp: Some(1_700_000_000),
        metadata: Some(ref_binding(&["test/main"])),
        ..CommitOptions::default()
    }
}

/// Builds the fixture source tree (hello/empty/nested/link) under `base/src`.
fn build_fixture_source(base: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let set_mode = |p: &Path, m: u32| {
        std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap();
    };
    let src = base.join("src");
    std::fs::create_dir_all(src.join("subdir")).unwrap();
    std::fs::write(src.join("hello.txt"), b"hello ostree\n").unwrap();
    std::fs::write(src.join("empty.txt"), b"").unwrap();
    std::fs::write(src.join("subdir/nested.txt"), b"nested\n").unwrap();
    std::os::unix::fs::symlink("hello.txt", src.join("link")).unwrap();
    set_mode(&src.join("hello.txt"), 0o644);
    set_mode(&src.join("empty.txt"), 0o644);
    set_mode(&src.join("subdir/nested.txt"), 0o644);
    set_mode(&src.join("subdir"), 0o755);
    set_mode(&src, 0o755);
}

/// Ingests `base/src` into a new root tree with owner 0:0 and canonical
/// permissions, so the tree matches the owner-0:0 fixture of the `ostree`
/// command. Returns the staged root. If `generate_sizes` is `true`, the ingest
/// also sets `GENERATE_SIZES`.
async fn ingest_fixture(txn: &Transaction, base: &Path, generate_sizes: bool) -> ostrya::RepoTree {
    let mut flags = CommitModifierFlags::CANONICAL_PERMISSIONS | CommitModifierFlags::SKIP_XATTRS;
    if generate_sizes {
        flags |= CommitModifierFlags::GENERATE_SIZES;
    }
    let mut modifier = CommitModifier::new(flags);
    let mut mtree = MutableTree::new();
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(
        dfd.as_fd(),
        Path::new("src"),
        &mut mtree,
        Some(&mut modifier),
    )
    .await
    .unwrap();
    txn.write_mtree(&mut mtree).await.unwrap()
}

/// Returns the on-disk bytes of a loose object in the repository at `root`.
fn object_bytes(root: &Path, hex: &str, ty: ObjectType, mode: RepoMode) -> Vec<u8> {
    std::fs::read(root.join("objects").join(loose_path(&csum(hex), ty, mode))).unwrap()
}

#[test]
fn commit_object_is_byte_identical_across_modes() {
    // The commit object does not depend on the mode. In each mode, the fixture
    // input reproduces the commit bytes and the checksum of the archive fixture,
    // and a ref that ostrya resolves.
    let fixture_commit = object_bytes(
        &fixture_repo("archive"),
        COMMIT,
        ObjectType::Commit,
        RepoMode::Archive,
    );

    for mode in [
        RepoMode::Archive,
        RepoMode::BareUser,
        RepoMode::BareUserShared,
    ] {
        let tmp = TmpDir::new("commit-bytes");
        let base = tmp.path();
        build_fixture_source(base);
        let root_dir = base.join("repo");
        block_on(async {
            let repo = Repo::create(&root_dir, CreateOptions::new(mode))
                .await
                .unwrap();
            let txn = repo.transaction().await.unwrap();
            let root = ingest_fixture(&txn, base, false).await;
            assert_eq!(
                root.dirtree_checksum(),
                &csum(ROOT_DIRTREE),
                "{mode:?} root dirtree"
            );
            assert_eq!(
                root.dirmeta_checksum(),
                &csum(ROOT_DIRMETA),
                "{mode:?} root dirmeta"
            );

            let commit = txn
                .write_commit(fixture_commit_options(), &root)
                .await
                .unwrap();
            assert_eq!(
                commit,
                csum(COMMIT),
                "{mode:?} commit checksum matches the tool"
            );
            txn.set_ref("test/main", Some(&commit));
            txn.commit().await.unwrap();

            assert_eq!(
                object_bytes(&root_dir, COMMIT, ObjectType::Commit, mode),
                fixture_commit,
                "{mode:?} commit object is byte-identical to the fixture"
            );

            // The ref file resolves in this handle and in a newly opened handle.
            assert_eq!(
                repo.resolve_rev("test/main", false).await.unwrap(),
                Some(csum(COMMIT)),
                "{mode:?} ref resolves"
            );
            let reopened = Repo::open(&root_dir).await.unwrap();
            assert_eq!(
                reopened.resolve_rev("test/main", false).await.unwrap(),
                Some(csum(COMMIT))
            );
        });
    }
}

#[test]
fn generate_sizes_commit_matches_the_fixture() {
    // An archive commit with GENERATE_SIZES reproduces the commit bytes and the
    // checksum of the sizes fixture. `ostree.sizes` covers every object (content
    // and metadata), and the commit appends it after the ref binding of the caller.
    let fixture_commit = object_bytes(
        &fixture_repo("sizes"),
        SIZES_COMMIT,
        ObjectType::Commit,
        RepoMode::Archive,
    );

    let tmp = TmpDir::new("commit-sizes");
    let base = tmp.path();
    build_fixture_source(base);
    let root_dir = base.join("repo");
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let root = ingest_fixture(&txn, base, true).await;
        let commit = txn
            .write_commit(fixture_commit_options(), &root)
            .await
            .unwrap();
        assert_eq!(commit, csum(SIZES_COMMIT), "generate-sizes commit checksum");
        txn.set_ref("test/main", Some(&commit));
        txn.commit().await.unwrap();

        assert_eq!(
            object_bytes(
                &root_dir,
                SIZES_COMMIT,
                ObjectType::Commit,
                RepoMode::Archive
            ),
            fixture_commit,
            "the ostree.sizes commit is byte-identical to the fixture"
        );
    });
}

#[test]
fn generate_sizes_is_a_noop_outside_archive() {
    // In bare-user, the request for sizes never marks the transaction, so the
    // commit is byte-identical with and without it.
    let commit_with = |generate_sizes: bool| {
        let tmp = TmpDir::new("commit-sizes-bare");
        let base = tmp.path();
        build_fixture_source(base);
        let root_dir = base.join("repo");
        block_on(async {
            let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::BareUser))
                .await
                .unwrap();
            let txn = repo.transaction().await.unwrap();
            let root = ingest_fixture(&txn, base, generate_sizes).await;
            let commit = txn
                .write_commit(fixture_commit_options(), &root)
                .await
                .unwrap();
            txn.abort().await.unwrap();
            commit
        })
    };
    assert_eq!(
        commit_with(true),
        commit_with(false),
        "GENERATE_SIZES is a no-op in bare-user, so the commit is unchanged"
    );
    // The commit is also equal to the fixture commit, which has no sizes key.
    assert_eq!(commit_with(true), csum(COMMIT));
}

#[test]
fn set_generate_sizes_settles_the_key_in_both_directions() {
    // `set_generate_sizes` sets the key for the whole transaction. `true` adds the
    // key when no ingest requested it. `false` removes the key after an ingest
    // under GENERATE_SIZES requested it.
    let commit_with = |ingest: bool, request: Option<bool>| {
        let tmp = TmpDir::new("commit-sizes-request");
        let base = tmp.path();
        build_fixture_source(base);
        let root_dir = base.join("repo");
        block_on(async {
            let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            let mut txn = repo.transaction().await.unwrap();
            let root = ingest_fixture(&txn, base, ingest).await;
            if let Some(enabled) = request {
                txn.set_generate_sizes(enabled);
            }
            let commit = txn
                .write_commit(fixture_commit_options(), &root)
                .await
                .unwrap();
            txn.abort().await.unwrap();
            commit
        })
    };
    let sized = csum(SIZES_COMMIT);
    let plain = csum(COMMIT);
    assert_eq!(commit_with(true, None), sized, "the ingest flag alone");
    assert_eq!(commit_with(false, None), plain, "no request at all");
    assert_eq!(
        commit_with(false, Some(true)),
        sized,
        "the request alone reaches the key"
    );
    assert_eq!(
        commit_with(true, Some(false)),
        plain,
        "the request turns the ingest flag off again"
    );
}

#[test]
fn detached_metadata_round_trips() {
    // A write of an a{sv} and a read give back the same value. A write of None
    // gives the zero-length "no metadata" file, which reads back as None.
    let tmp = TmpDir::new("commit-detached");
    let root_dir = tmp.path().join("repo");
    let commit = csum(COMMIT);
    let meta = Value::Array(vec![Value::Tuple(vec![
        Value::Str("ostree.sign.dummy".to_owned()),
        Value::variant(
            Type::parse("aay").unwrap(),
            Value::Array(vec![Value::Bytes(b"a-signature-blob".to_vec())]),
        ),
    ])]);

    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();

        assert_eq!(
            repo.read_commit_detached_metadata(&commit).await.unwrap(),
            None,
            "absent detached metadata reads as None"
        );

        repo.write_commit_detached_metadata(&commit, Some(&meta))
            .await
            .unwrap();
        assert_eq!(
            repo.read_commit_detached_metadata(&commit).await.unwrap(),
            Some(meta.clone()),
            "detached metadata round-trips"
        );

        // A None write gives the zero-length file, which reads back as None.
        repo.write_commit_detached_metadata(&commit, None)
            .await
            .unwrap();
        let path = root_dir.join("objects").join(loose_path(
            &commit,
            ObjectType::CommitMeta,
            RepoMode::Archive,
        ));
        assert_eq!(
            std::fs::metadata(&path).unwrap().len(),
            0,
            "None writes a zero-length file, not a deletion"
        );
        assert_eq!(
            repo.read_commit_detached_metadata(&commit).await.unwrap(),
            None,
            "a zero-length file reads as None, not an empty dict"
        );
    });
}

#[test]
fn corrupt_detached_metadata_is_a_core_error() {
    // A `.commitmeta` that is not an a{sv} in normal form does not parse.
    let tmp = TmpDir::new("commit-detached-corrupt");
    let root_dir = tmp.path().join("repo");
    let commit = csum(COMMIT);

    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.write_commit_detached_metadata(&commit, None)
            .await
            .unwrap();
        let path = root_dir.join("objects").join(loose_path(
            &commit,
            ObjectType::CommitMeta,
            RepoMode::Archive,
        ));
        std::fs::write(&path, [0xff]).unwrap();

        let err = repo
            .read_commit_detached_metadata(&commit)
            .await
            .unwrap_err();
        assert!(matches!(err, ostrya::Error::Core(_)), "{err:?}");
    });
}

#[test]
fn set_ref_immediate_writes_and_removes() {
    let tmp = TmpDir::new("commit-immediate");
    let root_dir = tmp.path().join("repo");
    let commit = csum(COMMIT);
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("branch/one", Some(&commit))
            .await
            .unwrap();
        assert_eq!(
            repo.resolve_rev("branch/one", false).await.unwrap(),
            Some(commit)
        );
        // The ref file has 65 bytes: 64 hex characters and a newline.
        let ref_path = root_dir.join("refs/heads/branch/one");
        assert_eq!(std::fs::metadata(&ref_path).unwrap().len(), 65);

        repo.set_ref_immediate("branch/one", None).await.unwrap();
        assert!(!ref_path.exists(), "a None checksum removes the ref");
        assert_eq!(repo.resolve_rev("branch/one", true).await.unwrap(), None);
    });
}

#[test]
fn ref_writes_run_under_both_fsync_settings() {
    // If `[core] fsync` is set, each ref change syncs the directory that holds
    // the ref. A ref write and an alias write sync it after the rename, and a
    // removal syncs it after the unlink. The sync is not visible outside the process.
    // This test pins the paths that the sync opens, because a wrong parent fails
    // the open. It also checks that both settings reach each form.
    for fsync in [true, false] {
        let tag = if fsync {
            "commit-fsync"
        } else {
            "commit-nofsync"
        };
        let tmp = TmpDir::new(tag);
        let root_dir = tmp.path().join("repo");
        let a = csum(COMMIT);
        let b = csum(CONTENT);
        block_on(async {
            Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            let config = root_dir.join("config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str(&format!("fsync={fsync}\n"));
            std::fs::write(&config, text).unwrap();
            let repo = Repo::open(&root_dir).await.unwrap();

            // A nested local ref, a remote ref, and a collection ref. Their parents are
            // one, two, and two levels under `refs/`.
            repo.set_ref_immediate("branch/one", Some(&a))
                .await
                .unwrap();
            repo.set_ref_immediate("origin:branch/two", Some(&b))
                .await
                .unwrap();
            let cref = CollectionRef::new("org.example.Coll", "three");
            repo.set_collection_ref_immediate(&cref, Some(&a))
                .await
                .unwrap();
            assert_eq!(
                repo.resolve_rev("branch/one", false).await.unwrap(),
                Some(a)
            );
            assert_eq!(
                repo.resolve_rev("origin:branch/two", false).await.unwrap(),
                Some(b)
            );

            // An alias beside the nested ref, then the removal of both refs.
            repo.set_ref_alias_immediate("branch/alias", "branch/one")
                .await
                .unwrap();
            let alias = root_dir.join("refs/heads/branch/alias");
            assert!(std::fs::symlink_metadata(&alias).unwrap().is_symlink());
            assert_eq!(
                repo.resolve_rev("branch/alias", false).await.unwrap(),
                Some(a)
            );

            repo.set_ref_immediate("branch/alias", None).await.unwrap();
            repo.set_ref_immediate("origin:branch/two", None)
                .await
                .unwrap();
            assert!(!alias.exists());
            assert_eq!(
                repo.resolve_rev("origin:branch/two", true).await.unwrap(),
                None
            );

            // A ref write of a transaction takes the same path.
            let txn = repo.transaction().await.unwrap();
            txn.set_ref("branch/four", Some(&b));
            txn.commit().await.unwrap();
            assert_eq!(
                repo.resolve_rev("branch/four", false).await.unwrap(),
                Some(b)
            );
        });
    }
}

#[test]
fn set_ref_over_alias_replaces_symlink() {
    // Observed with the `ostree` command (2026.1): a ref write to a relative
    // symlink alias replaces the symlink with a regular ref file.
    // The alias target does not change. This occurs for a commit onto the alias
    // and for `ostree refs --create --force`. The rename-over-target write of
    // ostrya gives the same result, and this test pins it.
    let tmp = TmpDir::new("commit-alias");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    let b = csum(CONTENT);
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        // A concrete ref test/bar -> A, then an alias test/foo -> bar. The alias is a
        // relative symlink, as the `ostree` command writes it.
        repo.set_ref_immediate("test/bar", Some(&a)).await.unwrap();
        let heads = root_dir.join("refs/heads/test");
        std::os::unix::fs::symlink("bar", heads.join("foo")).unwrap();
        // The read path follows the alias to A.
        assert_eq!(repo.resolve_rev("test/foo", false).await.unwrap(), Some(a));

        // A write of B onto the alias replaces the symlink with a regular file.
        repo.set_ref_immediate("test/foo", Some(&b)).await.unwrap();
        let foo_meta = std::fs::symlink_metadata(heads.join("foo")).unwrap();
        assert!(
            foo_meta.file_type().is_file(),
            "the alias symlink is replaced by a regular ref file"
        );
        assert_eq!(repo.resolve_rev("test/foo", false).await.unwrap(), Some(b));

        // The alias target does not change: test/bar still points at A.
        let bar_meta = std::fs::symlink_metadata(heads.join("bar")).unwrap();
        assert!(bar_meta.file_type().is_file());
        assert_eq!(repo.resolve_rev("test/bar", false).await.unwrap(), Some(a));
    });
}

#[test]
fn check_refs_path_reports_a_path_through_a_ref_file() {
    // The probe that a listing runs over the path that its PREFIX names. The
    // probe returns `ENOTDIR` if a component before the last one is not a
    // directory. It returns `Ok` for a ref file, a directory, and a path that
    // names nothing, because a prefix that matches no ref lists nothing.
    let tmp = TmpDir::new("commit-refs-path");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("plain", Some(&a)).await.unwrap();
        repo.set_ref_immediate("deep/nest/ing", Some(&a))
            .await
            .unwrap();
        repo.set_ref_immediate("origin:rr/x", Some(&a))
            .await
            .unwrap();
        repo.set_ref_alias_immediate("al", "plain").await.unwrap();

        for path in [
            "heads/plain",
            "heads/deep",
            "heads/deep/nest",
            "heads/al",
            "remotes/origin",
            "remotes/origin/rr/x",
            // Naming nothing, at one level and at two.
            "heads/nosuch",
            "heads/nosuch/deeper",
        ] {
            repo.check_refs_path(path)
                .await
                .unwrap_or_else(|err| panic!("`{path}` was refused: {err}"));
        }

        // Paths through a ref file:
        // - the last component under a ref file
        // - an inner component under a ref file
        // - a path through an alias symlink to a ref file
        // - the remote form
        for path in [
            "heads/plain/x",
            "heads/plain/x/y",
            "heads/al/x",
            "remotes/origin/rr/x/y",
        ] {
            let err = repo.check_refs_path(path).await.unwrap_err();
            assert!(
                err.to_string().contains("Not a directory"),
                "`{path}` was not refused with ENOTDIR, got {err}"
            );
        }
    });
}

#[test]
fn resolve_rev_reads_a_checksum_in_lowercase_hex_alone() {
    // A revision of 64 characters is a checksum only if it is in lowercase hex.
    // An uppercase or mixed-case name of that length is a refspec. The content of
    // a ref file keeps the lenient reader, so a file that holds an uppercase
    // checksum resolves.
    let tmp = TmpDir::new("commit-rev-case");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    let upper = COMMIT.to_uppercase();
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("plain", Some(&a)).await.unwrap();

        // The lowercase form resolves to itself, also if the object store does not
        // hold the commit.
        assert_eq!(repo.resolve_rev(COMMIT, false).await.unwrap(), Some(a));
        // The uppercase and mixed forms are ref names, and no ref has these names.
        let mixed = format!("{}{}", &upper[..1], &COMMIT[1..]);
        for rev in [upper.as_str(), mixed.as_str()] {
            assert_eq!(repo.resolve_rev(rev, true).await.unwrap(), None);
            let err = repo.resolve_rev(rev, false).await.unwrap_err();
            assert!(
                matches!(&err, ostrya::Error::RefNotFound(name) if name == rev),
                "`{rev}` was not reported as a missing ref, got {err}"
            );
        }

        // A ref with such a name resolves through the ref file.
        repo.set_ref_immediate(&upper, Some(&a)).await.unwrap();
        assert_eq!(repo.resolve_rev(&upper, false).await.unwrap(), Some(a));

        // The lenient parser reads the content of a ref file. This is the one case
        // where an uppercase checksum resolves.
        std::fs::write(
            root_dir.join("refs/heads/uc"),
            format!("{upper}\n").as_bytes(),
        )
        .unwrap();
        assert_eq!(repo.resolve_rev("uc", false).await.unwrap(), Some(a));
    });
}

#[test]
fn list_refs_refuses_a_symlink_naming_a_directory() {
    // A symlink under refs/ is an alias, whatever its target, so the listing
    // reads it as a ref and does not descend into it. As a result, a link to a
    // directory fails the read with EISDIR. This is the `Listing refs: Is a
    // directory` refusal of the `ostree` command. Without this rule, a self-link
    // recurses without end. Only an out-of-band change can create these links.
    let tmp = TmpDir::new("commit-refs-dirlink");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("deep/nest/ing", Some(&a))
            .await
            .unwrap();
        assert_eq!(repo.list_refs(None).await.unwrap().len(), 1);

        let heads = root_dir.join("refs/heads");
        // A link to the directory that holds it: a walk that follows it has no end.
        std::os::unix::fs::symlink(".", heads.join("selfdir")).unwrap();
        let err = repo.list_refs(None).await.unwrap_err();
        assert!(
            err.to_string().contains("Is a directory"),
            "a self-link is refused, got {err}"
        );

        // A link to another directory, which resolves but names no ref.
        std::fs::remove_file(heads.join("selfdir")).unwrap();
        std::os::unix::fs::symlink("deep", heads.join("dal")).unwrap();
        let err = repo.list_refs(None).await.unwrap_err();
        assert!(
            err.to_string().contains("Is a directory"),
            "a link naming a directory is refused, got {err}"
        );

        // The listing still reads an alias to a ref file through the link.
        std::fs::remove_file(heads.join("dal")).unwrap();
        std::os::unix::fs::symlink("deep/nest/ing", heads.join("al")).unwrap();
        let refs = repo.list_refs(None).await.unwrap();
        assert_eq!(
            refs,
            vec![("al".to_owned(), a), ("deep/nest/ing".to_owned(), a)]
        );
    });
}

/// Asserts that `result` failed with the OS error `errno`.
fn assert_errno(result: ostrya::Result<()>, errno: rustix::io::Errno, what: &str) {
    assert!(
        matches!(&result, Err(ostrya::Error::Io(e)) if e.raw_os_error() == Some(errno.raw_os_error())),
        "{what}: expected {errno:?}, got {result:?}"
    );
}

/// Returns the sorted names in the directory `dir`, or none if `dir` is absent.
fn dir_names(dir: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut names: Vec<String> = entries
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

#[test]
fn ref_writes_place_no_temp_beside_the_target() {
    // A ref write, an alias write, and a detached-metadata write create their
    // temp entry in `tmp/`. If `tmp/` is a regular file, each write fails before
    // it touches `refs/` or `objects/`.
    let tmp = TmpDir::new("commit-temp-in-tmp");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("base", Some(&a)).await.unwrap();
        let fanout = root_dir.join("objects").join(&COMMIT[..2]);
        assert!(!fanout.exists(), "the fanout directory starts absent");

        std::fs::remove_dir_all(root_dir.join("tmp")).unwrap();
        std::fs::write(root_dir.join("tmp"), b"").unwrap();

        let notdir = rustix::io::Errno::NOTDIR;
        assert_errno(
            repo.set_ref_immediate("dir/one", Some(&a)).await,
            notdir,
            "immediate ref write",
        );
        assert_errno(
            repo.set_ref_alias_immediate("dir/alias", "base").await,
            notdir,
            "immediate alias write",
        );
        let guard = repo.begin_update().await.unwrap();
        assert_errno(
            guard.set_ref("dir/two", Some(&a)).await,
            notdir,
            "guarded ref write",
        );
        guard.finish().await.unwrap();
        assert_errno(
            repo.write_commit_detached_metadata(&a, None).await,
            notdir,
            "detached metadata write",
        );

        assert!(
            !root_dir.join("refs/heads/dir").exists(),
            "a failed write creates no ref parent directory"
        );
        assert_eq!(dir_names(&root_dir.join("refs/heads")), ["base"]);
        assert!(
            !fanout.exists(),
            "a failed write creates no fanout directory"
        );
    });
}

#[test]
fn ref_writes_create_a_missing_tmp() {
    // If a repository has no `tmp/`, a ref, alias, or detached-metadata write
    // creates it and leaves it empty. A ref removal does not create it.
    let tmp = TmpDir::new("commit-missing-tmp");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    let tmp_dir = root_dir.join("tmp");
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("gone", Some(&a)).await.unwrap();

        std::fs::remove_dir_all(&tmp_dir).unwrap();
        repo.set_ref_immediate("gone", None).await.unwrap();
        assert!(!tmp_dir.exists(), "a ref removal does not create tmp/");

        repo.set_ref_immediate("dir/one", Some(&a)).await.unwrap();
        assert!(tmp_dir.is_dir());
        assert_eq!(dir_names(&tmp_dir), Vec::<String>::new());

        std::fs::remove_dir_all(&tmp_dir).unwrap();
        repo.set_ref_alias_immediate("dir/alias", "dir/one")
            .await
            .unwrap();
        assert!(tmp_dir.is_dir());
        assert_eq!(dir_names(&tmp_dir), Vec::<String>::new());

        std::fs::remove_dir_all(&tmp_dir).unwrap();
        repo.write_commit_detached_metadata(&a, None).await.unwrap();
        assert!(tmp_dir.is_dir());
        assert_eq!(dir_names(&tmp_dir), Vec::<String>::new());

        assert_eq!(
            repo.list_refs(None).await.unwrap(),
            vec![("dir/alias".to_owned(), a), ("dir/one".to_owned(), a)]
        );
        let meta = root_dir.join("objects").join(loose_path(
            &a,
            ObjectType::CommitMeta,
            RepoMode::Archive,
        ));
        assert_eq!(std::fs::metadata(&meta).unwrap().len(), 0);
    });
}

#[test]
fn a_ref_name_of_name_max_bytes_is_written() {
    // The temp entry in `tmp/` has a name of its own,
    // `.ostrya-ref-<pid>-<n>-XXXXXX`, which does not contain the ref name. As a
    // result, a ref leaf of 255 bytes (the longest file name) can be written and
    // listed.
    let tmp = TmpDir::new("commit-name-max");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    let leaf = "r".repeat(255);
    let alias = "a".repeat(255);
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let name = format!("long/{leaf}");
        let alias_name = format!("long/{alias}");
        repo.set_ref_immediate(&name, Some(&a)).await.unwrap();
        repo.set_ref_alias_immediate(&alias_name, &name)
            .await
            .unwrap();
        assert_eq!(
            repo.list_refs(None).await.unwrap(),
            vec![(alias_name, a), (name, a)]
        );
    });
}

#[test]
fn writes_fail_with_exdev_when_tmp_is_on_another_filesystem() {
    // If `tmp/` is on another file system, the rename of each temp entry fails
    // with EXDEV. The write fails, ostrya removes the temp entry, and the target
    // does not change.
    let tmp = TmpDir::new("commit-tmp-xdev");
    let root_dir = tmp.path().join("repo");
    let a = csum(COMMIT);
    let b = csum(CONTENT);

    // The test needs a second file system. `/dev/shm` is one if the host has it.
    // The test checks the device of `/dev/shm` only if the first write
    // succeeds. A host with a second file system then fails the test, and it
    // cannot pass by a skip.
    let other = Path::new("/dev/shm").join(format!("ostrya-tmp-xdev-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&other);
    if std::fs::create_dir_all(&other).is_err() {
        eprintln!("skipped: /dev/shm is not writable, so no second filesystem is reachable");
        return;
    }
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.set_ref_immediate("kept", Some(&a)).await.unwrap();
        std::fs::remove_dir_all(root_dir.join("tmp")).unwrap();
        std::os::unix::fs::symlink(&other, root_dir.join("tmp")).unwrap();

        let first = repo.set_ref_immediate("kept", Some(&b)).await;
        if first.is_ok() {
            use std::os::unix::fs::MetadataExt;
            let same_device = std::fs::metadata(&other).unwrap().dev()
                == std::fs::metadata(&root_dir).unwrap().dev();
            let _ = std::fs::remove_dir_all(&other);
            assert!(same_device, "a ref was renamed across filesystems");
            eprintln!("skipped: /dev/shm is the repository's own filesystem");
            return;
        }
        let xdev = rustix::io::Errno::XDEV;
        assert_errno(first, xdev, "ref write over an existing ref");
        assert_errno(
            repo.set_ref_immediate("dir/new", Some(&b)).await,
            xdev,
            "ref write of a new ref",
        );
        assert_errno(
            repo.set_ref_alias_immediate("kept", "dir/new").await,
            xdev,
            "alias write",
        );
        assert_errno(
            repo.write_commit_detached_metadata(&a, None).await,
            xdev,
            "detached metadata write",
        );

        assert_eq!(
            repo.list_refs(None).await.unwrap(),
            vec![("kept".to_owned(), a)]
        );
        let meta = root_dir.join("objects").join(loose_path(
            &a,
            ObjectType::CommitMeta,
            RepoMode::Archive,
        ));
        assert!(!meta.exists(), "no detached metadata is written");
        assert_eq!(dir_names(&other), Vec::<String>::new());
    });
    let _ = std::fs::remove_dir_all(&other);
}

#[test]
fn two_transactions_commit_concurrently() {
    // A repository holds concurrent transactions in one process. Two
    // transactions publish their objects and refs independently, and both stay
    // intact.
    let tmp = TmpDir::new("commit-concurrent");
    let root_dir = tmp.path().join("repo");
    let repo = block_on(Repo::create(
        &root_dir,
        CreateOptions::new(RepoMode::BareUser),
    ))
    .unwrap();

    let commit_one = |branch: &'static str, payload: &'static [u8]| {
        let repo = repo.clone();
        move || {
            block_on(async {
                let txn = repo.transaction().await.unwrap();
                let content = txn
                    .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), payload)
                    .await
                    .unwrap();
                let dirmeta_bytes = DirMeta {
                    uid: 0,
                    gid: 0,
                    mode: 0o040755,
                    xattrs: Xattrs::empty(),
                }
                .serialize()
                .unwrap();
                let dirmeta = txn
                    .write_metadata(ObjectType::DirMeta, None, &dirmeta_bytes)
                    .await
                    .unwrap();
                let mut mtree = MutableTree::new();
                mtree.set_metadata_checksum(dirmeta);
                mtree.replace_file("file.txt", content).unwrap();
                let root = txn.write_mtree(&mut mtree).await.unwrap();
                let commit = txn
                    .write_commit(
                        CommitOptions {
                            subject: Some("concurrent".to_owned()),
                            timestamp: Some(1_700_000_000),
                            ..CommitOptions::default()
                        },
                        &root,
                    )
                    .await
                    .unwrap();
                txn.set_ref(branch, Some(&commit));
                txn.commit().await.unwrap();
                commit
            })
        }
    };

    let (a, b) = std::thread::scope(|scope| {
        let ha = scope.spawn(commit_one("branch/a", b"payload a\n"));
        let hb = scope.spawn(commit_one("branch/b", b"payload b\n"));
        (ha.join().unwrap(), hb.join().unwrap())
    });
    assert_ne!(a, b, "distinct trees yield distinct commits");

    block_on(async {
        let repo = Repo::open(&root_dir).await.unwrap();
        assert_eq!(repo.resolve_rev("branch/a", false).await.unwrap(), Some(a));
        assert_eq!(repo.resolve_rev("branch/b", false).await.unwrap(), Some(b));
        // Both commit objects are present and load.
        repo.load_commit(&a).await.unwrap();
        repo.load_commit(&b).await.unwrap();
    });
}

#[test]
fn bare_user_only_commit_matches_the_tool() {
    if !ostree_available() {
        eprintln!(
            "skipping bare_user_only_commit_matches_the_tool: the ostree tool is unavailable"
        );
        return;
    }
    // bare-user-only records only what it can store: no ownership, no xattrs, and
    // permission bits reduced to `perm & 0o755`. This applies to content objects
    // and to directory metadata, and the object names follow from these headers.
    // As a result, a tree with ownership, modes, and xattrs outside what the mode
    // stores produces the object names of the `ostree` command. The fsck of the
    // `ostree` command accepts the result.
    let tmp = TmpDir::new("commit-buo-tool");
    let base = tmp.path();
    build_noncanonical_source(base);

    let port_root = base.join("port");
    block_on(async {
        let repo = Repo::create(&port_root, CreateOptions::new(RepoMode::BareUserOnly))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let mut mtree = MutableTree::new();
        let dfd = std::fs::File::open(base).unwrap();
        txn.write_dfd_to_mtree(dfd.as_fd(), Path::new("src"), &mut mtree, None)
            .await
            .unwrap();
        let root = txn.write_mtree(&mut mtree).await.unwrap();
        let commit = txn
            .write_commit(fixture_commit_options(), &root)
            .await
            .unwrap();
        txn.set_ref("test/main", Some(&commit));
        txn.commit().await.unwrap();
    });

    let tool_root = base.join("tool");
    let tool_arg = format!("--repo={}", tool_root.display());
    run_ostree(&[&tool_arg, "init", "--mode=bare-user-only"]);
    run_ostree(&[
        &tool_arg,
        "commit",
        "--branch=test/main",
        &format!("--subject={SUBJECT}"),
        "--timestamp=@1700000000",
        base.join("src").to_str().unwrap(),
    ]);

    // The commit object holds the metadata of the `ostree` command, so the test
    // compares only the objects that the tree produces.
    assert_eq!(
        tree_object_names(&tool_root),
        tree_object_names(&port_root),
        "tree objects of a non-canonical source in bare-user-only"
    );

    let port_arg = format!("--repo={}", port_root.display());
    run_ostree(&[&port_arg, "fsck"]);
    run_ostree(&[&port_arg, "ls", "-R", "test/main"]);
}

/// Builds a source tree under `base/src` with ownership, modes, and xattrs
/// that `bare-user-only` does not store. The tree holds a world-writable file
/// with an xattr, a setuid file, a world-writable directory, and a symlink.
/// The process owns each entry, so a commit reads a non-zero uid and gid for
/// each.
fn build_noncanonical_source(base: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let set_mode = |p: &Path, m: u32| {
        std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap();
    };
    let src = base.join("src");
    std::fs::create_dir_all(src.join("subdir")).unwrap();
    std::fs::write(src.join("hello.txt"), b"hello ostree\n").unwrap();
    std::fs::write(src.join("exec.sh"), b"#!/bin/sh\necho hi\n").unwrap();
    std::fs::write(src.join("subdir/nested.txt"), b"nested\n").unwrap();
    std::os::unix::fs::symlink("hello.txt", src.join("link")).unwrap();
    rustix::fs::setxattr(
        src.join("hello.txt"),
        "user.demo",
        b"value",
        rustix::fs::XattrFlags::empty(),
    )
    .unwrap();
    set_mode(&src.join("hello.txt"), 0o777);
    set_mode(&src.join("exec.sh"), 0o4755);
    set_mode(&src.join("subdir/nested.txt"), 0o640);
    set_mode(&src.join("subdir"), 0o777);
    set_mode(&src, 0o755);
}

/// Returns the loose-object names of the dirtree, dirmeta, and content
/// objects in a repository, as `<fanout>/<rest>` strings. The set excludes
/// commit objects.
fn tree_object_names(root: &Path) -> HashSet<String> {
    let objects = root.join("objects");
    let mut out = HashSet::new();
    for fanout in std::fs::read_dir(&objects).unwrap().flatten() {
        let prefix = fanout.file_name().to_string_lossy().into_owned();
        for obj in std::fs::read_dir(fanout.path()).unwrap().flatten() {
            let name = obj.file_name().to_string_lossy().into_owned();
            if name.ends_with(".commit") {
                continue;
            }
            out.insert(format!("{prefix}/{name}"));
        }
    }
    out
}

#[test]
fn tool_accepts_a_port_created_commit() {
    if !ostree_available() {
        eprintln!("skipping tool_accepts_a_port_created_commit: the ostree tool is unavailable");
        return;
    }
    let tmp = TmpDir::new("commit-tool");
    let base = tmp.path();
    build_fixture_source(base);
    let root_dir = base.join("repo");
    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let root = ingest_fixture(&txn, base, false).await;
        let commit = txn
            .write_commit(fixture_commit_options(), &root)
            .await
            .unwrap();
        txn.set_ref("test/main", Some(&commit));
        txn.commit().await.unwrap();
    });

    let repo_arg = format!("--repo={}", root_dir.display());
    // The `ostree` commands `fsck`, `show`, and `ls -R` accept the repository of
    // ostrya.
    run_ostree(&[&repo_arg, "fsck"]);
    run_ostree(&[&repo_arg, "show", "test/main"]);
    run_ostree(&[&repo_arg, "ls", "-R", "test/main"]);

    // A checkout reproduces the committed tree. `-U` (user mode) skips the
    // restore of ownership, because that restore needs root for the 0:0 owner of
    // the objects.
    let out = base.join("checkout");
    run_ostree(&[
        &repo_arg,
        "checkout",
        "-U",
        "test/main",
        out.to_str().unwrap(),
    ]);
    assert_eq!(
        std::fs::read(out.join("hello.txt")).unwrap(),
        b"hello ostree\n"
    );
    assert_eq!(
        std::fs::read(out.join("subdir/nested.txt")).unwrap(),
        b"nested\n"
    );
    assert_eq!(
        std::fs::read_link(out.join("link")).unwrap(),
        PathBuf::from("hello.txt")
    );
}

#[test]
fn multi_commit_sizes_are_scoped_to_each_root() {
    // Two different trees committed in one transaction with GENERATE_SIZES. The
    // `ostree.sizes` key of each commit must list exactly the objects that its
    // own root reaches. The key of the second commit must not hold the objects
    // that only the first commit reaches.
    let tmp = TmpDir::new("commit-multi-sizes");
    let base = tmp.path();
    build_flat_source(&base.join("srcA"), "a.txt", b"alpha payload\n");
    build_flat_source(&base.join("srcB"), "b.txt", b"bravo payload\n");
    let root_dir = base.join("repo");

    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let root_a = ingest_flat(&txn, base, "srcA").await;
        let root_b = ingest_flat(&txn, base, "srcB").await;
        assert_ne!(
            root_a.dirtree_checksum(),
            root_b.dirtree_checksum(),
            "the two source trees are distinct"
        );

        let commit_a = txn
            .write_commit(multi_commit_options(), &root_a)
            .await
            .unwrap();
        let commit_b = txn
            .write_commit(multi_commit_options(), &root_b)
            .await
            .unwrap();
        assert_ne!(commit_a, commit_b);
        txn.set_ref("multi/a", Some(&commit_a));
        txn.set_ref("multi/b", Some(&commit_b));
        txn.commit().await.unwrap();

        let sizes_a = decode_sizes_checksums(&repo, &commit_a).await;
        let sizes_b = decode_sizes_checksums(&repo, &commit_b).await;
        let reachable_a = walk_reachable(&repo, "multi/a").await;
        let reachable_b = walk_reachable(&repo, "multi/b").await;

        assert_eq!(
            sizes_a, reachable_a,
            "commit A's ostree.sizes covers exactly A's reachable objects"
        );
        assert_eq!(
            sizes_b, reachable_b,
            "commit B's ostree.sizes covers exactly B's reachable objects"
        );

        // The keys do not leak across commits: an object unique to one tree never
        // appears in the sizes of the other tree.
        let a_only: HashSet<Checksum> = reachable_a.difference(&reachable_b).copied().collect();
        let b_only: HashSet<Checksum> = reachable_b.difference(&reachable_a).copied().collect();
        assert!(
            !a_only.is_empty() && !b_only.is_empty(),
            "the trees have objects unique to each"
        );
        assert!(
            sizes_b.is_disjoint(&a_only),
            "B's sizes must exclude objects unique to A"
        );
        assert!(
            sizes_a.is_disjoint(&b_only),
            "A's sizes must exclude objects unique to B"
        );
    });
}

#[test]
fn multi_commit_sizes_match_separate_tool_commits() {
    // A cross-check of the reachable scope with the `ostree` command. The
    // `ostree` command commits each tree alone into its own repository. Each set
    // of sized-object checksums is equal to the set that the multi-commit
    // transaction of ostrya records for that tree. Object checksums are
    // content-addressed and do not depend on compression, so the sets compare
    // directly.
    if !ostree_available() {
        eprintln!("skipping multi_commit_sizes_match_separate_tool_commits: no ostree tool");
        return;
    }
    let tmp = TmpDir::new("commit-multi-sizes-tool");
    let base = tmp.path();
    build_flat_source(&base.join("srcA"), "a.txt", b"alpha payload\n");
    build_flat_source(&base.join("srcB"), "b.txt", b"bravo payload\n");
    let root_dir = base.join("repo");

    let (port_a, port_b) = block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let root_a = ingest_flat(&txn, base, "srcA").await;
        let root_b = ingest_flat(&txn, base, "srcB").await;
        let commit_a = txn
            .write_commit(multi_commit_options(), &root_a)
            .await
            .unwrap();
        let commit_b = txn
            .write_commit(multi_commit_options(), &root_b)
            .await
            .unwrap();
        txn.commit().await.unwrap();
        (
            decode_sizes_checksums(&repo, &commit_a).await,
            decode_sizes_checksums(&repo, &commit_b).await,
        )
    });

    let tool_a = tool_commit_sizes(&base.join("toolA"), &base.join("srcA"), "a");
    let tool_b = tool_commit_sizes(&base.join("toolB"), &base.join("srcB"), "b");
    assert_eq!(
        port_a, tool_a,
        "A's sized objects match a standalone tool commit of A"
    );
    assert_eq!(
        port_b, tool_b,
        "B's sized objects match a standalone tool commit of B"
    );
}

#[test]
fn incremental_commit_sizes_cover_deduplicated_objects() {
    // An incremental commit into an archive repository that exists. v2 shares
    // hello.txt (an unchanged leaf) and the full keep/ subtree (an unchanged,
    // deduplicated dirtree) with v1. v2 changes change/x.txt. Every object that
    // v2 reaches must appear in the `ostree.sizes` key of v2. This includes the
    // objects that v2 staged and the objects that deduplicated against objects/.
    let tmp = TmpDir::new("commit-incremental-sizes");
    let base = tmp.path();
    build_incremental_source(&base.join("v1"), b"first revision\n");
    build_incremental_source(&base.join("v2"), b"second revision\n");
    let root_dir = base.join("repo");

    block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();

        // v1 in its own transaction, published to objects/.
        let txn = repo.transaction().await.unwrap();
        let root_v1 = ingest_flat(&txn, base, "v1").await;
        let commit_v1 = txn
            .write_commit(multi_commit_options(), &root_v1)
            .await
            .unwrap();
        txn.set_ref("inc/main", Some(&commit_v1));
        txn.commit().await.unwrap();

        // v2 in a new transaction: the shared objects deduplicate against objects/,
        // and the transaction does not stage them again.
        let txn = repo.transaction().await.unwrap();
        let root_v2 = ingest_flat(&txn, base, "v2").await;
        let commit_v2 = txn
            .write_commit(
                CommitOptions {
                    parent: Some(commit_v1),
                    ..multi_commit_options()
                },
                &root_v2,
            )
            .await
            .unwrap();
        txn.set_ref("inc/main", Some(&commit_v2));
        txn.commit().await.unwrap();
        assert_ne!(commit_v1, commit_v2, "v2 is a distinct revision");

        let sizes_v2 = decode_sizes_checksums(&repo, &commit_v2).await;
        let reachable_v2 = walk_reachable(&repo, "inc/main").await;
        assert_eq!(
            sizes_v2, reachable_v2,
            "v2 ostree.sizes must cover every object reachable from v2, \
             including the shared objects that deduplicated against objects/"
        );
    });
}

#[test]
fn incremental_commit_sizes_match_a_tool_incremental_commit() {
    // A cross-check of the incremental scope with the `ostree` command. ostrya
    // and the `ostree` command each commit v1 and then v2 into their own archive
    // repository. The decoded `ostree.sizes` entries of v2 are the same for
    // both. They have the same objects, the same recovered compressed and
    // unpacked sizes, and the same object types.
    //
    // Object checksums are content-addressed, and ostrya compresses to the same
    // bytes as the `ostree` command, so the loose objects and their entries
    // compare directly.
    if !ostree_available() {
        eprintln!(
            "skipping incremental_commit_sizes_match_a_tool_incremental_commit: no ostree tool"
        );
        return;
    }
    let tmp = TmpDir::new("commit-incremental-sizes-tool");
    let base = tmp.path();
    build_incremental_source(&base.join("v1"), b"first revision\n");
    build_incremental_source(&base.join("v2"), b"second revision\n");
    let root_dir = base.join("repo");

    let port_v2 = block_on(async {
        let repo = Repo::create(&root_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let root_v1 = ingest_flat(&txn, base, "v1").await;
        let commit_v1 = txn
            .write_commit(multi_commit_options(), &root_v1)
            .await
            .unwrap();
        txn.commit().await.unwrap();

        let txn = repo.transaction().await.unwrap();
        let root_v2 = ingest_flat(&txn, base, "v2").await;
        let commit_v2 = txn
            .write_commit(
                CommitOptions {
                    parent: Some(commit_v1),
                    ..multi_commit_options()
                },
                &root_v2,
            )
            .await
            .unwrap();
        txn.commit().await.unwrap();
        decode_sizes_entries(&repo, &commit_v2).await
    });

    let tool_v2 = tool_incremental_v2_sizes(&base.join("tool"), &base.join("v1"), &base.join("v2"));
    assert_eq!(
        port_v2, tool_v2,
        "the port's incremental v2 ostree.sizes entries match the tool's"
    );
}

/// Builds a source tree with three entries for the incremental tests. The
/// entries are a shared top-level file `hello.txt`, an unchanged subtree
/// `keep/`, and `change/x.txt` with the content `x`. The permissions are already canonical
/// (file `0o644`, directory `0o755`).
fn build_incremental_source(dir: &Path, x: &[u8]) {
    use std::os::unix::fs::PermissionsExt;
    let set_mode = |p: &Path, m: u32| {
        std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap();
    };
    std::fs::create_dir_all(dir.join("keep")).unwrap();
    std::fs::create_dir_all(dir.join("change")).unwrap();
    std::fs::write(dir.join("hello.txt"), b"hello ostree\n").unwrap();
    std::fs::write(dir.join("keep/stable.txt"), b"stable payload\n").unwrap();
    std::fs::write(dir.join("change/x.txt"), x).unwrap();
    for p in [
        dir.join("hello.txt"),
        dir.join("keep/stable.txt"),
        dir.join("change/x.txt"),
    ] {
        set_mode(&p, 0o644);
    }
    for p in [dir.to_path_buf(), dir.join("keep"), dir.join("change")] {
        set_mode(&p, 0o755);
    }
}

/// Commits `v1` and then `v2` into one new archive repository with the
/// `ostree` command under `--generate-sizes`. Returns the decoded
/// `ostree.sizes` entries of the second commit.
fn tool_incremental_v2_sizes(
    repo_dir: &Path,
    v1: &Path,
    v2: &Path,
) -> HashMap<Checksum, ostrya_core::sizes::SizeEntry> {
    let repo_arg = format!("--repo={}", repo_dir.display());
    run_ostree(&[&repo_arg, "init", "--mode=archive-z2"]);
    let commit = |src: &Path| {
        run_ostree(&[
            &repo_arg,
            "commit",
            "-b",
            "inc",
            "-s",
            "tool",
            "--owner-uid=0",
            "--owner-gid=0",
            "--no-xattrs",
            "--generate-sizes",
            src.to_str().unwrap(),
        ]);
    };
    commit(v1);
    commit(v2);
    block_on(async {
        let repo = Repo::open(repo_dir).await.unwrap();
        let commit = repo.resolve_rev("inc", false).await.unwrap().unwrap();
        decode_sizes_entries(&repo, &commit).await
    })
}

/// Returns the commit options of the multi-commit test: `ostree.sizes` is the
/// only metadata entry, and the timestamp is fixed.
fn multi_commit_options() -> CommitOptions {
    CommitOptions {
        subject: Some("multi".to_owned()),
        timestamp: Some(1_700_000_000),
        ..CommitOptions::default()
    }
}

/// Builds a source directory with one file and canonical permissions (file
/// `0o644`, directory `0o755`). With these permissions, the
/// `CANONICAL_PERMISSIONS` ingest of ostrya and an owner-0:0 commit of the
/// `ostree` command produce the same objects.
fn build_flat_source(dir: &Path, name: &str, content: &[u8]) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::create_dir_all(dir).unwrap();
    let file = dir.join(name);
    std::fs::write(&file, content).unwrap();
    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755)).unwrap();
}

/// Ingests `base/sub` into a new root under `GENERATE_SIZES` with owner 0:0
/// and canonical permissions. Returns the staged root.
async fn ingest_flat(txn: &Transaction, base: &Path, sub: &str) -> RepoTree {
    let flags = CommitModifierFlags::CANONICAL_PERMISSIONS
        | CommitModifierFlags::SKIP_XATTRS
        | CommitModifierFlags::GENERATE_SIZES;
    let mut modifier = CommitModifier::new(flags);
    let mut mtree = MutableTree::new();
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
        .await
        .unwrap();
    txn.write_mtree(&mut mtree).await.unwrap()
}

/// Returns the decoded `ostree.sizes` entries of a commit, keyed by object
/// checksum. Each entry holds the full record (compressed size, unpacked
/// size, object type), so a comparison with the `ostree` command checks the
/// recovered sizes and the listed objects.
async fn decode_sizes_entries(
    repo: &Repo,
    commit: &Checksum,
) -> HashMap<Checksum, ostrya_core::sizes::SizeEntry> {
    let value = repo.load_variant(ObjectType::Commit, commit).await.unwrap();
    let Value::Tuple(fields) = value else {
        panic!("a commit object is a tuple");
    };
    let Value::Array(entries) = &fields[0] else {
        panic!("commit metadata is an a{{sv}} array");
    };
    for entry in entries {
        let Value::Tuple(kv) = entry else { continue };
        let Value::Str(key) = &kv[0] else { continue };
        if key != "ostree.sizes" {
            continue;
        }
        let Value::Variant(boxed) = &kv[1] else {
            panic!("ostree.sizes is a variant");
        };
        let Value::Array(elements) = &boxed.1 else {
            panic!("ostree.sizes wraps an aay array");
        };
        return elements
            .iter()
            .map(|element| {
                let Value::Bytes(bytes) = element else {
                    panic!("each ostree.sizes element is an ay buffer");
                };
                let entry = ostrya_core::sizes::unpack_entry(bytes).unwrap();
                (entry.checksum, entry)
            })
            .collect();
    }
    panic!("commit {} has no ostree.sizes key", commit.to_hex());
}

/// Returns the set of object checksums in the `ostree.sizes` key of a commit.
async fn decode_sizes_checksums(repo: &Repo, commit: &Checksum) -> HashSet<Checksum> {
    decode_sizes_entries(repo, commit)
        .await
        .into_keys()
        .collect()
}

/// Returns the set of object checksums that the root of a commit reaches. The
/// walk uses the public read API: the dirmeta and dirtree of each directory,
/// and each file entry.
async fn walk_reachable(repo: &Repo, rev: &str) -> HashSet<Checksum> {
    let (root, _) = repo.read_commit(rev).await.unwrap();
    let mut set = HashSet::new();
    let mut stack = vec![root];
    while let Some(tree) = stack.pop() {
        set.insert(*tree.dirmeta_checksum());
        set.insert(*tree.dirtree_checksum());
        for entry in tree.read_dir().await.unwrap() {
            match entry {
                TreeEntry::File { checksum, .. } => {
                    set.insert(checksum);
                }
                TreeEntry::Dir { tree, .. } => stack.push(tree),
            }
        }
    }
    set
}

/// Commits `src` alone into a new archive repository with the `ostree`
/// command under `--generate-sizes`. Returns the set of sized-object
/// checksums of that commit.
fn tool_commit_sizes(repo_dir: &Path, src: &Path, branch: &str) -> HashSet<Checksum> {
    let repo_arg = format!("--repo={}", repo_dir.display());
    run_ostree(&[&repo_arg, "init", "--mode=archive-z2"]);
    run_ostree(&[
        &repo_arg,
        "commit",
        "-b",
        branch,
        "-s",
        "tool",
        "--owner-uid=0",
        "--owner-gid=0",
        "--no-xattrs",
        "--generate-sizes",
        src.to_str().unwrap(),
    ]);
    block_on(async {
        let repo = Repo::open(repo_dir).await.unwrap();
        let commit = repo.resolve_rev(branch, false).await.unwrap().unwrap();
        decode_sizes_checksums(&repo, &commit).await
    })
}

fn run_ostree(args: &[&str]) {
    let output = Command::new("ostree")
        .args(args)
        .output()
        .expect("run ostree");
    assert!(
        output.status.success(),
        "ostree {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}