grit-lib 0.5.18

Core library for the grit Git implementation
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
//! In-process maintenance primitives that embedders such as `jj` use in place
//! of shelling out to `git gc` / `git remote show` / `gix::refs::transaction`.
//!
//! These are the remaining "replaced paths" from the jj spike (PR #9632) that
//! are not transport-shaped:
//!
//! * [`prune_loose_unreachable`] — what `jj util gc` actually needs: delete the
//!   loose objects that are not reachable from a set of roots (full repack /
//!   `pack-refs` are explicitly out of scope).
//! * [`remote_default_branch_local`] — the `git remote show` default-branch
//!   lookup for a local / `file://` remote, via the remote `HEAD` symref.
//! * [`update_refs`] — a thin, compare-and-swap, all-or-nothing batch ref
//!   transaction over the [`crate::refs`] primitives (the in-process equivalent
//!   of what jj built on `gix::refs::transaction`).
//!
//! Scope note: only the local / on-disk path is in scope here. `git://`,
//! `http(s)`, and `ssh` remotes are out of scope and left as TODOs.

use std::collections::{HashSet, VecDeque};
use std::path::Path;
use std::time::SystemTime;

use crate::error::{Error, Result};
use crate::objects::{parse_commit, parse_tag, parse_tree, ObjectId, ObjectKind};
use crate::odb::Odb;
use crate::refs::store::{Expected, RawRef, RefUpdate, RefUpdateFlags};
use crate::refs::{self, Ref};

/// Result of a loose-object prune.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PruneStats {
    /// Number of loose objects deleted.
    pub pruned: usize,
    /// Number of loose objects kept (reachable, or too recent to prune).
    pub kept: usize,
}

/// Delete loose objects in `odb` that are not reachable from `reachable_roots`.
///
/// This is the in-process core of `jj util gc`: it walks the full reachability
/// closure from `reachable_roots` (commits → parents and trees, trees → entries,
/// annotated tags → their target) and then removes every **loose** object whose
/// id is not in that closure. Packed objects are never touched — only loose
/// object files under `objects/??/` are candidates for deletion.
///
/// When `keep_newer_than` is `Some(t)`, a loose object is only deleted if its
/// file modification time is strictly older than `t`. This mirrors Git's
/// `gc.pruneExpire` grace window: recently written objects (which may be the
/// in-progress target of a concurrent operation) are kept even when currently
/// unreachable. A `None` grace window prunes every unreachable loose object
/// regardless of age.
///
/// Submodule (gitlink) tree entries are skipped during the walk: the commit they
/// name lives in another object store.
///
/// The repository hash width is threaded through [`Odb::hash_algo`] (via the
/// 2-char fan-out directory + suffix length), so SHA-256 repositories work.
///
/// # Errors
///
/// Returns an error if a root or a reachable object cannot be read or parsed, or
/// on I/O failure while enumerating or deleting loose object files.
pub fn prune_loose_unreachable(
    odb: &Odb,
    reachable_roots: &[ObjectId],
    keep_newer_than: Option<SystemTime>,
) -> Result<PruneStats> {
    odb.require_files_primary("gc")?;
    let loose = odb.enumerate_local_loose_objects()?;
    prune_unreachable_from(odb, loose, reachable_roots, keep_newer_than)
}

/// [`prune_loose_unreachable`] right after a repack built from the same `reachable_roots`.
///
/// Building that pack already read every reachable object, so when no loose objects
/// remain there is nothing to delete and the reachability walk is skipped.
///
/// # Errors
///
/// Same as [`prune_loose_unreachable`] whenever loose objects remain.
pub(crate) fn prune_loose_unreachable_after_repack(
    odb: &Odb,
    reachable_roots: &[ObjectId],
    keep_newer_than: Option<SystemTime>,
) -> Result<PruneStats> {
    odb.require_files_primary("gc")?;
    let loose = odb.enumerate_local_loose_objects()?;
    if loose.is_empty() {
        return Ok(PruneStats::default());
    }
    prune_unreachable_from(odb, loose, reachable_roots, keep_newer_than)
}

fn prune_unreachable_from(
    odb: &Odb,
    loose: Vec<(ObjectId, std::path::PathBuf)>,
    reachable_roots: &[ObjectId],
    keep_newer_than: Option<SystemTime>,
) -> Result<PruneStats> {
    let mut stats = PruneStats::default();
    let reachable = reachable_closure(odb, reachable_roots)?;

    for (oid, path) in loose {
        if reachable.contains(&oid) {
            stats.kept += 1;
            continue;
        }

        // Respect the grace window: keep objects whose mtime is not strictly
        // older than the cutoff.
        if let Some(cutoff) = keep_newer_than {
            let too_new = std::fs::metadata(&path)
                .and_then(|m| m.modified())
                .map(|mtime| mtime >= cutoff)
                .unwrap_or(false);
            if too_new {
                stats.kept += 1;
                continue;
            }
        }

        match std::fs::remove_file(&path) {
            Ok(()) => stats.pruned += 1,
            // A concurrent prune may have already removed it; treat as pruned.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => stats.pruned += 1,
            Err(e) => return Err(e.into()),
        }
    }

    Ok(stats)
}

/// Object ids named directly by refs (any kind), used as roots for [`prune_loose_unreachable`].
///
/// Includes annotated tag objects, blob/tree tips, and detached-HEAD oids. Does not peel tags to
/// commits only — the reachability walk expands each root through the object graph.
///
/// # Errors
///
/// Propagates ref listing or HEAD read failures.
pub fn collect_referenced_object_roots(git_dir: &Path) -> Result<Vec<ObjectId>> {
    let mut roots = HashSet::new();
    for (_, oid) in refs::list_refs(git_dir, "refs/")? {
        roots.insert(oid);
    }
    let head_path = git_dir.join("HEAD");
    if head_path.is_file() {
        match refs::read_ref_file(&head_path)? {
            Ref::Direct(oid) => {
                roots.insert(oid);
            }
            Ref::Symbolic(_) => {}
        }
    }
    Ok(roots.into_iter().collect())
}

/// Full object closure reachable from maintenance roots (used before repack pack removal).
pub(crate) fn reachability_closure_for_roots(
    odb: &Odb,
    roots: &[ObjectId],
) -> Result<HashSet<ObjectId>> {
    reachable_closure(odb, roots)
}

/// Compute the full object closure reachable from `roots` (commits → parents and
/// tree, trees → entries, tags → target). Mirrors the reachability walk used by
/// the transfer pack builder, but specialized for prune (no exclusion set).
///
/// Blobs named by trees are checked for existence but not read: they link to nothing.
///
/// # Errors
///
/// [`Error::ObjectNotFound`] when a reachable object is missing, and read or parse
/// errors for the objects that are walked.
/// File type bits of a tree entry mode, and the value that marks a directory.
const S_IFMT: u32 = 0o170000;
const S_IFDIR: u32 = 0o040000;

fn reachable_closure(odb: &Odb, roots: &[ObjectId]) -> Result<HashSet<ObjectId>> {
    let mut seen: HashSet<ObjectId> = HashSet::new();
    let mut queue: VecDeque<ObjectId> = VecDeque::new();
    let mut blobs: Vec<ObjectId> = Vec::new();

    for &root in roots {
        if seen.insert(root) {
            queue.push_back(root);
        }
    }

    while let Some(oid) = queue.pop_front() {
        let obj = odb.read(&oid)?;
        match obj.kind {
            ObjectKind::Commit => {
                let commit = parse_commit(&obj.data)?;
                for parent in commit.parents {
                    if seen.insert(parent) {
                        queue.push_back(parent);
                    }
                }
                if seen.insert(commit.tree) {
                    queue.push_back(commit.tree);
                }
            }
            ObjectKind::Tree => {
                for entry in parse_tree(&obj.data)? {
                    // Skip submodule (gitlink) entries.
                    if entry.mode == 0o160000 {
                        continue;
                    }
                    if !seen.insert(entry.oid) {
                        continue;
                    }
                    // Classify by file type bits, as Git does, so non-canonical directory
                    // modes from old trees still count as trees.
                    if entry.mode & S_IFMT == S_IFDIR {
                        queue.push_back(entry.oid);
                    } else {
                        blobs.push(entry.oid);
                    }
                }
            }
            ObjectKind::Tag => {
                let tag = parse_tag(&obj.data)?;
                if seen.insert(tag.object) {
                    queue.push_back(tag.object);
                }
            }
            ObjectKind::Blob => {}
        }
    }

    require_objects_exist(odb, &blobs)?;
    Ok(seen)
}

/// Fail with [`Error::ObjectNotFound`] for the first of `oids` that does not exist.
///
/// Local pack indexes are loaded once and searched directly: going through
/// [`Odb::exists`] or [`Odb::read_info`] per object revalidates the pack directory
/// or probes for a loose file each time, which dominates prune on large trees.
fn require_objects_exist(odb: &Odb, oids: &[ObjectId]) -> Result<()> {
    let indexes =
        crate::pack::read_local_pack_indexes_cached(odb.objects_dir()).unwrap_or_default();
    for oid in oids {
        let packed = indexes.iter().any(|idx| idx.find_position(oid).is_some());
        if !packed && !odb.exists(oid) {
            return Err(Error::ObjectNotFound(oid.to_hex()));
        }
    }
    Ok(())
}

/// Enumerate the loose objects physically present in `odb`'s objects directory,
/// returning each `(oid, path)`. Only the `??/<rest>` fan-out directories are
/// scanned; pack files, `info/`, and any non-object entries are ignored.
///
/// Entries whose names do not form a valid full-length hex OID for the
/// repository's hash algorithm are skipped (e.g. tmp files, the wrong hash
/// width), matching Git's loose-object scan.
/// Return the short name of a local remote's default branch (its `HEAD` symref
/// target), e.g. `main` for a `HEAD` pointing at `refs/heads/main`.
///
/// This is the `git remote show <remote>` default-branch lookup for a local /
/// `file://` remote. It reuses [`crate::remote::list_refs_from_git_dir`]'s symref handling
/// to read the remote `HEAD` and strips the `refs/heads/` prefix from its
/// target. Returns `None` when the remote has no symbolic `HEAD` (e.g. a
/// detached or absent `HEAD`).
///
/// # Errors
///
/// Returns an error if the remote git directory cannot be read.
//
// TODO(phase: remote transports): the `git://`, `http(s)`, and `ssh`
// default-branch lookup (handshake `symref=HEAD:`) is out of scope here.
pub fn remote_default_branch_local(remote_git_dir: &Path) -> Result<Option<String>> {
    let remote_odb =
        Odb::new(&remote_git_dir.join("objects")).with_config_git_dir(remote_git_dir.to_path_buf());

    let entries = crate::remote::list_refs_from_git_dir(
        remote_git_dir,
        Some(&remote_odb),
        &crate::remote::ListRefsOptions {
            symrefs: true,
            ..Default::default()
        },
    )
    .map_err(crate::error::Error::from)?;

    for entry in &entries {
        if entry.name == "HEAD" {
            return Ok(entry
                .symref_target
                .as_ref()
                .map(|t| t.strip_prefix("refs/heads/").unwrap_or(t).to_owned()));
        }
    }

    Ok(None)
}

/// A single ref change in an [`update_refs`] batch transaction.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RefTransactionItem {
    /// Full ref name (e.g. `refs/heads/main`).
    pub name: String,
    /// New value to write, or `None` to delete the ref.
    pub new_oid: Option<ObjectId>,
    /// Compare-and-swap expectation. When `Some`, the ref's current value must
    /// equal this for the item to apply (an `expected_old` of an oid that is not
    /// the current value — including when the ref is absent — fails the batch).
    /// When `None`, the current value is not checked.
    ///
    /// Note: this CAS form expects the ref to currently hold `expected_old`. To
    /// require that a ref be *created* (must not already exist), leave this
    /// `None` — callers that need create-only semantics check existence
    /// themselves; matching jj's transaction model where `None` means "any".
    pub expected_old: Option<ObjectId>,
}

/// Apply a batch of ref create/update/delete operations transactionally with
/// compare-and-swap semantics.
///
/// Every item whose `expected_old` is `Some` is checked against the ref's
/// current value first; if **any** CAS check fails, the entire batch is rejected
/// and **nothing** is written (all-or-nothing). Only once all CAS checks pass
/// are the changes applied:
///
/// * `new_oid = Some(oid)` writes (creates or updates) the ref to `oid` via
///   [`crate::refs::write_ref`].
/// * `new_oid = None` deletes the ref via [`crate::refs::delete_ref`].
///
/// This is a thin transactional wrapper over the [`crate::refs`] primitives,
/// matching the in-process ref-update path jj built on `gix::refs::transaction`.
///
/// # Errors
///
/// Returns [`crate::refs::store::RefStoreError`] for duplicate ref names, CAS failures,
/// lock conflicts, and namespace checks. Propagates other ref I/O errors.
pub fn update_refs(git_dir: &Path, updates: &[RefTransactionItem]) -> Result<()> {
    if updates.is_empty() {
        return Ok(());
    }
    let store_updates: Vec<RefUpdate> = updates
        .iter()
        .map(ref_transaction_item_to_store_update)
        .collect();
    refs::commit_ref_store_batch(git_dir, &store_updates)
}

fn ref_transaction_item_to_store_update(item: &RefTransactionItem) -> RefUpdate {
    let mut flags = RefUpdateFlags::default();
    if item.name == "HEAD" {
        flags.no_deref = true;
    }
    RefUpdate {
        name: item.name.clone(),
        new_value: item.new_oid.map(RawRef::Direct),
        expected: match item.expected_old {
            Some(oid) => Expected::Oid(oid),
            None => Expected::Any,
        },
        reflog: None,
        flags,
    }
}

#[cfg(test)]
mod update_refs_tests {
    use super::*;
    use crate::error::Error;
    use crate::refs::store::RefStoreError;
    use crate::repo::init_repository;
    use tempfile::TempDir;

    fn sample_oid(hex: &str) -> ObjectId {
        hex.parse().expect("oid")
    }

    #[test]
    fn rejects_duplicate_ref_names_in_batch() {
        let tmp = TempDir::new().expect("tempdir");
        let repo = init_repository(
            tmp.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .expect("init");
        let oid = sample_oid("67bf698f3ab735e92fb011a99cff3497c44d30c1");
        let items = vec![
            RefTransactionItem {
                name: "refs/heads/dup".to_owned(),
                new_oid: Some(oid),
                expected_old: None,
            },
            RefTransactionItem {
                name: "refs/heads/dup".to_owned(),
                new_oid: Some(oid),
                expected_old: None,
            },
        ];
        let err = update_refs(&repo.git_dir(), &items).expect_err("duplicate");
        match &err {
            Error::RefStore(RefStoreError::DuplicateUpdate { name }) => {
                assert_eq!(name, "refs/heads/dup");
            }
            other => panic!("expected DuplicateUpdate, got {other}"),
        }
    }

    #[test]
    fn update_refs_typed_errors() {
        let tmp = TempDir::new().expect("tempdir");
        let repo = init_repository(
            tmp.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .expect("init");
        let git_dir = repo.git_dir();
        let c1 = sample_oid("67bf698f3ab735e92fb011a99cff3497c44d30c1");
        let c2 = sample_oid("1111111111111111111111111111111111111111");
        refs::write_ref(&git_dir, "refs/heads/cas", &c2).expect("seed");

        let err = update_refs(
            &git_dir,
            &[RefTransactionItem {
                name: "refs/heads/cas".to_owned(),
                new_oid: Some(c1),
                expected_old: Some(c1),
            }],
        )
        .expect_err("stale cas");
        match &err {
            Error::RefStore(RefStoreError::ExpectedMismatch { name, .. }) => {
                assert_eq!(name, "refs/heads/cas");
            }
            other => panic!("expected ExpectedMismatch, got {other}"),
        }
    }

    #[test]
    fn reftable_cas_rechecked_under_stack_lock() {
        let tmp = TempDir::new().expect("tempdir");
        let repo = init_repository(
            tmp.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Reftable,
        )
        .expect("init");
        let git_dir = repo.git_dir();
        let c1 = sample_oid("67bf698f3ab735e92fb011a99cff3497c44d30c1");
        let c2 = sample_oid("1111111111111111111111111111111111111111");
        crate::refs::write_ref(&git_dir, "refs/heads/locked-cas", &c1).expect("seed");
        crate::refs::write_ref(&git_dir, "refs/heads/locked-cas", &c2).expect("advance");
        let err = update_refs(
            &git_dir,
            &[RefTransactionItem {
                name: "refs/heads/locked-cas".to_owned(),
                new_oid: Some(c1),
                expected_old: Some(c1),
            }],
        )
        .expect_err("stale cas");
        assert!(
            matches!(err, Error::RefStore(RefStoreError::ExpectedMismatch { .. })),
            "{err}"
        );
        assert_eq!(
            crate::refs::resolve_ref(&git_dir, "refs/heads/locked-cas").unwrap(),
            c2
        );
    }

    #[test]
    fn apply_cas_rejects_after_concurrent_packed_delete() {
        let _pause_serial = refs::test_pause_injection_serial_guard();
        use std::path::Path;
        use std::process::Command;
        use std::sync::Arc;
        use std::thread;

        let _pause_scope = refs::ref_store_batch_pause_test_scope();

        fn git(dir: &Path, args: &[&str]) {
            let out = Command::new("git")
                .current_dir(dir)
                .args(args)
                .env("GIT_AUTHOR_NAME", "T")
                .env("GIT_AUTHOR_EMAIL", "t@example.com")
                .env("GIT_COMMITTER_NAME", "T")
                .env("GIT_COMMITTER_EMAIL", "t@example.com")
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_SYSTEM", "/dev/null")
                .output()
                .expect("git");
            assert!(
                out.status.success(),
                "git {:?}: {}",
                args,
                String::from_utf8_lossy(&out.stderr)
            );
        }

        fn rev_parse(repo: &Path, refname: &str) -> ObjectId {
            let hex = Command::new("git")
                .current_dir(repo)
                .args(["rev-parse", refname])
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_SYSTEM", "/dev/null")
                .output()
                .expect("rev-parse")
                .stdout;
            String::from_utf8(hex)
                .expect("utf8")
                .trim()
                .parse()
                .expect("oid")
        }

        let tmp = TempDir::new().expect("tempdir");
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        git(&repo, &["init", "-q", "-b", "main", "."]);
        let git_dir = repo.join(".git");

        std::fs::write(repo.join("f.txt"), "one\n").unwrap();
        git(&repo, &["add", "f.txt"]);
        git(&repo, &["commit", "-q", "-m", "c1"]);
        let c1 = rev_parse(&repo, "HEAD");

        std::fs::write(repo.join("f.txt"), "two\n").unwrap();
        git(&repo, &["add", "f.txt"]);
        git(&repo, &["commit", "-q", "-m", "c2"]);
        let c2 = rev_parse(&repo, "HEAD");

        for name in ["refs/heads/first", "refs/heads/middle", "refs/heads/last"] {
            git(&repo, &["update-ref", name, &c1.to_hex()]);
        }
        git(&repo, &["pack-refs", "--all"]);
        for name in ["first", "middle", "last"] {
            let _ = std::fs::remove_file(git_dir.join(format!("refs/heads/{name}")));
        }

        let gate = refs::new_ref_store_batch_pause_gate();
        refs::set_test_inject_ref_store_batch_pause_after_apply(
            0,
            &git_dir,
            Some(Arc::clone(&gate)),
        );

        let updates = vec![
            RefTransactionItem {
                name: "refs/heads/first".to_owned(),
                new_oid: Some(c2),
                expected_old: Some(c1),
            },
            RefTransactionItem {
                name: "refs/heads/middle".to_owned(),
                new_oid: Some(c2),
                expected_old: Some(c1),
            },
            RefTransactionItem {
                name: "refs/heads/last".to_owned(),
                new_oid: Some(c2),
                expected_old: Some(c1),
            },
        ];

        let git_dir_thread = git_dir.clone();
        let updates_thread = updates.clone();
        let worker = thread::spawn(move || update_refs(&git_dir_thread, &updates_thread));

        let mut paused = gate.wait.lock().expect("lock");
        while !*paused {
            paused = gate.cv.wait(paused).expect("wait");
        }

        git(
            &repo,
            &["update-ref", "-d", "refs/heads/last", &c1.to_hex()],
        );

        *paused = false;
        gate.cv.notify_all();
        drop(paused);

        let err = worker.join().expect("join").expect_err("stale CAS");
        match &err {
            Error::RefStore(RefStoreError::ExpectedMismatch { name, .. }) => {
                assert_eq!(name, "refs/heads/last");
            }
            other => panic!("expected ExpectedMismatch for last ref, got {other}"),
        }
        assert!(crate::refs::resolve_ref(&git_dir, "refs/heads/last").is_err());
        assert_eq!(
            crate::refs::resolve_ref(&git_dir, "refs/heads/first").expect("first"),
            c2
        );

        refs::set_test_inject_ref_store_batch_pause_after_apply(0, &git_dir, None);
    }

    #[test]
    fn unconditional_create_rejects_after_concurrent_packed_parent() {
        let _pause_serial = refs::test_pause_injection_serial_guard();
        use std::path::Path;
        use std::process::Command;
        use std::sync::Arc;
        use std::thread;

        let _pause_scope = refs::ref_store_batch_pause_test_scope();

        fn git(dir: &Path, args: &[&str]) {
            let out = Command::new("git")
                .current_dir(dir)
                .args(args)
                .env("GIT_AUTHOR_NAME", "T")
                .env("GIT_AUTHOR_EMAIL", "t@example.com")
                .env("GIT_COMMITTER_NAME", "T")
                .env("GIT_COMMITTER_EMAIL", "t@example.com")
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_SYSTEM", "/dev/null")
                .output()
                .expect("git");
            assert!(
                out.status.success(),
                "git {:?}: {}",
                args,
                String::from_utf8_lossy(&out.stderr)
            );
        }

        fn rev_parse(repo: &Path, refname: &str) -> ObjectId {
            let hex = Command::new("git")
                .current_dir(repo)
                .args(["rev-parse", refname])
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_SYSTEM", "/dev/null")
                .output()
                .expect("rev-parse")
                .stdout;
            String::from_utf8(hex)
                .expect("utf8")
                .trim()
                .parse()
                .expect("oid")
        }

        let tmp = TempDir::new().expect("tempdir");
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        git(&repo, &["init", "-q", "-b", "main", "."]);
        let git_dir = repo.join(".git");

        std::fs::write(repo.join("f.txt"), "one\n").unwrap();
        git(&repo, &["add", "f.txt"]);
        git(&repo, &["commit", "-q", "-m", "c1"]);
        let c1 = rev_parse(&repo, "HEAD");

        let gate = refs::new_ref_store_batch_pause_gate();
        refs::set_test_inject_ref_store_batch_pause_after_apply(
            0,
            &git_dir,
            Some(Arc::clone(&gate)),
        );

        let updates = vec![
            RefTransactionItem {
                name: "refs/heads/one".to_owned(),
                new_oid: Some(c1),
                expected_old: None,
            },
            RefTransactionItem {
                name: "refs/heads/two".to_owned(),
                new_oid: Some(c1),
                expected_old: None,
            },
            RefTransactionItem {
                name: "refs/heads/conflict/child".to_owned(),
                new_oid: Some(c1),
                expected_old: None,
            },
        ];

        let git_dir_thread = git_dir.clone();
        let updates_thread = updates.clone();
        let worker = thread::spawn(move || update_refs(&git_dir_thread, &updates_thread));

        let mut paused = gate.wait.lock().expect("lock");
        while !*paused {
            paused = gate.cv.wait(paused).expect("wait");
        }

        git(&repo, &["update-ref", "refs/heads/conflict", &c1.to_hex()]);
        git(&repo, &["pack-refs", "--all"]);

        *paused = false;
        gate.cv.notify_all();
        drop(paused);

        let err = worker
            .join()
            .expect("join")
            .expect_err("namespace conflict on child");
        assert!(
            err.to_string().contains("namespace conflict")
                || err.to_string().contains("cannot lock ref"),
            "{err}"
        );
        assert!(crate::refs::resolve_ref(&git_dir, "refs/heads/conflict").is_ok());
        assert!(crate::refs::resolve_ref(&git_dir, "refs/heads/conflict/child").is_err());

        refs::set_test_inject_ref_store_batch_pause_after_apply(0, &git_dir, None);
    }
}

#[cfg(test)]
mod prune_walk_tests {
    use super::*;
    use crate::maintenance::{repack, RepackOptions};
    use crate::repo::init_repository;
    use tempfile::TempDir;

    #[test]
    fn prune_checks_packed_blobs_without_per_object_lookups() {
        let tmp = TempDir::new().expect("tempdir");
        let repo = init_repository(
            tmp.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .expect("init");
        let odb = repo.odb();
        let mut tree = Vec::new();
        for i in 0..50 {
            let blob = odb
                .write(ObjectKind::Blob, format!("blob {i}\n").as_bytes())
                .expect("blob");
            tree.extend_from_slice(format!("100644 f{i:02}\0").as_bytes());
            tree.extend_from_slice(blob.as_bytes());
        }
        let tree = odb.write(ObjectKind::Tree, &tree).expect("tree");
        let commit = format!(
            "tree {tree}\nauthor A <a@example.com> 1 +0000\ncommitter A <a@example.com> 1 +0000\n\nm\n"
        );
        let commit = odb
            .write(ObjectKind::Commit, commit.as_bytes())
            .expect("commit");
        std::fs::write(
            repo.git_dir().join("refs/heads/main"),
            format!("{}\n", commit.to_hex()),
        )
        .expect("ref");
        repack(&repo, &RepackOptions::default()).expect("repack");
        assert!(odb
            .enumerate_local_loose_objects()
            .expect("loose")
            .is_empty());

        odb.reset_exists_probe();
        let stats = prune_loose_unreachable(odb, &[commit], None).expect("prune");
        assert_eq!(stats, PruneStats::default());
        assert_eq!(
            odb.exists_probe_count(),
            0,
            "packed blobs must be checked against the pack indexes, not one lookup each"
        );
    }
}