ostrya 0.2.4

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
//! Commit-assembly, refs, and detached-metadata integration tests (Phase 7d).
//!
//! These replay the fixture source tree through the 7a-7d write path and check
//! the commit object byte-for-byte against the tool's fixtures: the sizes-free
//! commit across archive, bare-user, and bare-user-shared (the commit object is
//! mode-independent), the archive `--generate-sizes` commit, the ref files the
//! tool resolves, detached-metadata round-trips, immediate ref writes,
//! concurrent commits, tool acceptance of a port-built repository, and a
//! bare-user-only commit of a non-canonical tree against the tool's own objects.

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 the tool writes for a branch commit:
/// a single `as` entry naming the branch. Reproducing the fixture commit
/// byte-for-byte requires supplying it in the tool's key order.
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()
    }
}

/// Build 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);
}

/// Ingest `base/src` into a fresh root tree, forcing owner 0:0 with canonical
/// permissions so it matches the tool's owner-0:0 fixture. Returns the staged
/// root. Adds `GENERATE_SIZES` when requested.
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()
}

/// The on-disk bytes of a loose object in a repository rooted 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 is mode-independent, so replaying the fixture input
    // through 7a-7d in each mode reproduces the archive fixture's commit bytes,
    // its checksum, and a ref the port 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 a freshly opened one.
            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 sizes fixture's
    // commit bytes and checksum: ostree.sizes covers every object (content and
    // metadata) and is appended after the caller's ref-binding.
    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 size-generation request 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"
    );
    // And it equals the mode-independent fixture commit (no sizes key).
    assert_eq!(commit_with(true), csum(COMMIT));
}

#[test]
fn set_generate_sizes_settles_the_key_in_both_directions() {
    // `set_generate_sizes` answers for the whole transaction: `true` reaches the
    // key where no ingest asked for it, and `false` turns it off again after an
    // ingest under GENERATE_SIZES did.
    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() {
    // Writing an a{sv} and reading it back yields the same value; writing None
    // yields the zero-length "no metadata" file, read 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 is the documented zero-length file, read 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 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 is the 65-byte hex-plus-newline form.
        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() {
    // Every ref mutation syncs the directory holding the ref when `[core] fsync`
    // is set: the write after its rename, the alias write after its rename, and
    // the removal after its unlink. The sync is not observable from outside the
    // process, so this pins the paths it opens -- a parent named wrong fails the
    // open -- and that both settings reach every 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, whose
            // parents sit one, two, and two levels below `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 transaction's ref write 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 tool (2026.1): writing a ref whose file is a relative
    // symlink alias replaces the symlink with a regular ref file and leaves the
    // alias target unchanged, both when committing onto the alias and via
    // `ostree refs --create --force`. See docs/format-reference.md. The port's
    // rename-over-target write reproduces this; this test pins the behavior.
    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, mirroring
        // the tool's relative-symlink alias.
        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));

        // Writing 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 is untouched: 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 a listing runs over the path its PREFIX names: `ENOTDIR` where a
    // component above the last is not a directory, and `Ok` for a ref file, a
    // directory, and a path naming nothing, since a prefix matching no ref
    // enumerates nothing. See docs/format-reference.md, "refs".
    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}"));
        }

        // Through a ref file: the last component under one, an inner component
        // under one, through an alias symlink naming one, and 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 64-character revision is a checksum in lowercase hex alone; an uppercase
    // or mixed-case name of that length is a refspec. Ref file content keeps the
    // lenient reader, so a file holding an uppercase checksum resolves.
    // See docs/format-reference.md, "Revision syntax".
    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, whether or not the store holds
        // the commit.
        assert_eq!(repo.resolve_rev(COMMIT, false).await.unwrap(), Some(a));
        // The uppercase and mixed forms are ref names, and no ref carries them.
        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 carrying 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));

        // Ref file content is read by the lenient parser, the one case an
        // uppercase checksum still 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 it points at, so the listing
    // reads it as a ref rather than descending into it. A link naming a
    // directory therefore fails the read with EISDIR, which is the tool's own
    // `Listing refs: Is a directory` refusal. A self-link is the case that
    // would otherwise recurse without end. Both links are reachable only by
    // out-of-band mutation; see docs/format-reference.md, "refs".
    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 holding it: following 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}"
        );

        // An alias naming a ref file is still read 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)]
        );
    });
}

#[test]
fn two_transactions_commit_concurrently() {
    // The Phase 6 concurrency promise completes: two transactions in one
    // process publish their objects and refs independently, both 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 what it can store -- no ownership, no xattrs, and
    // permission bits reduced to `perm & 0o755` -- for content objects and
    // directory metadata alike, and the identities follow from those headers. A
    // tree whose ownership, modes, and xattrs are all outside what the mode
    // stores therefore produces the tool's own object names, and the tool's fsck
    // 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 carries the tool's own metadata, so the comparison is
    // over the objects the tree itself 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"]);
}

/// Build a source tree under `base/src` whose ownership, modes, and xattrs are
/// all outside what `bare-user-only` stores: a world-writable file carrying an
/// xattr, a setuid file, a world-writable directory, and a symlink. The process
/// owns every 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);
}

/// The loose-object names of the dirtree, dirmeta, and content objects in a
/// repository, as `<fanout>/<rest>` strings. Commit objects are excluded.
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());
    // fsck, show, and a recursive listing all accept the port's repository.
    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
    // ownership restore, which would need root for the objects' 0:0 owner.
    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 distinct trees committed in one transaction with GENERATE_SIZES. Each
    // commit's ostree.sizes must list exactly the objects reachable from its own
    // root, not the union of everything the transaction staged. Under the old
    // whole-transaction scope the second commit's key would also carry the first
    // commit's objects.
    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: objects unique to one tree never
        // appear in the other's sizes.
        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() {
    // The reachable scope is cross-checked against the tool: committing each tree
    // alone into its own repository yields the same set of sized-object checksums
    // the port's multi-commit transaction records for that tree. Object
    // checksums are content-addressed and compression-independent, 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 existing archive repository. v2 shares
    // hello.txt (an unchanged leaf) and the whole keep/ subtree (an unchanged,
    // deduplicated dirtree) with v1, and changes change/x.txt. Every object
    // reachable from v2 -- including the objects that deduplicated against
    // objects/ -- must appear in v2's ostree.sizes, not only the objects v2
    // freshly staged.
    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 fresh transaction: the shared objects now deduplicate against
        // objects/ instead of being freshly staged.
        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() {
    // Cross-check the incremental scope against the tool: the port and the tool
    // each commit v1 then v2 into their own archive repository, and the port's
    // decoded v2 ostree.sizes entries equal the tool's -- same objects, and the
    // same recovered compressed and unpacked sizes and object types. Object
    // checksums are content-addressed and the port's compression matches the
    // tool's, 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"
    );
}

/// A three-entry source tree used by the incremental tests: a shared top-level
/// file `hello.txt`, an unchanged subtree `keep/`, and a `change/x.txt` whose
/// content is `x`. 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);
    }
}

/// Commit `v1` then `v2` into one fresh archive repository with the tool under
/// `--generate-sizes`, then decode the second commit's `ostree.sizes` entries.
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
    })
}

/// Commit options for the multi-commit test: `ostree.sizes` is the sole
/// metadata entry, over a fixed timestamp.
fn multi_commit_options() -> CommitOptions {
    CommitOptions {
        subject: Some("multi".to_owned()),
        timestamp: Some(1_700_000_000),
        ..CommitOptions::default()
    }
}

/// A single-file source directory with already-canonical permissions (file
/// `0o644`, directory `0o755`), so the port's `CANONICAL_PERMISSIONS` ingest and
/// an owner-0:0 tool commit produce identical 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();
}

/// Ingest `base/sub` into a fresh root under `GENERATE_SIZES`, forcing owner
/// 0:0 with 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()
}

/// The decoded `ostree.sizes` entries of a commit, keyed by object checksum.
/// Carries the full record (compressed size, unpacked size, object type), so a
/// comparison against the tool checks the recovered sizes, not only which
/// objects are listed.
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());
}

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

/// The set of object checksums reachable from a commit's root, walked through
/// the public read API: each directory's dirmeta and dirtree, and every 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
}

/// Commit `src` alone into a fresh archive repository with the tool under
/// `--generate-sizes`, then decode the sized-object checksum set from the
/// resulting 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)
    );
}