Skip to main content

grit_lib/odb/
mod.rs

1//! Loose object database: reading and writing zlib-compressed Git objects.
2//!
3//! Git stores objects as files under `<git-dir>/objects/<xx>/<38-hex-chars>`,
4//! where the path is derived from the SHA-1 digest. Each file is a zlib-
5//! compressed byte sequence whose decompressed form is:
6//!
7//! ```text
8//! "<type> <size>\0<data>"
9//! ```
10//!
11//! # Usage
12//!
13//! Files-backed repositories (default):
14//!
15//! ```no_run
16//! use std::path::Path;
17//! use grit_lib::objects::odb::Odb;
18//!
19//! let odb = Odb::new(Path::new(".git/objects"));
20//! ```
21//!
22//! Custom primary store — see [`RepositoryOptions::with_object_store`](crate::environment::RepositoryOptions::with_object_store);
23//! read layers and alternates — see [`OdbBuilder`] and [`RepositoryOptions::with_odb_builder`](crate::environment::RepositoryOptions::with_odb_builder).
24
25pub mod builder;
26mod commit;
27mod peel;
28mod primary;
29mod read_store;
30pub mod store;
31mod stream;
32mod tree;
33
34pub(crate) use primary::PrimaryStore;
35pub(crate) use stream::deflate_stream_to_writer;
36
37use primary::OpenPrimary;
38
39#[doc(inline)]
40pub use builder::OdbBuilder;
41pub(crate) use builder::PruneTarget;
42pub(crate) use peel::peel_stored_tag_target_in;
43
44pub(crate) use store::loose::{
45    decompress_zlib_loose_bytes, for_each_loose_object_id, for_each_object_id_in_fanout_dir,
46    parse_object_bytes, read_loose_object_info,
47};
48#[doc(inline)]
49pub use store::LooseStore;
50pub use store::{CompositeStore, FilesSource, ObjectStream};
51#[doc(inline)]
52pub use store::{MemoryStore, ObjectStore, WritableObjectStore};
53
54use crate::error::ObjectError;
55use crate::git_path::CanonicalizeExt;
56use std::collections::{HashMap, HashSet};
57use std::fs;
58use std::hash::{Hash, Hasher};
59use std::ops::ControlFlow;
60use std::path::{Path, PathBuf};
61#[cfg(test)]
62use std::sync::atomic::AtomicUsize;
63use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
64use std::sync::{Arc, Mutex, OnceLock, RwLock};
65
66use crate::config::ConfigSet;
67use crate::diagnostics::NullDiagnostics;
68use crate::error::{Error, Result};
69use crate::hash;
70use crate::midx::validate_midx_referenced_packs_with_diagnostics;
71use crate::objects::{
72    oid_hash_set, HashAlgo, Object, ObjectId, ObjectInfo, ObjectKind, OidHashMap, OidHashSet,
73};
74use crate::pack;
75use crate::pack_store::PackStore;
76use crate::repo::error::FilesOnlyOperation;
77use crate::repo::RepositoryError;
78use filetime::{set_file_mtime, FileTime};
79use flate2::Compression;
80
81pub(crate) use store::BoundedRead;
82use store::{LocalSizedRead, PackedObjects};
83
84/// How repack/gc retains unreachable objects stored only in packs about to be deleted.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub(crate) enum UnreachablePackRetention {
87    /// Keep every unreachable object (matches `git repack -ad` with `-k` / `gc.pruneExpire=never`).
88    KeepAll,
89    /// Keep unreachable objects whose pack mtime is not strictly older than the cutoff.
90    KeepGraceProtected(std::time::SystemTime),
91    /// Drop unreachable objects when their pack is removed (immediate prune).
92    DropAll,
93}
94
95/// Pack paths and `.keep` status captured once at repack inventory.
96pub(crate) struct RepackPackInventorySnapshot {
97    pub pack_paths: HashSet<PathBuf>,
98    pub kept_at_inventory: HashSet<PathBuf>,
99}
100
101type MemOdbOverlayStore = Arc<RwLock<Option<Arc<MemoryStore>>>>;
102
103/// Cached alternate [`CompositeStore`] keyed by file/env/submodule alternate state.
104struct AlternateSourcesCache {
105    file_generation: u64,
106    env_fingerprint: u64,
107    submodule_generation: u64,
108    sources: Option<Arc<CompositeStore>>,
109}
110
111struct AlternateSourcesKey {
112    file_generation: u64,
113    env_fingerprint: u64,
114    submodule_generation: u64,
115}
116
117/// Cached `info/alternates` chain for one [`Odb`] (generation bumps on invalidation/reload).
118struct FileAlternatesCache {
119    generation: u64,
120    snapshot: Option<Arc<Vec<PathBuf>>>,
121}
122
123/// Options for [`Odb::write_with`].
124#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
125pub struct WriteOptions {
126    /// When set, do not touch mtimes on existing objects (Git `WRITE_OBJECT_SILENT`).
127    pub silent: bool,
128    /// When set, skip the full `Odb::exists` scan (packs/alternates) and only
129    /// test for a loose file in this repository's object directory before writing.
130    ///
131    /// Bulk staging of new worktree blobs uses this so each insert does not walk
132    /// every pack on a miss.
133    pub assume_loose_only_existence: bool,
134    /// When set, skip existence probes and write when the loose path is absent
135    /// (bulk add of all-new blobs). [`Self::freshen_existing`] still applies.
136    pub trust_new_loose: bool,
137    /// When set, skip `create_dir_all` on the loose prefix directory (call
138    /// [`Odb::ensure_all_loose_prefix_dirs`] first).
139    pub loose_prefix_dirs_ready: bool,
140    /// When set and no loose copy exists in this repository's object directory, freshen
141    /// a copy stored in a local pack (promisor packs included) or in an alternate object
142    /// directory, and skip the write when that succeeds (Git freshens before writing).
143    ///
144    /// Packs are looked up in the cached pack listing; a miss does not rescan
145    /// `objects/pack/`, so many probes for new objects stay cheap. An object stored only
146    /// where it cannot be freshened (a cruft pack) is still written loose. Like the pack
147    /// hits of [`Self::assume_loose_only_existence`], the copy is freshened even when
148    /// [`Self::silent`] is set.
149    pub freshen_existing: bool,
150}
151
152/// [`WriteOptions`] for parallel staging of new worktree blobs (bulk `git add`).
153///
154/// Only a loose copy stops the write; use [`Odb::bulk_stage_write_options`] for staging
155/// content that may already be packed.
156pub const BULK_NEW_LOOSE_WRITE: WriteOptions = WriteOptions {
157    assume_loose_only_existence: true,
158    trust_new_loose: true,
159    silent: false,
160    loose_prefix_dirs_ready: true,
161    freshen_existing: false,
162};
163
164/// Parallel restage of tracked modifications (objects may already be loose or packed).
165pub const BULK_TRACKED_RESTAGE_LOOSE_WRITE: WriteOptions = WriteOptions {
166    assume_loose_only_existence: true,
167    trust_new_loose: false,
168    silent: false,
169    loose_prefix_dirs_ready: true,
170    freshen_existing: false,
171};
172
173/// True when `oid` is stored as a loose object or in a **non-promisor** local pack.
174///
175/// Non-promisor pack membership is checked before loose storage so packed objects
176/// avoid a per-probe loose `stat` on the hot path. A non-promisor pack hit already
177/// implies the object is materialized locally, including when a loose copy also exists.
178fn exists_materialized_in_objects_dir(objects_dir: &Path, oid: &ObjectId) -> bool {
179    store::local_object_materialized(objects_dir, oid)
180}
181
182/// The oids from `oids` for which `keep` answers `Ok(true)`, stopping at the first error.
183fn filter_oids(
184    oids: impl IntoIterator<Item = ObjectId>,
185    mut keep: impl FnMut(&ObjectId) -> Result<bool>,
186) -> Result<Vec<ObjectId>> {
187    oids.into_iter()
188        .filter_map(|oid| keep(&oid).map(|k| k.then_some(oid)).transpose())
189        .collect()
190}
191
192fn objects_dir_has_pack_index_files(objects_dir: &Path) -> bool {
193    let pack_dir = objects_dir.join("pack");
194    let Ok(entries) = fs::read_dir(pack_dir) else {
195        return false;
196    };
197    entries
198        .filter_map(|e| e.ok())
199        .any(|ent| ent.path().extension().is_some_and(|ext| ext == "idx"))
200}
201
202/// A loose-object database rooted at a given `objects/` directory.
203///
204/// # Examples
205///
206/// ```
207/// use grit_lib::objects::{ObjectKind, odb::Odb};
208/// use std::path::Path;
209///
210/// # fn main() -> grit_lib::error::Result<()> {
211/// let dir = tempfile::tempdir()?;
212/// let objects = dir.path().join("objects");
213/// std::fs::create_dir_all(&objects)?;
214/// let odb = Odb::new(&objects);
215/// let oid = odb.write(ObjectKind::Blob, b"hello")?;
216/// let obj = odb.read(&oid)?;
217/// assert_eq!(obj.data, b"hello");
218/// # Ok(())
219/// # }
220/// ```
221#[derive(Clone)]
222pub struct Odb {
223    objects_dir: PathBuf,
224    /// Work tree root for resolving relative alternate env paths.
225    work_tree: Option<PathBuf>,
226    /// Embedded submodule object stores registered for this read pass (Git `register_all_submodule_sources`).
227    submodule_alternate_dirs: Arc<Mutex<Vec<PathBuf>>>,
228    /// When set, used to read `core.multiPackIndex` (and related) for MIDX-backed object reads.
229    config_git_dir: Option<PathBuf>,
230    /// Cache for `core.multiPackIndex` — populated on first lookup.
231    ///
232    /// Reading this config requires loading the system/global/local config cascade and reparsing
233    /// every file; the value cannot change for a process that has opened a single repository, so
234    /// caching it here avoids re-loading the cascade for every object read.
235    core_multi_pack_index_cache: Arc<OnceLock<bool>>,
236    /// Whether `objects/pack` contains at least one `.idx` file (directory probe, once per Odb).
237    local_pack_indexes_seen: Arc<OnceLock<bool>>,
238    /// `info/alternates` chain resolved lazily; generation bumps on invalidation/reload.
239    file_alternate_dirs_cache: Arc<RwLock<FileAlternatesCache>>,
240    #[cfg(test)]
241    exists_probe: Arc<AtomicUsize>,
242    #[cfg(test)]
243    pub(crate) hot_path_test_metrics: Arc<crate::hot_path_test_metrics::HotPathTestMetrics>,
244    /// Explicit env alternates from [`Self::with_env_alternate_dirs`] (tests / callers); empty uses lazy env read.
245    env_alternate_dirs: Vec<PathBuf>,
246    /// Lazily parsed `GIT_ALTERNATE_OBJECT_DIRECTORIES` (first alternate lookup only).
247    env_alternate_lazy: Arc<OnceLock<Arc<Vec<PathBuf>>>>,
248    /// When `Some`, object writes are redirected into this in-memory overlay instead of being
249    /// persisted to the loose store (Git's tmp-objdir). Reads consult the overlay first. This
250    /// mirrors `git merge-tree --quiet`, which performs a full merge but must leave the object
251    /// database untouched (no new loose objects).
252    mem_overlay: MemOdbOverlayStore,
253    /// Whether [`Self::enable_mem_overlay`] activated the in-memory overlay (avoids locking on reads).
254    mem_overlay_active: Arc<AtomicBool>,
255    /// The store reads and writes go to first: the lazily opened [`FilesSource`] for
256    /// [`Self::objects_dir`], or the store from [`OdbBuilder::primary`].
257    primary: PrimaryStore,
258    /// Alternate object dirs as a [`CompositeStore`] (generation-bumped with file alternates).
259    alternate_sources_cache: Arc<RwLock<AlternateSourcesCache>>,
260    /// Whether MIDX pack validation has run for this [`Odb`] (Git warns once per process).
261    midx_packs_validated: Arc<OnceLock<()>>,
262    /// The repository's object hash algorithm (`extensions.objectformat`),
263    /// detected lazily from the config and cached. Determines the hash used
264    /// when writing objects. Defaults to SHA-1 when no config is available.
265    hash_algo_cache: Arc<OnceLock<HashAlgo>>,
266    /// Zlib level for loose-object writes, resolved from config and cached.
267    loose_zlib_cache: Arc<OnceLock<Compression>>,
268    /// Zlib level for pack-objects output, resolved from config and cached.
269    pack_zlib_cache: Arc<OnceLock<Compression>>,
270    /// `core.bigFileThreshold`, resolved from config and cached.
271    big_file_threshold_cache: Arc<OnceLock<u64>>,
272    /// Shared with [`crate::repo::Repository`] so config is loaded once per open handle.
273    shared_config_state: Option<crate::repo::RepositoryConfigSnapshot>,
274    /// One-time sync of `core.deltaBaseCacheLimit` into the process-wide pack delta-base LRU.
275    delta_base_cache_sync: Arc<OnceLock<()>>,
276    /// Environment paired with [`Self::shared_config_state`] for repository-scoped config cache.
277    shared_environment: Option<Arc<crate::environment::Environment>>,
278    /// Fallback when [`Self::shared_environment`] is unset (repo-local config only).
279    empty_config_env: Arc<OnceLock<crate::environment::Environment>>,
280    /// Pack files whose mtimes were already bumped for object freshening on this [`Odb`]
281    /// (Git's `packed_git->freshened`: at most one `utimensat` per pack per process).
282    freshened_packs: Arc<Mutex<HashSet<PathBuf>>>,
283    /// Repository-scoped pack/MIDX read caches (shared by [`Odb`] clones).
284    pack_store: Arc<PackStore>,
285    /// Cached [`PackStore`] handles for alternate object directories (lazy).
286    alternate_pack_stores: Arc<Mutex<HashMap<PathBuf, Arc<PackStore>>>>,
287    /// Bumps when [`Self::register_submodule_object_directories_from_index`] repopulates submodule sources.
288    submodule_sources_generation: Arc<AtomicU64>,
289    /// Read-only layers from [`OdbBuilder::push_read_source`], after primary, before alternates.
290    extra_read_sources: Vec<Arc<dyn ObjectStore>>,
291    /// When false, alternate object directories are not consulted ([`OdbBuilder::alternates`]).
292    alternates_enabled: bool,
293    /// Commit-graph supplied by [`OdbBuilder::commit_graph`]; used instead of any on-disk graph.
294    attached_commit_graph: Option<Arc<crate::commit_graph_file::CommitGraphChain>>,
295    /// Avoid re-reading the same loose object repeatedly during one repository session.
296    session_loose_reads: Arc<std::sync::Mutex<SessionLooseReads>>,
297    /// Parsed or raw trees reused for the lifetime of this [`Odb`] handle (Git object cache).
298    session_tree_entries: Arc<Mutex<SessionTreeEntries>>,
299    /// Negative loose-read caches keyed by `objects/` directory (shared across [`LooseStore`] opens).
300    loose_negative_caches: Arc<Mutex<HashMap<PathBuf, store::SharedLooseNegativeCache>>>,
301}
302
303/// Largest loose object [`Odb::read_unless_larger`] keeps in the session read cache. Its callers
304/// (checkout) promise bounded memory, so a cache of up to a few hundred entries must not be
305/// able to pin hundreds of near-limit blobs.
306const SESSION_BOUNDED_LOOSE_CACHE_MAX: usize = 64 * 1024;
307
308/// Largest blob a general [`Odb::read`] keeps in the session read cache. Tiny blobs that are
309/// read again and again (attributes, submodule and mailmap files) stay cached, while the
310/// blobs a diff or merge reads once each pin at most this much per cache entry.
311const SESSION_READ_BLOB_CACHE_MAX: usize = 4 * 1024;
312
313/// Objects the session read cache holds before it starts over.
314const SESSION_LOOSE_CACHE_MAX_ENTRIES: usize = 256;
315
316/// Payload bytes the session read cache holds before it starts over, so no mix of reads can
317/// make it pin more than this however large the objects are.
318const SESSION_LOOSE_CACHE_MAX_BYTES: usize = 16 * 1024 * 1024;
319
320/// Recently read objects reused within one [`Odb`] session, bounded by entry count and by
321/// total payload bytes. When either bound would be exceeded the cache starts over.
322#[derive(Default)]
323struct SessionLooseReads {
324    objects: OidHashMap<Object>,
325    bytes: usize,
326}
327
328impl SessionLooseReads {
329    // Every session-cache hit calls this; without the hint, codegen-unit partitioning
330    // decides whether it is inlined into the read path.
331    #[inline]
332    fn get(&self, oid: &ObjectId) -> Option<&Object> {
333        self.objects.get(oid)
334    }
335
336    fn insert(&mut self, oid: ObjectId, obj: &Object) {
337        let len = obj.data.len();
338        if len > SESSION_LOOSE_CACHE_MAX_BYTES {
339            return;
340        }
341        if self.objects.len() > SESSION_LOOSE_CACHE_MAX_ENTRIES
342            || self.bytes.saturating_add(len) > SESSION_LOOSE_CACHE_MAX_BYTES
343        {
344            self.objects.clear();
345            self.bytes = 0;
346        }
347        if let Some(old) = self.objects.insert(oid, obj.clone()) {
348            self.bytes = self.bytes.saturating_sub(old.data.len());
349        }
350        self.bytes += len;
351    }
352
353    #[cfg(test)]
354    fn is_empty(&self) -> bool {
355        self.objects.is_empty()
356    }
357}
358
359/// A tree held by [`SessionTreeEntries`]: parsed for callers that keep owned entries, or the
360/// raw payload for read-only walks that borrow names straight from it.
361#[derive(Clone)]
362pub(crate) enum SessionTree {
363    /// Entries parsed by [`Odb::cached_tree_entries`].
364    Parsed(Arc<Vec<crate::objects::TreeEntry>>),
365    /// The tree object's payload, as read by [`Odb::cached_tree_for_walk`].
366    Raw(Arc<Vec<u8>>),
367}
368
369impl SessionTree {
370    /// Approximate heap bytes a parsed entry costs (struct plus its name allocation).
371    const PARSED_ENTRY_BYTES: usize = 80;
372
373    fn cost(&self) -> usize {
374        match self {
375            Self::Parsed(entries) => entries.len().saturating_mul(Self::PARSED_ENTRY_BYTES),
376            Self::Raw(data) => data.len(),
377        }
378    }
379}
380
381/// Recently read trees for [`Odb::cached_tree_entries`] and [`Odb::cached_tree_for_walk`],
382/// bounded by their approximate size.
383#[derive(Default)]
384struct SessionTreeEntries {
385    trees: OidHashMap<SessionTree>,
386    bytes: usize,
387}
388
389impl SessionTreeEntries {
390    /// Approximate bytes kept before the cache starts over; a bigger tree is never kept. A few
391    /// MiB is enough for the trees a diff of neighbouring commits revisits, without growing
392    /// with history size.
393    const BYTE_BUDGET: usize = (1 << 16) * SessionTree::PARSED_ENTRY_BYTES;
394
395    fn insert(&mut self, oid: ObjectId, tree: SessionTree) {
396        let cost = tree.cost();
397        if cost > Self::BYTE_BUDGET {
398            return;
399        }
400        if let Some(old) = self.trees.remove(&oid) {
401            self.bytes -= old.cost();
402        }
403        if self.bytes + cost > Self::BYTE_BUDGET {
404            self.trees.clear();
405            self.bytes = 0;
406        }
407        self.bytes += cost;
408        self.trees.insert(oid, tree);
409    }
410}
411
412#[cfg(test)]
413mod session_tree_entries_tests {
414    use super::*;
415    use crate::objects::TreeEntry;
416
417    fn tree(entries: usize) -> SessionTree {
418        let entry = TreeEntry {
419            mode: 0o100644,
420            name: b"f".to_vec(),
421            oid: ObjectId::zero(),
422        };
423        SessionTree::Parsed(Arc::new(vec![entry; entries]))
424    }
425
426    fn raw(bytes: usize) -> SessionTree {
427        SessionTree::Raw(Arc::new(vec![0u8; bytes]))
428    }
429
430    fn oid(n: u8) -> ObjectId {
431        ObjectId::from_bytes(&[n; 20]).expect("oid")
432    }
433
434    const ENTRY_BUDGET: usize = SessionTreeEntries::BYTE_BUDGET / SessionTree::PARSED_ENTRY_BYTES;
435
436    #[test]
437    fn cache_starts_over_when_the_budget_is_exceeded() {
438        let mut cache = SessionTreeEntries::default();
439        let half = ENTRY_BUDGET / 2;
440        cache.insert(oid(1), tree(half));
441        cache.insert(oid(2), tree(half));
442        assert_eq!(cache.bytes, SessionTreeEntries::BYTE_BUDGET);
443        assert_eq!(cache.trees.len(), 2);
444
445        cache.insert(oid(3), tree(1));
446        assert_eq!(cache.trees.len(), 1);
447        assert!(cache.trees.contains_key(&oid(3)));
448        assert_eq!(cache.bytes, SessionTree::PARSED_ENTRY_BYTES);
449
450        cache.insert(oid(4), tree(ENTRY_BUDGET + 1));
451        assert!(
452            !cache.trees.contains_key(&oid(4)),
453            "an oversized tree is not cached"
454        );
455        assert!(cache.trees.contains_key(&oid(3)));
456        assert!(cache.bytes <= SessionTreeEntries::BYTE_BUDGET);
457    }
458
459    #[test]
460    fn raw_trees_count_their_payload_bytes() {
461        let mut cache = SessionTreeEntries::default();
462        cache.insert(oid(1), raw(1000));
463        cache.insert(oid(2), tree(10));
464        assert_eq!(cache.bytes, 1000 + 10 * SessionTree::PARSED_ENTRY_BYTES);
465
466        cache.insert(oid(3), raw(SessionTreeEntries::BYTE_BUDGET + 1));
467        assert!(
468            !cache.trees.contains_key(&oid(3)),
469            "an oversized payload is not cached"
470        );
471        assert_eq!(cache.trees.len(), 2);
472    }
473
474    #[test]
475    fn replacing_a_tree_releases_its_old_cost() {
476        let mut cache = SessionTreeEntries::default();
477        cache.insert(oid(1), raw(4000));
478        cache.insert(oid(1), tree(2));
479        assert_eq!(cache.trees.len(), 1);
480        assert_eq!(cache.bytes, 2 * SessionTree::PARSED_ENTRY_BYTES);
481        assert!(matches!(
482            cache.trees.get(&oid(1)),
483            Some(SessionTree::Parsed(_))
484        ));
485    }
486}
487
488const _: () = {
489    fn assert_send_sync<T: Send + Sync>() {}
490    let _ = assert_send_sync::<Odb>;
491};
492
493impl std::fmt::Debug for Odb {
494    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495        f.debug_struct("Odb")
496            .field("objects_dir", &self.objects_dir)
497            .field("work_tree", &self.work_tree)
498            .field("submodule_alternate_dirs", &"<mutex>")
499            .field("config_git_dir", &self.config_git_dir)
500            .finish()
501    }
502}
503
504/// Resolve the repository hash algorithm from `extensions.objectformat` in `git_dir`'s config.
505///
506/// Uses the same config parser as [`Odb::hash_algo`], including case-insensitive section and
507/// key names. Defaults to [`HashAlgo::Sha1`] when the extension is absent or unreadable.
508#[must_use]
509pub fn hash_algo_for_git_dir(env: &crate::environment::Environment, git_dir: &Path) -> HashAlgo {
510    ConfigSet::load(
511        env,
512        Some(git_dir),
513        &crate::config::LoadConfigOptions::standard(env, Some(git_dir)),
514    )
515    .ok()
516    .and_then(|cfg| cfg.value("extensions.objectformat"))
517    .and_then(|v| HashAlgo::from_name(&v))
518    .unwrap_or(HashAlgo::Sha1)
519}
520
521/// Like [`hash_algo_for_git_dir`] but takes an `objects/` directory path.
522#[must_use]
523pub fn hash_algo_for_objects_dir(
524    env: &crate::environment::Environment,
525    objects_dir: &Path,
526) -> HashAlgo {
527    objects_dir
528        .parent()
529        .map(|d| hash_algo_for_git_dir(env, d))
530        .unwrap_or(HashAlgo::Sha1)
531}
532
533impl Odb {
534    /// Create an [`Odb`] pointing at the given `objects/` directory.
535    ///
536    /// The directory does not need to exist yet; it will be created on the
537    /// first write operation. Does not read `GIT_ALTERNATE_OBJECT_DIRECTORIES`;
538    /// use [`Self::env_alternate_dirs_from_var`] and [`Self::with_env_alternate_dirs`]
539    /// (or open via [`crate::repo::Repository`], which resolves env alternates lazily on first use).
540    #[must_use]
541    pub fn new(objects_dir: &Path) -> Self {
542        Self {
543            objects_dir: objects_dir.to_path_buf(),
544            work_tree: None,
545            submodule_alternate_dirs: Arc::new(Mutex::new(Vec::new())),
546            config_git_dir: None,
547            core_multi_pack_index_cache: Arc::new(OnceLock::new()),
548            local_pack_indexes_seen: Arc::new(OnceLock::new()),
549            file_alternate_dirs_cache: Arc::new(RwLock::new(FileAlternatesCache {
550                generation: 0,
551                snapshot: None,
552            })),
553            env_alternate_dirs: Vec::new(),
554            env_alternate_lazy: Arc::new(OnceLock::new()),
555            mem_overlay: Arc::new(RwLock::new(None)),
556            mem_overlay_active: Arc::new(AtomicBool::new(false)),
557            primary: PrimaryStore::files(),
558            alternate_sources_cache: Arc::new(RwLock::new(AlternateSourcesCache {
559                file_generation: 0,
560                env_fingerprint: 0,
561                submodule_generation: 0,
562                sources: None,
563            })),
564            midx_packs_validated: Arc::new(OnceLock::new()),
565            hash_algo_cache: Arc::new(OnceLock::new()),
566            loose_zlib_cache: Arc::new(OnceLock::new()),
567            pack_zlib_cache: Arc::new(OnceLock::new()),
568            big_file_threshold_cache: Arc::new(OnceLock::new()),
569            shared_config_state: None,
570            delta_base_cache_sync: Arc::new(OnceLock::new()),
571            shared_environment: None,
572            empty_config_env: Arc::new(OnceLock::new()),
573            freshened_packs: Arc::new(Mutex::new(HashSet::new())),
574            pack_store: Arc::new(PackStore::new(objects_dir.to_path_buf())),
575            alternate_pack_stores: Arc::new(Mutex::new(HashMap::new())),
576            submodule_sources_generation: Arc::new(AtomicU64::new(0)),
577            extra_read_sources: Vec::new(),
578            alternates_enabled: true,
579            attached_commit_graph: None,
580            session_loose_reads: Arc::new(Mutex::new(SessionLooseReads::default())),
581            session_tree_entries: Arc::new(Mutex::new(SessionTreeEntries::default())),
582            loose_negative_caches: Arc::new(Mutex::new(HashMap::new())),
583            #[cfg(test)]
584            exists_probe: Arc::new(AtomicUsize::new(0)),
585            #[cfg(test)]
586            hot_path_test_metrics: crate::hot_path_test_metrics::HotPathTestMetrics::new(),
587        }
588    }
589
590    /// Create an [`Odb`] with a work tree for resolving relative alternate paths.
591    ///
592    /// Does not read `GIT_ALTERNATE_OBJECT_DIRECTORIES`; pass env-derived paths with
593    /// [`Self::with_env_alternate_dirs`] (see [`Self::env_alternate_dirs_from_var`]).
594    #[must_use]
595    pub fn with_work_tree(objects_dir: &Path, work_tree: &Path) -> Self {
596        Self {
597            objects_dir: objects_dir.to_path_buf(),
598            work_tree: Some(work_tree.to_path_buf()),
599            submodule_alternate_dirs: Arc::new(Mutex::new(Vec::new())),
600            config_git_dir: None,
601            core_multi_pack_index_cache: Arc::new(OnceLock::new()),
602            local_pack_indexes_seen: Arc::new(OnceLock::new()),
603            file_alternate_dirs_cache: Arc::new(RwLock::new(FileAlternatesCache {
604                generation: 0,
605                snapshot: None,
606            })),
607            env_alternate_dirs: Vec::new(),
608            env_alternate_lazy: Arc::new(OnceLock::new()),
609            mem_overlay: Arc::new(RwLock::new(None)),
610            mem_overlay_active: Arc::new(AtomicBool::new(false)),
611            primary: PrimaryStore::files(),
612            alternate_sources_cache: Arc::new(RwLock::new(AlternateSourcesCache {
613                file_generation: 0,
614                env_fingerprint: 0,
615                submodule_generation: 0,
616                sources: None,
617            })),
618            midx_packs_validated: Arc::new(OnceLock::new()),
619            hash_algo_cache: Arc::new(OnceLock::new()),
620            loose_zlib_cache: Arc::new(OnceLock::new()),
621            pack_zlib_cache: Arc::new(OnceLock::new()),
622            big_file_threshold_cache: Arc::new(OnceLock::new()),
623            shared_config_state: None,
624            delta_base_cache_sync: Arc::new(OnceLock::new()),
625            shared_environment: None,
626            empty_config_env: Arc::new(OnceLock::new()),
627            freshened_packs: Arc::new(Mutex::new(HashSet::new())),
628            pack_store: Arc::new(PackStore::new(objects_dir.to_path_buf())),
629            alternate_pack_stores: Arc::new(Mutex::new(HashMap::new())),
630            submodule_sources_generation: Arc::new(AtomicU64::new(0)),
631            extra_read_sources: Vec::new(),
632            alternates_enabled: true,
633            attached_commit_graph: None,
634            session_loose_reads: Arc::new(Mutex::new(SessionLooseReads::default())),
635            session_tree_entries: Arc::new(Mutex::new(SessionTreeEntries::default())),
636            loose_negative_caches: Arc::new(Mutex::new(HashMap::new())),
637            #[cfg(test)]
638            exists_probe: Arc::new(AtomicUsize::new(0)),
639            #[cfg(test)]
640            hot_path_test_metrics: crate::hot_path_test_metrics::HotPathTestMetrics::new(),
641        }
642    }
643
644    fn session_tree(&self, oid: &ObjectId) -> Option<SessionTree> {
645        self.session_tree_entries
646            .lock()
647            .ok()?
648            .trees
649            .get(oid)
650            .cloned()
651    }
652
653    fn remember_session_tree(&self, oid: &ObjectId, tree: SessionTree) {
654        if let Ok(mut guard) = self.session_tree_entries.lock() {
655            guard.insert(*oid, tree);
656        }
657    }
658
659    /// [`Self::read`] without keeping a copy in the session read cache, for walks that
660    /// read each object once (pack enumeration), where the copy is pure overhead.
661    ///
662    /// # Errors
663    ///
664    /// Same as [`Self::read`].
665    pub(crate) fn read_once(&self, oid: &ObjectId) -> Result<Object> {
666        self.read_impl(oid, false)
667    }
668
669    fn read_tree_payload(&self, oid: &ObjectId) -> Result<Vec<u8>> {
670        let obj = self.read_impl(oid, false)?;
671        if obj.kind != ObjectKind::Tree {
672            return Err(Error::Object(ObjectError::Corrupt {
673                detail: format!("expected tree, got {}", obj.kind.as_str()),
674            }));
675        }
676        Ok(obj.data)
677    }
678
679    /// Parsed tree entries for `oid`, cached on this [`Odb`] handle.
680    pub(crate) fn cached_tree_entries(
681        &self,
682        oid: &ObjectId,
683    ) -> Result<Arc<Vec<crate::objects::TreeEntry>>> {
684        let parsed = match self.session_tree(oid) {
685            Some(SessionTree::Parsed(entries)) => return Ok(entries),
686            Some(SessionTree::Raw(data)) => {
687                crate::objects::parse_tree_for_algo(&data, self.hash_algo())?
688            }
689            None => crate::objects::parse_tree_for_algo(
690                &self.read_tree_payload(oid)?,
691                self.hash_algo(),
692            )?,
693        };
694        let arc = Arc::new(parsed);
695        self.remember_session_tree(oid, SessionTree::Parsed(Arc::clone(&arc)));
696        Ok(arc)
697    }
698
699    /// The tree `oid` for a read-only walk, cached on this [`Odb`] handle.
700    ///
701    /// Returns the parsed entries when another caller already cached them, otherwise the raw
702    /// payload, so a walk that only compares entries never allocates one per entry.
703    pub(crate) fn cached_tree_for_walk(&self, oid: &ObjectId) -> Result<SessionTree> {
704        if let Some(tree) = self.session_tree(oid) {
705            return Ok(tree);
706        }
707        let tree = SessionTree::Raw(Arc::new(self.read_tree_payload(oid)?));
708        self.remember_session_tree(oid, tree.clone());
709        Ok(tree)
710    }
711
712    fn session_cached_loose_read(&self, oid: &ObjectId) -> Option<Object> {
713        self.session_loose_reads.lock().ok()?.get(oid).cloned()
714    }
715
716    /// Drop the session read and tree caches, so objects a prune just deleted from a
717    /// custom primary are not served from them afterwards.
718    pub(crate) fn forget_session_reads(&self) {
719        if let Ok(mut guard) = self.session_loose_reads.lock() {
720            *guard = SessionLooseReads::default();
721        }
722        if let Ok(mut guard) = self.session_tree_entries.lock() {
723            *guard = SessionTreeEntries::default();
724        }
725    }
726
727    /// Whether the session read cache holds a copy of `oid` (crate-internal tests only).
728    #[cfg(test)]
729    pub(crate) fn session_read_is_cached(&self, oid: &ObjectId) -> bool {
730        self.session_cached_loose_read(oid).is_some()
731    }
732
733    /// Keep `obj` in the session read cache. Bounded checkout reads call this directly for
734    /// the small blobs they reuse; general reads go through [`Self::finish_session_loose_read`].
735    fn remember_session_loose_read(&self, oid: &ObjectId, obj: &Object) {
736        if let Ok(mut guard) = self.session_loose_reads.lock() {
737            guard.insert(*oid, obj);
738        }
739    }
740
741    /// Return a freshly read object, caching commits, trees, tags and tiny blobs for reuse
742    /// when `remember` is set.
743    ///
744    /// Larger blobs are not cached here (see [`SESSION_READ_BLOB_CACHE_MAX`]): diffs, merges
745    /// and blame read each blob about once, so a cached copy only costs an extra allocation
746    /// and keeps every blob of an operation resident until the cache starts over. Callers
747    /// that do re-read small blobs opt in through [`Self::read_unless_larger`].
748    fn finish_session_loose_read(
749        &self,
750        oid: &ObjectId,
751        obj: Object,
752        remember: bool,
753    ) -> Result<Object> {
754        if remember
755            && (obj.kind != ObjectKind::Blob || obj.data.len() <= SESSION_READ_BLOB_CACHE_MAX)
756        {
757            self.remember_session_loose_read(oid, &obj);
758        }
759        Ok(obj)
760    }
761
762    /// Hot-path regression counters (crate-internal tests only).
763    #[cfg(test)]
764    #[must_use]
765    pub(crate) fn hot_path_metrics(&self) -> &crate::hot_path_test_metrics::HotPathTestMetrics {
766        &self.hot_path_test_metrics
767    }
768
769    #[cfg(test)]
770    #[must_use]
771    pub(crate) fn hot_path_metrics_arc(
772        &self,
773    ) -> Arc<crate::hot_path_test_metrics::HotPathTestMetrics> {
774        Arc::clone(&self.hot_path_test_metrics)
775    }
776
777    /// Share the repository's lazy config snapshot (see [`crate::repo::Repository::config`]).
778    #[must_use]
779    pub(crate) fn with_shared_config_state(
780        mut self,
781        state: crate::repo::RepositoryConfigSnapshot,
782        env: Arc<crate::environment::Environment>,
783    ) -> Self {
784        self.pack_store.set_repo_caches(Arc::clone(&state));
785        self.shared_config_state = Some(state);
786        self.shared_environment = Some(env);
787        self
788    }
789
790    fn diagnostics_handle(&self) -> crate::diagnostics::DiagnosticsHandle {
791        self.shared_config_state
792            .as_ref()
793            .map(|state| state.diagnostics_handle())
794            .unwrap_or_else(|| Arc::new(NullDiagnostics))
795    }
796
797    /// The config cascade for this object database's repository.
798    ///
799    /// With a shared repository config state this is the repository's own snapshot: the load
800    /// uses the same options (and so the same cache entry) as
801    /// [`crate::repo::Repository::config`], so opening a repository parses the cascade once.
802    pub(crate) fn load_config_cascade(&self) -> Result<Arc<ConfigSet>> {
803        let git_dir = self
804            .config_git_dir
805            .as_deref()
806            .or_else(|| self.objects_dir.parent());
807        if let (Some(caches), Some(env)) = (&self.shared_config_state, &self.shared_environment) {
808            let opts = crate::config::LoadConfigOptions::for_repository(
809                env,
810                git_dir,
811                Some(Arc::clone(caches)),
812            );
813            return caches.load_config_with_options(env.as_ref(), git_dir, &opts);
814        }
815        match git_dir {
816            Some(git_dir) => ConfigSet::load(
817                self.config_environment(),
818                Some(git_dir),
819                &crate::config::LoadConfigOptions::standard(
820                    self.config_environment(),
821                    Some(git_dir),
822                ),
823            )
824            .map(Arc::new),
825            None => Ok(Arc::new(ConfigSet::new())),
826        }
827    }
828
829    fn config_environment(&self) -> &crate::environment::Environment {
830        if let Some(env) = self.shared_environment.as_deref() {
831            return env;
832        }
833        self.empty_config_env
834            .get_or_init(crate::environment::Environment::empty)
835    }
836
837    fn env_alternate_dirs_snapshot(&self) -> Arc<Vec<PathBuf>> {
838        if !self.env_alternate_dirs.is_empty() {
839            return Arc::new(self.env_alternate_dirs.clone());
840        }
841        Arc::clone(self.env_alternate_lazy.get_or_init(|| {
842            Arc::new(Self::env_alternate_dirs_from_var(
843                self.config_environment(),
844                self.work_tree.as_deref(),
845            ))
846        }))
847    }
848
849    /// Parse `GIT_ALTERNATE_OBJECT_DIRECTORIES` once for [`Self::with_env_alternate_dirs`].
850    ///
851    /// Relative entries are resolved against `resolve_base` (typically the work tree root).
852    #[must_use]
853    pub fn env_alternate_dirs_from_var(
854        env: &crate::environment::Environment,
855        resolve_base: Option<&Path>,
856    ) -> Vec<PathBuf> {
857        match env.var("GIT_ALTERNATE_OBJECT_DIRECTORIES") {
858            Some(val) if !val.is_empty() => {
859                let mut dirs = parse_alternate_env(&val);
860                if let Some(base) = resolve_base {
861                    for dir in &mut dirs {
862                        if dir.is_relative() {
863                            *dir = base.join(&dir);
864                        }
865                    }
866                }
867                dirs
868            }
869            _ => Vec::new(),
870        }
871    }
872
873    /// Attach env-derived alternate object directories (see [`Self::env_alternate_dirs_from_var`]).
874    #[must_use]
875    pub fn with_env_alternate_dirs(mut self, dirs: Vec<PathBuf>) -> Self {
876        self.env_alternate_dirs = dirs;
877        self.clear_alternate_sources_cache();
878        self
879    }
880
881    fn clear_alternate_sources_cache(&self) {
882        if let Ok(mut guard) = self.alternate_sources_cache.write() {
883            guard.sources = None;
884        }
885    }
886
887    fn alternate_sources_key(&self) -> AlternateSourcesKey {
888        AlternateSourcesKey {
889            file_generation: self
890                .file_alternate_dirs_cache
891                .read()
892                .map(|g| g.generation)
893                .unwrap_or(0),
894            env_fingerprint: self.env_alternate_fingerprint(),
895            submodule_generation: self.submodule_sources_generation.load(Ordering::Relaxed),
896        }
897    }
898
899    fn env_alternate_fingerprint(&self) -> u64 {
900        let mut hasher = std::collections::hash_map::DefaultHasher::new();
901        for path in self.env_alternate_dirs_snapshot().iter() {
902            path.hash(&mut hasher);
903        }
904        hasher.finish()
905    }
906
907    /// Reload `info/alternates` from disk into this [`Odb`]'s cache (used after external writes).
908    ///
909    /// # Errors
910    ///
911    /// Propagates failures from reading the alternates chain (I/O or malformed `info/alternates`).
912    pub fn refresh_file_alternates_from_disk(&self) -> Result<()> {
913        let snapshot = Arc::new(pack::read_alternates_recursive(&self.objects_dir)?);
914        if let Ok(mut guard) = self.file_alternate_dirs_cache.write() {
915            guard.generation = guard.generation.wrapping_add(1);
916            guard.snapshot = Some(snapshot);
917        }
918        self.clear_alternate_sources_cache();
919        Ok(())
920    }
921
922    /// Append `alternate_objects_dir` to `objects/info/alternates` (deduped) and refresh the cache.
923    ///
924    /// # Errors
925    ///
926    /// [`Error::Io`] when the alternates file cannot be read or written.
927    pub fn append_file_alternate(&self, alternate_objects_dir: &Path) -> Result<()> {
928        Self::append_alternate_objects_line(&self.objects_dir, alternate_objects_dir)?;
929        self.refresh_file_alternates_from_disk()?;
930        Ok(())
931    }
932
933    /// Append one absolute `objects` directory line to `objects/info/alternates` (deduped).
934    ///
935    /// Does not update any in-memory cache; pair with [`Self::refresh_file_alternates_from_disk`]
936    /// on the relevant [`Odb`] when the same process keeps using it.
937    pub fn append_alternate_objects_line(
938        objects_dir: &Path,
939        alternate_objects_dir: &Path,
940    ) -> Result<()> {
941        let info = objects_dir.join("info");
942        fs::create_dir_all(&info)?;
943        let alt_path = info.join("alternates");
944        let alt_abs = alternate_objects_dir
945            .canonicalize_simplified()
946            .unwrap_or_else(|_| alternate_objects_dir.to_path_buf());
947        let line = format!("{}\n", alt_abs.display());
948        let existing = match fs::read_to_string(&alt_path) {
949            Ok(s) => s,
950            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
951            Err(e) => return Err(Error::Io(e)),
952        };
953        if existing
954            .lines()
955            .any(|l| l.trim() == alt_abs.to_string_lossy())
956        {
957            return Ok(());
958        }
959        let mut out = existing;
960        out.push_str(&line);
961        fs::write(alt_path, out).map_err(Error::Io)
962    }
963
964    fn file_alternate_dirs_snapshot(&self) -> Arc<Vec<PathBuf>> {
965        loop {
966            let observed_gen = self
967                .file_alternate_dirs_cache
968                .read()
969                .map(|g| g.generation)
970                .unwrap_or(0);
971            if let Ok(guard) = self.file_alternate_dirs_cache.read() {
972                if guard.generation == observed_gen {
973                    if let Some(snapshot) = &guard.snapshot {
974                        return Arc::clone(snapshot);
975                    }
976                }
977            }
978            if let Ok(mut guard) = self.file_alternate_dirs_cache.write() {
979                if guard.generation != observed_gen {
980                    continue;
981                }
982                if let Some(snapshot) = &guard.snapshot {
983                    return Arc::clone(snapshot);
984                }
985                let snapshot = Arc::new(
986                    pack::read_alternates_recursive(&self.objects_dir).unwrap_or_default(),
987                );
988                guard.snapshot = Some(Arc::clone(&snapshot));
989                return snapshot;
990            }
991            break;
992        }
993        Arc::new(Vec::new())
994    }
995
996    /// Object directories whose loose and pack stores participate in repository fsck.
997    ///
998    /// Includes the primary `objects/` path and file/env alternates when enabled.
999    pub(crate) fn local_store_validation_object_dirs(&self) -> Vec<PathBuf> {
1000        if !self.uses_files_primary() {
1001            return Vec::new();
1002        }
1003        let mut dirs = Vec::new();
1004        if let Some(primary) = self.files_objects_dir() {
1005            dirs.push(primary.to_path_buf());
1006        }
1007        if self.alternates_enabled {
1008            for alt in self.file_alternate_dirs_snapshot().iter() {
1009                if !dirs.iter().any(|d| d == alt) {
1010                    dirs.push(alt.clone());
1011                }
1012            }
1013            for alt in self.env_alternate_dirs_snapshot().iter() {
1014                if !dirs.iter().any(|d| d == alt) {
1015                    dirs.push(alt.clone());
1016                }
1017            }
1018        }
1019        dirs
1020    }
1021
1022    fn loose_negative_cache_for(&self, objects_dir: &Path) -> store::SharedLooseNegativeCache {
1023        let key = objects_dir.to_path_buf();
1024        if let Ok(guard) = self.loose_negative_caches.lock() {
1025            if let Some(hit) = guard.get(&key) {
1026                return Arc::clone(hit);
1027            }
1028        }
1029        let mut guard = self
1030            .loose_negative_caches
1031            .lock()
1032            .unwrap_or_else(|e| e.into_inner());
1033        guard
1034            .entry(key)
1035            .or_insert_with(|| Arc::new(Mutex::new(store::LooseNegativeCache::default())))
1036            .clone()
1037    }
1038
1039    fn invalidate_loose_negative_cache(&self, objects_dir: &Path) {
1040        let key = objects_dir.to_path_buf();
1041        let cache = self
1042            .loose_negative_caches
1043            .lock()
1044            .ok()
1045            .and_then(|guard| guard.get(&key).map(Arc::clone));
1046        let Some(cache) = cache else {
1047            return;
1048        };
1049        let mut inner = cache
1050            .lock()
1051            .unwrap_or_else(|poisoned| poisoned.into_inner());
1052        *inner = store::LooseNegativeCache::default();
1053    }
1054
1055    #[cold]
1056    #[inline(never)]
1057    fn reread_primary_after_pack_recheck(&self, oid: &ObjectId) -> Result<Option<Object>> {
1058        self.invalidate_loose_negative_cache(self.objects_dir.as_path());
1059        self.with_pack_store_for(&self.objects_dir, || {
1060            crate::pack::pack_cache::untrust_pack_listing_for_miss(&self.objects_dir);
1061            let _ = crate::pack::reprepare_pack_directory_on_miss(&self.objects_dir);
1062        });
1063        let primary = self.primary_writable()?;
1064        primary.read(oid)
1065    }
1066
1067    #[cold]
1068    #[inline(never)]
1069    fn object_not_found_after_primary_revalidate(&self, oid: &ObjectId) -> Result<Object> {
1070        if let Some(obj) = self.reread_primary_after_pack_recheck(oid)? {
1071            return Ok(obj);
1072        }
1073        Err(Error::Object(ObjectError::NotFound { name: oid.to_hex() }))
1074    }
1075
1076    #[cold]
1077    #[inline(never)]
1078    fn try_read_primary_info_after_negative_revalidate(
1079        &self,
1080        oid: &ObjectId,
1081    ) -> Result<Option<ObjectInfo>> {
1082        self.invalidate_loose_negative_cache(self.objects_dir.as_path());
1083        self.with_pack_store_for(&self.objects_dir, || {
1084            crate::pack::pack_cache::untrust_pack_listing_for_miss(&self.objects_dir);
1085            let _ = crate::pack::reprepare_pack_directory_on_miss(&self.objects_dir);
1086        });
1087        let primary = self.primary_writable()?;
1088        primary.read_info(oid)
1089    }
1090
1091    #[cold]
1092    #[inline(never)]
1093    fn try_read_primary_into_after_negative_revalidate(
1094        &self,
1095        oid: &ObjectId,
1096        buf: &mut Vec<u8>,
1097    ) -> Result<Option<ObjectKind>> {
1098        self.invalidate_loose_negative_cache(self.objects_dir.as_path());
1099        self.with_pack_store_for(&self.objects_dir, || {
1100            crate::pack::pack_cache::untrust_pack_listing_for_miss(&self.objects_dir);
1101            let _ = crate::pack::reprepare_pack_directory_on_miss(&self.objects_dir);
1102        });
1103        let primary = self.primary_writable()?;
1104        primary.read_into(oid, buf)
1105    }
1106
1107    #[cold]
1108    #[inline(never)]
1109    fn object_info_not_found_after_primary_revalidate(&self, oid: &ObjectId) -> Result<ObjectInfo> {
1110        if let Some(info) = self.try_read_primary_info_after_negative_revalidate(oid)? {
1111            return Ok(info);
1112        }
1113        Err(Error::Object(ObjectError::NotFound { name: oid.to_hex() }))
1114    }
1115
1116    #[cold]
1117    #[inline(never)]
1118    fn object_kind_not_found_after_primary_revalidate(
1119        &self,
1120        oid: &ObjectId,
1121        buf: &mut Vec<u8>,
1122    ) -> Result<ObjectKind> {
1123        if let Some(kind) = self.try_read_primary_into_after_negative_revalidate(oid, buf)? {
1124            return Ok(kind);
1125        }
1126        Err(Error::Object(ObjectError::NotFound { name: oid.to_hex() }))
1127    }
1128
1129    #[cfg(test)]
1130    pub(crate) fn exists_probe_count(&self) -> usize {
1131        self.exists_probe.load(Ordering::Relaxed)
1132    }
1133
1134    #[cfg(test)]
1135    pub(crate) fn reset_exists_probe(&self) {
1136        self.exists_probe.store(0, Ordering::Relaxed);
1137    }
1138
1139    /// Enable the in-memory write overlay (Git's tmp-objdir): subsequent [`Self::write`]/
1140    /// [`Self::write_local`] calls keep objects only in memory, and [`Self::read`] consults that
1141    /// overlay before the on-disk store. Used by `merge-tree --quiet` so a full merge can run
1142    /// without persisting any new loose objects.
1143    pub fn enable_mem_overlay(&self) {
1144        self.mem_overlay_active.store(true, Ordering::Release);
1145        if let Ok(mut guard) = self.mem_overlay.write() {
1146            if guard.is_none() {
1147                *guard = Some(Arc::new(MemoryStore::new(self.hash_algo())));
1148            }
1149        }
1150    }
1151
1152    /// Disable the in-memory write overlay, discarding any objects accumulated in it.
1153    pub fn disable_mem_overlay(&self) {
1154        self.mem_overlay_active.store(false, Ordering::Release);
1155        if let Ok(mut guard) = self.mem_overlay.write() {
1156            *guard = None;
1157        }
1158    }
1159
1160    /// Write every object in the active mem overlay as a loose object in this repository, then
1161    /// clear the overlay. No-op when the overlay is inactive or empty.
1162    ///
1163    /// # Errors
1164    ///
1165    /// Propagates overlay iteration and [`Self::write_into_primary`] failures.
1166    pub(crate) fn persist_mem_overlay(&self) -> Result<()> {
1167        use std::ops::ControlFlow;
1168
1169        let store = match self.overlay_store() {
1170            Some(store) => store,
1171            None => return Ok(()),
1172        };
1173        let mut oids = Vec::new();
1174        store.for_each_object(&mut |oid| {
1175            oids.push(*oid);
1176            ControlFlow::Continue(())
1177        })?;
1178        let mut payloads = Vec::with_capacity(oids.len());
1179        for oid in oids {
1180            let obj = store
1181                .read(&oid)?
1182                .ok_or_else(|| Error::Object(ObjectError::NotFound { name: oid.to_hex() }))?;
1183            payloads.push((obj.kind, obj.data));
1184        }
1185        self.mem_overlay_active.store(false, Ordering::Release);
1186        if let Ok(mut guard) = self.mem_overlay.write() {
1187            *guard = None;
1188        }
1189        let custom_primary = self.primary.is_custom();
1190        for (kind, data) in payloads {
1191            self.write_into_primary(kind, &data)?;
1192        }
1193        if custom_primary {
1194            self.flush()?;
1195        }
1196        Ok(())
1197    }
1198
1199    /// Write selected overlay objects to loose storage, leaving the overlay active.
1200    ///
1201    /// Skips `oid`s that are absent from the overlay or already stored locally.
1202    ///
1203    /// # Errors
1204    ///
1205    /// Propagates overlay read and [`Self::write_into_primary`] failures.
1206    pub(crate) fn persist_mem_overlay_objects(
1207        &self,
1208        oids: impl IntoIterator<Item = ObjectId>,
1209    ) -> Result<()> {
1210        let store = match self.overlay_store() {
1211            Some(store) => store,
1212            None => return Ok(()),
1213        };
1214        for oid in oids {
1215            if self.exists_local(&oid) {
1216                continue;
1217            }
1218            let Some(obj) = store.read(&oid)? else {
1219                continue;
1220            };
1221            self.write_into_primary(obj.kind, &obj.data)?;
1222        }
1223        if self.primary.is_custom() {
1224            self.flush()?;
1225        }
1226        Ok(())
1227    }
1228
1229    /// Whether the in-memory write overlay is currently enabled.
1230    #[must_use]
1231    pub(crate) fn is_mem_overlay_active(&self) -> bool {
1232        self.mem_overlay_active.load(Ordering::Acquire)
1233    }
1234
1235    fn overlay_active(&self) -> bool {
1236        self.mem_overlay
1237            .read()
1238            .ok()
1239            .and_then(|g| g.as_ref().map(|_| ()))
1240            .is_some()
1241    }
1242
1243    fn overlay_store(&self) -> Option<Arc<MemoryStore>> {
1244        if !self.mem_overlay_active.load(Ordering::Acquire) {
1245            return None;
1246        }
1247        self.mem_overlay.read().ok().and_then(|g| g.clone())
1248    }
1249
1250    /// Number of objects stored in the active mem overlay (tests only).
1251    #[cfg(test)]
1252    pub(crate) fn mem_overlay_len_for_tests(&self) -> Option<usize> {
1253        let store = self.overlay_store()?;
1254        let mut count = 0usize;
1255        store
1256            .for_each_object(&mut |_| {
1257                count += 1;
1258                ControlFlow::Continue(())
1259            })
1260            .ok()?;
1261        Some(count)
1262    }
1263
1264    /// If the in-memory overlay is active, store `(kind, data)` under `oid` there and return
1265    /// `true`; otherwise return `false` so the caller falls through to the on-disk path.
1266    fn overlay_store_object(&self, oid: ObjectId, kind: ObjectKind, data: &[u8]) -> bool {
1267        let Some(store) = self.overlay_store() else {
1268            return false;
1269        };
1270        store.insert_object(oid, kind, Arc::from(data.to_owned()));
1271        true
1272    }
1273
1274    /// Read `oid` from the in-memory overlay, if active and present.
1275    fn overlay_read(&self, oid: &ObjectId) -> Option<Object> {
1276        let store = self.overlay_store()?;
1277        store.read(oid).ok().flatten()
1278    }
1279
1280    /// Primary on-disk object source for this repository's `objects/` directory.
1281    ///
1282    /// Files-backed primaries only. For a store that works with any primary use
1283    /// [`Self::primary_writable`] (the primary alone) or [`Self::read_store`] (everything
1284    /// this database can read).
1285    ///
1286    /// # Errors
1287    ///
1288    /// - [`RepositoryError::UnsupportedObjectStore`] (`operation:` [`FilesOnlyOperation::FilesSource`](crate::repo::error::FilesOnlyOperation::FilesSource)) when
1289    ///   [`RepositoryOptions::with_object_store`](crate::environment::RepositoryOptions::with_object_store)
1290    ///   replaced the files-backed primary.
1291    /// - Failures while opening pack, MIDX, or loose backends.
1292    pub fn primary(&self) -> Result<Arc<FilesSource>> {
1293        self.files_primary().map(Arc::clone)
1294    }
1295
1296    /// The pattern-matchable primary store; see [`PrimaryStore`].
1297    pub(crate) fn primary_store(&self) -> &PrimaryStore {
1298        &self.primary
1299    }
1300
1301    /// Borrowed [`Self::primary`]: the files source, opened on first use, without an `Arc`
1302    /// clone.
1303    ///
1304    /// # Errors
1305    ///
1306    /// Same as [`Self::primary`].
1307    fn files_primary(&self) -> Result<&Arc<FilesSource>> {
1308        match &self.primary {
1309            PrimaryStore::Files(slot) => self.open_files_source(slot),
1310            PrimaryStore::Custom(_) => Err(RepositoryError::UnsupportedObjectStore {
1311                operation: FilesOnlyOperation::FilesSource,
1312            }
1313            .into()),
1314        }
1315    }
1316
1317    /// The primary store opened for one operation (files source or custom store).
1318    ///
1319    /// # Errors
1320    ///
1321    /// Failures while opening the files source's pack, MIDX, or loose backends.
1322    fn open_primary(&self) -> Result<OpenPrimary<'_>> {
1323        match &self.primary {
1324            PrimaryStore::Files(slot) => self
1325                .open_files_source(slot)
1326                .map(|files| OpenPrimary::Files(files.as_ref())),
1327            PrimaryStore::Custom(store) => Ok(OpenPrimary::Custom(store.as_ref())),
1328        }
1329    }
1330
1331    fn open_files_source<'a>(
1332        &self,
1333        slot: &'a OnceLock<Arc<FilesSource>>,
1334    ) -> Result<&'a Arc<FilesSource>> {
1335        if let Some(src) = slot.get() {
1336            return Ok(src);
1337        }
1338        let src = self.build_files_source(
1339            &self.objects_dir,
1340            self.multi_pack_index_reads_enabled(),
1341            self.midx_tip_listing_enabled(),
1342        )?;
1343        Ok(slot.get_or_init(|| src))
1344    }
1345
1346    /// Whether abbreviation must consult the full read chain (not only the primary pack index).
1347    ///
1348    /// True when [`OdbBuilder::push_read_source`] layers, an in-memory overlay, a custom
1349    /// primary store or alternate object directories can hold objects beyond the primary
1350    /// `objects/` loose and pack stores.
1351    #[must_use]
1352    pub(crate) fn has_secondary_object_stores(&self) -> bool {
1353        if !self.extra_read_sources.is_empty()
1354            || self.primary.is_custom()
1355            || self.overlay_store().is_some()
1356        {
1357            return true;
1358        }
1359        self.alternates_enabled && self.alternate_object_lookup_needed()
1360    }
1361
1362    /// Whether any alternate object directory is configured for this database.
1363    #[must_use]
1364    fn alternate_object_lookup_needed(&self) -> bool {
1365        if !self.file_alternate_dirs_snapshot().is_empty() {
1366            return true;
1367        }
1368        if !self.env_alternate_dirs_snapshot().is_empty() {
1369            return true;
1370        }
1371        self.submodule_alternate_dirs
1372            .lock()
1373            .ok()
1374            .is_some_and(|guard| !guard.is_empty())
1375    }
1376
1377    /// Alternate object directories (`info/alternates`, env, submodules) as one composite store.
1378    ///
1379    /// Only the alternates: neither the primary nor [`OdbBuilder::push_read_source`] layers
1380    /// are included, and the composite is empty when [`OdbBuilder::alternates`] is off. Use
1381    /// [`Self::read_store`] for the whole lookup chain.
1382    ///
1383    /// # Errors
1384    ///
1385    /// Propagates failures while opening any alternate files source.
1386    pub fn sources(&self) -> Result<Arc<CompositeStore>> {
1387        if !self.alternates_enabled {
1388            return Ok(Arc::new(CompositeStore::new(Vec::new(), self.hash_algo())));
1389        }
1390        let key = self.alternate_sources_key();
1391        if let Ok(guard) = self.alternate_sources_cache.read() {
1392            if guard.file_generation == key.file_generation
1393                && guard.env_fingerprint == key.env_fingerprint
1394                && guard.submodule_generation == key.submodule_generation
1395            {
1396                if let Some(sources) = guard.sources.as_ref() {
1397                    return Ok(Arc::clone(sources));
1398                }
1399            }
1400        }
1401        let use_midx = self.multi_pack_index_reads_enabled();
1402        let midx_tip = self.midx_tip_listing_enabled();
1403        let mut stores: Vec<Arc<dyn ObjectStore>> = Vec::new();
1404        for alt_dir in self.file_alternate_dirs_snapshot().iter() {
1405            stores.push(self.build_files_source(alt_dir, use_midx, midx_tip)?);
1406        }
1407        for alt_dir in self.env_alternate_dirs_snapshot().iter() {
1408            stores.push(self.build_files_source(alt_dir, use_midx, midx_tip)?);
1409        }
1410        if let Ok(guard) = self.submodule_alternate_dirs.lock() {
1411            for alt_dir in guard.iter() {
1412                stores.push(self.build_files_source(alt_dir, false, false)?);
1413            }
1414        }
1415        let composite = Arc::new(CompositeStore::new(stores, self.hash_algo()));
1416        if let Ok(mut guard) = self.alternate_sources_cache.write() {
1417            guard.file_generation = key.file_generation;
1418            guard.env_fingerprint = key.env_fingerprint;
1419            guard.submodule_generation = key.submodule_generation;
1420            guard.sources = Some(Arc::clone(&composite));
1421        }
1422        Ok(composite)
1423    }
1424
1425    fn midx_tip_listing_enabled(&self) -> bool {
1426        self.config_git_dir.is_some() && self.core_multi_pack_index_enabled()
1427    }
1428
1429    fn build_files_source(
1430        &self,
1431        objects_dir: &Path,
1432        use_midx: bool,
1433        midx_tip_listing_for_exists: bool,
1434    ) -> Result<Arc<FilesSource>> {
1435        let loose = self.loose_at(objects_dir)?;
1436        let pack_store = self.pack_store_for(objects_dir);
1437        let diagnostics = if objects_dir == self.objects_dir.as_path() {
1438            self.diagnostics_handle()
1439        } else {
1440            Arc::new(NullDiagnostics)
1441        };
1442        FilesSource::open(
1443            pack_store,
1444            loose,
1445            use_midx,
1446            midx_tip_listing_for_exists,
1447            diagnostics,
1448        )
1449        .map(Arc::new)
1450    }
1451
1452    /// Register `<submodule-git-dir>/objects` for every stage-0 gitlink in `index` that has a
1453    /// checkout under `work_tree`, so reads can resolve submodule commits stored only in the
1454    /// nested repository (matches Git's `odb_add_submodule_source_by_path` / `register_all_submodule_sources`).
1455    pub fn register_submodule_object_directories_from_index(
1456        &self,
1457        work_tree: &Path,
1458        index: &crate::index::Index,
1459    ) {
1460        use crate::diff::submodule_embedded_git_dir;
1461
1462        let Ok(mut dirs) = self.submodule_alternate_dirs.lock() else {
1463            return;
1464        };
1465        dirs.clear();
1466        for e in &index.entries {
1467            if e.stage() != 0 || e.mode != crate::index::MODE_GITLINK {
1468                continue;
1469            }
1470            let path_str = String::from_utf8_lossy(&e.path);
1471            let abs = work_tree.join(path_str.as_ref());
1472            let Some(sub_git) = submodule_embedded_git_dir(&abs) else {
1473                continue;
1474            };
1475            let objects = sub_git.join("objects");
1476            if !objects.is_dir() {
1477                continue;
1478            }
1479            let canon = objects.canonicalize_simplified().unwrap_or(objects);
1480            if !dirs.iter().any(|p| p == &canon) {
1481                dirs.push(canon);
1482            }
1483        }
1484        self.submodule_sources_generation
1485            .fetch_add(1, Ordering::Relaxed);
1486        self.clear_alternate_sources_cache();
1487    }
1488
1489    /// Attach a git directory so [`Self::read`] can honor `core.multiPackIndex` when resolving packed objects.
1490    #[must_use]
1491    pub fn with_config_git_dir(mut self, git_dir: PathBuf) -> Self {
1492        self.config_git_dir = Some(git_dir);
1493        self
1494    }
1495
1496    /// The repository's object hash algorithm, detected from
1497    /// `extensions.objectformat` and cached for the lifetime of this `Odb`.
1498    ///
1499    /// The git directory is taken from the attached `config_git_dir` when set,
1500    /// otherwise inferred as the parent of the `objects/` directory. Defaults
1501    /// to [`HashAlgo::Sha1`] when no config can be read.
1502    ///
1503    /// With a custom primary store
1504    /// ([`RepositoryOptions::with_object_store`](crate::environment::RepositoryOptions::with_object_store))
1505    /// this is the store's own algorithm, which a successful
1506    /// [`Repository::open`](crate::repo::Repository::open) has already checked against the
1507    /// repository's object format.
1508    #[must_use]
1509    pub fn hash_algo(&self) -> HashAlgo {
1510        if let PrimaryStore::Custom(primary) = &self.primary {
1511            return primary.hash_algo();
1512        }
1513        *self.hash_algo_cache.get_or_init(|| {
1514            if self.config_git_dir.is_none() && self.objects_dir.parent().is_none() {
1515                return HashAlgo::Sha1;
1516            }
1517            let cfg = self.load_config_cascade().unwrap_or_default();
1518            cfg.value("extensions.objectformat")
1519                .and_then(|v| HashAlgo::from_name(&v))
1520                .unwrap_or(HashAlgo::Sha1)
1521        })
1522    }
1523
1524    fn resolve_loose_zlib_level(&self) -> Result<u32> {
1525        if self.config_git_dir.is_none() && self.objects_dir.parent().is_none() {
1526            return Ok(ConfigSet::LOOSE_OBJECTS_ZLIB_DEFAULT as u32);
1527        }
1528        let cfg = self.load_config_cascade()?;
1529        Ok(cfg.loose_objects_zlib_level()? as u32)
1530    }
1531
1532    /// Zlib compression used for loose-object writes ([`ConfigSet::loose_objects_zlib_level`]),
1533    /// cached for the lifetime of this `Odb`.
1534    ///
1535    /// # Errors
1536    ///
1537    /// Returns errors from loading the config cascade or from invalid compression settings.
1538    pub(crate) fn loose_compression(&self) -> Result<Compression> {
1539        if let Some(cached) = self.loose_zlib_cache.get() {
1540            return Ok(*cached);
1541        }
1542        let level = self.resolve_loose_zlib_level()?;
1543        let compression = Compression::new(level);
1544        let _ = self.loose_zlib_cache.set(compression);
1545        Ok(compression)
1546    }
1547
1548    fn resolve_pack_zlib_level(&self) -> Result<i32> {
1549        if self.config_git_dir.is_none() && self.objects_dir.parent().is_none() {
1550            return Ok(6);
1551        }
1552        let cfg = self.load_config_cascade()?;
1553        cfg.pack_objects_zlib_level()
1554    }
1555
1556    /// Zlib compression for pack-objects ([`ConfigSet::pack_objects_zlib_level`]).
1557    ///
1558    /// # Errors
1559    ///
1560    /// Returns errors from loading the config cascade or from invalid compression settings.
1561    pub(crate) fn pack_compression(&self) -> Result<Compression> {
1562        if let Some(cached) = self.pack_zlib_cache.get() {
1563            return Ok(*cached);
1564        }
1565        let level = self.resolve_pack_zlib_level()?;
1566        let compression = crate::pack_zlib::flate2_compression_for_pack_level(level);
1567        let _ = self.pack_zlib_cache.set(compression);
1568        Ok(compression)
1569    }
1570
1571    /// `core.bigFileThreshold` ([`ConfigSet::big_file_threshold`]), cached for the lifetime of
1572    /// this `Odb`.
1573    ///
1574    /// Objects of at least this size are written by [`Self::write_stream`] into their own
1575    /// pack, and worktree files of at least this size that need no clean conversion are hashed
1576    /// and stored as a stream instead of being read into memory.
1577    ///
1578    /// # Errors
1579    ///
1580    /// Returns errors from loading the config cascade or from an invalid threshold value.
1581    pub fn big_file_threshold(&self) -> Result<u64> {
1582        if let Some(cached) = self.big_file_threshold_cache.get() {
1583            return Ok(*cached);
1584        }
1585        let threshold = if self.config_git_dir.is_none() && self.objects_dir.parent().is_none() {
1586            ConfigSet::BIG_FILE_THRESHOLD_DEFAULT
1587        } else {
1588            self.load_config_cascade()?.big_file_threshold()?
1589        };
1590        let _ = self.big_file_threshold_cache.set(threshold);
1591        Ok(threshold)
1592    }
1593
1594    /// An operation-local view with bounded pack residency and tree delta bases.
1595    /// Custom stores and overlays are preserved; file sources and alternates are rebuilt
1596    /// against private caches so this view cannot evict or reconfigure a caller's caches.
1597    pub(crate) fn with_bounded_pack_cache(&self) -> Self {
1598        let mut odb = self.clone();
1599        odb.pack_store = Arc::new(PackStore::for_bounded_reads(self.objects_dir.clone()));
1600        if let PrimaryStore::Files(_) = odb.primary {
1601            odb.primary = PrimaryStore::files();
1602        }
1603        odb.session_loose_reads = Arc::new(Mutex::new(SessionLooseReads::default()));
1604        odb.alternate_pack_stores = Arc::new(Mutex::new(HashMap::new()));
1605        odb.alternate_sources_cache = Arc::new(RwLock::new(AlternateSourcesCache {
1606            file_generation: 0,
1607            env_fingerprint: 0,
1608            submodule_generation: 0,
1609            sources: None,
1610        }));
1611        odb
1612    }
1613
1614    fn sync_delta_base_cache_limit(&self) {
1615        if self.pack_store.bounded_reads() {
1616            return;
1617        }
1618        self.delta_base_cache_sync.get_or_init(|| {
1619            if self.config_git_dir.is_some() {
1620                let cfg = self.load_config_cascade().unwrap_or_default();
1621                self.pack_store
1622                    .configure_delta_base_from_config(Some(cfg.as_ref()));
1623            }
1624        });
1625    }
1626
1627    pub(crate) fn pack_store_for(&self, objects_dir: &Path) -> Arc<PackStore> {
1628        if objects_dir == self.objects_dir.as_path() {
1629            return Arc::clone(&self.pack_store);
1630        }
1631        let new_store = || {
1632            Arc::new(if self.pack_store.bounded_reads() {
1633                PackStore::for_bounded_reads(objects_dir.to_path_buf())
1634            } else {
1635                PackStore::new(objects_dir.to_path_buf())
1636            })
1637        };
1638        if let Ok(mut guard) = self.alternate_pack_stores.lock() {
1639            return Arc::clone(
1640                guard
1641                    .entry(objects_dir.to_path_buf())
1642                    .or_insert_with(new_store),
1643            );
1644        }
1645        new_store()
1646    }
1647
1648    /// Pack/MIDX read cache shared by this handle and its [`Clone`]s.
1649    pub fn pack_store(&self) -> Result<&Arc<PackStore>> {
1650        self.primary
1651            .require_files_primary(FilesOnlyOperation::PackStore)?;
1652        Ok(&self.pack_store)
1653    }
1654
1655    /// Path to the largest pack index in the primary `objects/pack/` directory (by entry count).
1656    ///
1657    /// Used when writing a reachability bitmap for an all-into-one repack. Returns `Ok(None)`
1658    /// when no pack index exists.
1659    ///
1660    /// # Errors
1661    ///
1662    /// Returns [`RepositoryError::UnsupportedObjectStore`] when the store is not files-backed.
1663    pub fn largest_pack_index_path(&self) -> Result<Option<PathBuf>> {
1664        self.primary
1665            .require_files_primary(FilesOnlyOperation::LargestPackIndex)?;
1666        let mut indexes = pack::read_local_pack_indexes_cached(self.objects_dir())?;
1667        indexes.sort_by_key(|idx| std::cmp::Reverse(idx.len()));
1668        Ok(indexes.first().map(|idx| idx.idx_path.clone()))
1669    }
1670
1671    /// Drop the resolved delta bases cached for the primary `objects/` packs, keeping
1672    /// indexes and pack bytes. Frees memory between phases of a long operation whose
1673    /// next reads will not revisit the same bases.
1674    pub(crate) fn clear_delta_base_cache(&self) {
1675        self.pack_store.delta_bases().clear();
1676    }
1677
1678    /// Drop cached pack listings, parsed indexes, pack bytes, delta bases, and MIDX layers.
1679    ///
1680    /// Call after in-process repack, garbage collection, or [`crate::index_pack::install_pack_bytes`]
1681    /// so the next read rescans `objects/pack/`. Cloned [`Odb`] handles share one
1682    /// [`PackStore`] for the primary `objects/` directory; alternates have separate stores
1683    /// that are invalidated here as well.
1684    pub fn invalidate_packs(&self) {
1685        self.pack_store.invalidate_all();
1686        PackStore::invalidate_legacy_for_objects_dir(&self.objects_dir);
1687        if let Ok(guard) = self.alternate_pack_stores.lock() {
1688            for store in guard.values() {
1689                store.invalidate_all();
1690                PackStore::invalidate_legacy_for_objects_dir(store.objects_dir());
1691            }
1692        }
1693        self.invalidate_change_id_header_probe();
1694    }
1695
1696    fn invalidate_change_id_header_probe(&self) {
1697        if let Some(caches) = self.shared_config_state.as_ref() {
1698            crate::change_id::invalidate_stored_change_id_header_probe(
1699                caches,
1700                self.files_objects_dir(),
1701            );
1702        }
1703    }
1704
1705    fn note_commit_object_written(&self, kind: ObjectKind) {
1706        if kind == ObjectKind::Commit {
1707            self.invalidate_change_id_header_probe();
1708        }
1709    }
1710
1711    /// Materialize unreachable objects from packfiles superseded by a new repack pack.
1712    ///
1713    /// Git gc stores grace-protected unreachable objects in cruft packs; grit writes them
1714    /// loose (with preserved mtimes) so later loose pruning can apply `gc.pruneExpire`.
1715    ///
1716    /// `reachable` is only walked when a superseded pack holds an object that is in
1717    /// neither the new pack nor a `.keep` pack. `retained_packs` protects ordinary
1718    /// packs that supply available promises from being superseded or loosened.
1719    ///
1720    /// # Errors
1721    ///
1722    /// Propagates pack index read failures, object read/write errors, I/O failures,
1723    /// and errors from the reachability walk.
1724    pub(crate) fn loosen_unreachable_from_superseded_packs(
1725        &self,
1726        pack_dir: &Path,
1727        keep_pack: &Path,
1728        reachable: &crate::gc::LazyReachable<'_>,
1729        retention: UnreachablePackRetention,
1730        retained_packs: &HashSet<PathBuf>,
1731        inventory: &RepackPackInventorySnapshot,
1732    ) -> Result<usize> {
1733        if matches!(retention, UnreachablePackRetention::DropAll) {
1734            return Ok(0);
1735        }
1736        self.primary
1737            .require_files_primary(FilesOnlyOperation::Repack)?;
1738        let keep_idx = keep_pack.with_extension("idx");
1739        let keep_pack_oids = if keep_idx.is_file() {
1740            PackedObjects::object_ids_from_index_path(&keep_idx)?
1741        } else {
1742            HashSet::new()
1743        };
1744        let kept_pack_oids =
1745            oids_in_inventory_kept_packs(pack_dir, keep_pack, &inventory.kept_at_inventory)?;
1746        let mut loosened = 0usize;
1747        for (idx_path, pack_mtime) in
1748            superseded_pack_indexes(pack_dir, keep_pack, retained_packs, inventory)?
1749        {
1750            let oids = PackedObjects::object_ids_from_index_path(&idx_path)?;
1751            for oid in oids {
1752                let keep = match retention {
1753                    UnreachablePackRetention::KeepAll => true,
1754                    UnreachablePackRetention::KeepGraceProtected(cutoff) => pack_mtime >= cutoff,
1755                    UnreachablePackRetention::DropAll => false,
1756                };
1757                if !keep {
1758                    continue;
1759                }
1760                if keep_pack_oids.contains(&oid) || kept_pack_oids.contains(&oid) {
1761                    continue;
1762                }
1763                if reachable.get()?.contains(&oid) {
1764                    continue;
1765                }
1766                let loose_path = oid.loose_path_in(&self.objects_dir);
1767                let pack_ft = system_time_to_file_time(pack_mtime);
1768                match retention {
1769                    UnreachablePackRetention::KeepGraceProtected(cutoff) => {
1770                        if loose_path.is_file() {
1771                            let loose_mtime = fs::metadata(&loose_path)
1772                                .and_then(|m| m.modified())
1773                                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
1774                            if loose_mtime >= cutoff {
1775                                continue;
1776                            }
1777                            set_file_mtime(&loose_path, pack_ft).map_err(Error::Io)?;
1778                            loosened += 1;
1779                            continue;
1780                        }
1781                    }
1782                    UnreachablePackRetention::KeepAll => {
1783                        if loose_path.is_file() {
1784                            continue;
1785                        }
1786                    }
1787                    UnreachablePackRetention::DropAll => {}
1788                }
1789                let obj = self.read(&oid)?;
1790                self.write_loose_materialize(obj.kind, &obj.data)?;
1791                let primary = self.files_primary()?;
1792                let loose_path = primary.loose_store().object_path(&oid);
1793                set_file_mtime(&loose_path, pack_ft).map_err(Error::Io)?;
1794                loosened += 1;
1795            }
1796        }
1797        Ok(loosened)
1798    }
1799
1800    fn core_multi_pack_index_enabled(&self) -> bool {
1801        // The system/global/local config cascade is expensive to load (the parser walks every
1802        // file from `/etc/gitconfig` through `.git/config`); calling it once per object lookup
1803        // dominated `status` runtime. Cache the result for the lifetime of this `Odb`.
1804        *self.core_multi_pack_index_cache.get_or_init(|| {
1805            if self.config_git_dir.is_none() {
1806                return false;
1807            }
1808            let cfg = self.load_config_cascade().unwrap_or_default();
1809            cfg.bool_with_default("core.multiPackIndex", true)
1810        })
1811    }
1812
1813    fn multi_pack_index_reads_enabled(&self) -> bool {
1814        if self.primary.is_custom() {
1815            return false;
1816        }
1817        if self.config_git_dir.is_none() {
1818            return false;
1819        }
1820        if !*self
1821            .local_pack_indexes_seen
1822            .get_or_init(|| objects_dir_has_pack_index_files(&self.objects_dir))
1823        {
1824            return false;
1825        }
1826        self.core_multi_pack_index_enabled()
1827    }
1828
1829    /// When MIDX is configured but no chain is on disk, still use the fast pack-index path.
1830    fn skip_batch_packed_read_for_active_midx(&self) -> bool {
1831        self.multi_pack_index_reads_enabled()
1832            && self
1833                .primary()
1834                .ok()
1835                .is_some_and(|files| files.midx_reads_active())
1836    }
1837
1838    fn ensure_midx_prepared(&self) {
1839        if !self.multi_pack_index_reads_enabled() {
1840            return;
1841        }
1842        let _ = self.midx_packs_validated.get_or_init(|| {
1843            let diagnostics = self.diagnostics_handle();
1844            self.with_pack_store_for(&self.objects_dir, || {
1845                validate_midx_referenced_packs_with_diagnostics(
1846                    &self.objects_dir,
1847                    diagnostics.as_ref(),
1848                );
1849            });
1850        });
1851    }
1852
1853    /// Direct pack read when [`PackStore::with_context`] matches the primary `objects/` tree.
1854    ///
1855    /// Skips [`ObjectStore`] dynamic dispatch on batch cat-file workloads; MIDX repos use the
1856    /// full primary path instead.
1857    fn try_read_packed_in_batch_context(&self, oid: &ObjectId) -> Result<Option<Object>> {
1858        if self.primary.is_custom()
1859            || !PackStore::read_context_matches_objects_dir(&self.objects_dir)
1860            || self.skip_batch_packed_read_for_active_midx()
1861        {
1862            return Ok(None);
1863        }
1864        self.sync_delta_base_cache_limit();
1865        match pack::try_read_object_from_packs_with_options(
1866            &self.objects_dir,
1867            oid,
1868            pack::PackLookupOptions::ALL_LOCAL_PACKS,
1869        ) {
1870            Ok(obj) => Ok(Some(obj)),
1871            Err(Error::Object(ObjectError::NotFound { .. })) => Ok(None),
1872            Err(err) => Err(err),
1873        }
1874    }
1875
1876    fn try_read_info_packed_in_batch_context(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
1877        if self.primary.is_custom()
1878            || !PackStore::read_context_matches_objects_dir(&self.objects_dir)
1879            || self.skip_batch_packed_read_for_active_midx()
1880        {
1881            return Ok(None);
1882        }
1883        match pack::try_read_object_info_from_packs_with_options(
1884            &self.objects_dir,
1885            oid,
1886            pack::PackLookupOptions::ALL_LOCAL_PACKS,
1887        ) {
1888            Ok(info) => Ok(Some(info)),
1889            Err(Error::Object(ObjectError::NotFound { .. })) => Ok(None),
1890            Err(err) => Err(err),
1891        }
1892    }
1893
1894    /// Return the path to the `objects/` directory.
1895    ///
1896    /// This is always the repository layout path (including for custom primaries that do not
1897    /// store objects on disk). Prefer [`Self::files_objects_dir`] when the operation requires a
1898    /// files-backed primary; filesystem maintenance returns
1899    /// [`RepositoryError::UnsupportedObjectStore`] otherwise.
1900    #[must_use]
1901    pub fn objects_dir(&self) -> &Path {
1902        &self.objects_dir
1903    }
1904
1905    /// The commit-graph history walks consult for this database.
1906    ///
1907    /// A graph attached with [`OdbBuilder::commit_graph`] wins for any primary. Otherwise a
1908    /// files primary loads `objects/info/commit-graph` (or the split chain) at most once per
1909    /// repository handle. A custom primary never reads graph files from `objects/`: they
1910    /// describe whatever the files layout holds, not the custom store, and a walk trusting
1911    /// them would report commits the store does not have.
1912    ///
1913    /// `None` when no graph applies, or when a files-backed database is not attached to a
1914    /// repository's caches (built standalone); callers then read commits directly.
1915    pub(crate) fn commit_graph_chain(
1916        &self,
1917    ) -> Option<Arc<crate::commit_graph_file::CommitGraphChain>> {
1918        if let Some(chain) = &self.attached_commit_graph {
1919            return Some(Arc::clone(chain));
1920        }
1921        if self.primary.is_custom() {
1922            return None;
1923        }
1924        let caches = self.shared_config_state.as_ref()?;
1925        let mut alternate_object_dirs = Vec::new();
1926        if self.alternates_enabled {
1927            for alt in self.file_alternate_dirs_snapshot().iter() {
1928                if !alternate_object_dirs.iter().any(|d| d == alt) {
1929                    alternate_object_dirs.push(alt.clone());
1930                }
1931            }
1932            for alt in self.env_alternate_dirs_snapshot().iter() {
1933                if !alternate_object_dirs.iter().any(|d| d == alt) {
1934                    alternate_object_dirs.push(alt.clone());
1935                }
1936            }
1937        }
1938        caches.commit_graph_chain(self.objects_dir(), &alternate_object_dirs)
1939    }
1940
1941    fn try_read_extra_sources(&self, oid: &ObjectId) -> Result<Option<Object>> {
1942        for src in &self.extra_read_sources {
1943            if let Some(obj) = src.read(oid)? {
1944                return Ok(Some(obj));
1945            }
1946        }
1947        Ok(None)
1948    }
1949
1950    fn try_read_info_extra_sources(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
1951        for src in &self.extra_read_sources {
1952            if let Some(info) = src.read_info(oid)? {
1953                return Ok(Some(info));
1954            }
1955        }
1956        Ok(None)
1957    }
1958
1959    fn try_open_stream_extra_sources(
1960        &self,
1961        oid: &ObjectId,
1962    ) -> Result<Option<store::ObjectStream<'_>>> {
1963        for src in &self.extra_read_sources {
1964            if let Some(stream) = src.open_stream(oid)? {
1965                return Ok(Some(stream));
1966            }
1967        }
1968        Ok(None)
1969    }
1970
1971    /// Return the attached git directory, if one was set with
1972    /// [`Self::with_config_git_dir`].
1973    ///
1974    /// Used by config- and ref-aware operations (delta islands, on-disk delta
1975    /// reuse) that need the repository root rather than just the object store.
1976    #[must_use]
1977    pub fn config_git_dir(&self) -> Option<&Path> {
1978        self.config_git_dir.as_deref()
1979    }
1980
1981    /// Return the filesystem path for a given object ID.
1982    #[must_use]
1983    pub fn object_path(&self, oid: &ObjectId) -> PathBuf {
1984        oid.loose_path_in(&self.objects_dir)
1985    }
1986
1987    /// Pack indexes in this database's own `objects/pack` (not alternates), from
1988    /// the shared index cache.
1989    ///
1990    /// # Errors
1991    ///
1992    /// Propagates pack directory listing and index parse failures.
1993    pub(crate) fn local_pack_indexes(&self) -> Result<Vec<Arc<pack::PackIndex>>> {
1994        // Outside this database's pack-read context the listing would come from a fresh
1995        // store, which maps every index a second time beside the copies object reads use.
1996        self.with_primary_read_context(|| pack::read_local_pack_indexes_cached(&self.objects_dir))
1997    }
1998
1999    /// Pack indexes for collision-aware abbreviation (`log --oneline`, status rows).
2000    ///
2001    /// Empty-primary shared clones store objects only under alternates; abbreviation must
2002    /// consult those pack indexes instead of returning early and falling back to prefix scans.
2003    ///
2004    /// # Errors
2005    ///
2006    /// Propagates pack directory listing and index parse failures.
2007    pub(crate) fn pack_indexes_for_display(&self) -> Result<Vec<Arc<pack::PackIndex>>> {
2008        let local = self.local_pack_indexes()?;
2009        if !local.is_empty() || !self.alternate_object_lookup_needed() {
2010            return Ok(local);
2011        }
2012        let alts = self.file_alternate_dirs_snapshot();
2013        let Some(alt) = alts.first() else {
2014            return Ok(local);
2015        };
2016        let dir = alt.as_path();
2017        if crate::pack_store::PackStore::read_context_matches_objects_dir(dir) {
2018            return pack::read_local_pack_indexes_cached(dir);
2019        }
2020        self.with_objects_dir_pack_read_access(dir, || pack::read_local_pack_indexes_cached(dir))
2021    }
2022
2023    /// Whether any configured alternate object directory currently holds loose objects.
2024    ///
2025    /// Abbreviation can use pack-index neighbors alone only when every store that could
2026    /// collide is pack-only (borrow-only shared clones with no alternate loose).
2027    #[must_use]
2028    pub(crate) fn alternates_may_hold_loose_objects(&self) -> bool {
2029        if !self.alternates_enabled {
2030            return false;
2031        }
2032        for alt_dir in self.file_alternate_dirs_snapshot().iter() {
2033            if pack::objects_dir_has_loose_objects(alt_dir) {
2034                return true;
2035            }
2036        }
2037        for alt_dir in self.env_alternate_dirs_snapshot().iter() {
2038            if pack::objects_dir_has_loose_objects(alt_dir) {
2039                return true;
2040            }
2041        }
2042        if let Ok(guard) = self.submodule_alternate_dirs.lock() {
2043            for alt_dir in guard.iter() {
2044                if pack::objects_dir_has_loose_objects(alt_dir) {
2045                    return true;
2046                }
2047            }
2048        }
2049        false
2050    }
2051
2052    /// Whether `oid` is stored in a non-promisor pack under any alternate object directory.
2053    ///
2054    /// Loose objects in alternates do not count (Git `has_object_pack` / `prune-packed`).
2055    ///
2056    /// # Errors
2057    ///
2058    /// Propagates pack index read failures from an alternate directory.
2059    pub(crate) fn contained_in_alternate_pack(&self, oid: &ObjectId) -> Result<bool> {
2060        if !self.alternates_enabled {
2061            return Ok(false);
2062        }
2063        for alt_dir in self.file_alternate_dirs_snapshot().iter() {
2064            if store::object_in_non_promisor_pack(alt_dir, oid) {
2065                return Ok(true);
2066            }
2067        }
2068        for alt_dir in self.env_alternate_dirs_snapshot().iter() {
2069            if store::object_in_non_promisor_pack(alt_dir, oid) {
2070                return Ok(true);
2071            }
2072        }
2073        if let Ok(guard) = self.submodule_alternate_dirs.lock() {
2074            for alt_dir in guard.iter() {
2075                if store::object_in_non_promisor_pack(alt_dir, oid) {
2076                    return Ok(true);
2077                }
2078            }
2079        }
2080        Ok(false)
2081    }
2082
2083    /// Delete `oid`'s loose file from this database's own `objects/`, if there is one.
2084    ///
2085    /// Returns whether a file was removed. Packed copies and alternates are untouched;
2086    /// callers drop cached reads themselves if they keep any.
2087    ///
2088    /// # Errors
2089    ///
2090    /// Removal failures other than the file not existing.
2091    pub(crate) fn remove_local_loose(&self, oid: &ObjectId) -> Result<bool> {
2092        match fs::remove_file(self.object_path(oid)) {
2093            Ok(()) => Ok(true),
2094            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
2095            Err(err) => Err(Error::Io(err)),
2096        }
2097    }
2098
2099    /// Size in bytes of `oid`'s loose file in this database's own `objects/`,
2100    /// or `None` when it is not stored loose here.
2101    pub(crate) fn local_loose_file_size(&self, oid: &ObjectId) -> Option<u64> {
2102        fs::metadata(self.object_path(oid))
2103            .ok()
2104            .filter(fs::Metadata::is_file)
2105            .map(|meta| meta.len())
2106    }
2107
2108    /// Whether the object exists under this database directory only (loose or local packs).
2109    ///
2110    /// Unlike [`Self::exists`], this ignores `info/alternates` and
2111    /// `GIT_ALTERNATE_OBJECT_DIRECTORIES`. Used for partial-clone bookkeeping where
2112    /// objects reachable via alternates are still treated as "missing" until copied locally.
2113    ///
2114    /// Objects stored **only** in promisor packs (sibling `.promisor` marker next to the
2115    /// `.pack`) are treated as absent: Git considers them fetchable on demand, and
2116    /// `rev-list --missing=print` lists them until materialized as loose objects or a
2117    /// non-promisor pack.
2118    ///
2119    /// The empty tree object is treated as present without a loose file (matches Git).
2120    ///
2121    /// A failing custom primary store counts as "absent"; decision paths inside the
2122    /// crate use the fallible form, which propagates the backend error.
2123    #[must_use]
2124    pub fn exists_local(&self, oid: &ObjectId) -> bool {
2125        self.try_exists_local(oid).unwrap_or(false)
2126    }
2127
2128    /// Fallible [`Self::exists_local`]: errors from a custom primary store propagate.
2129    pub(crate) fn try_exists_local(&self, oid: &ObjectId) -> Result<bool> {
2130        if self.is_empty_tree(oid) {
2131            return Ok(true);
2132        }
2133        match &self.primary {
2134            PrimaryStore::Custom(primary) => primary.contains(oid),
2135            PrimaryStore::Files(_) => Ok(self.with_pack_store_for(&self.objects_dir, || {
2136                exists_materialized_in_objects_dir(&self.objects_dir, oid)
2137            })),
2138        }
2139    }
2140
2141    /// Whether `oid` is stored locally in loose storage or any pack (including promisor).
2142    ///
2143    /// Unlike [`Self::exists_local`], objects present only in promisor-marked packs count
2144    /// as stored. Does not trigger lazy fetch or consult alternates.
2145    ///
2146    /// A failing custom primary store counts as "absent"; decision paths inside the
2147    /// crate use the fallible form, which propagates the backend error.
2148    #[must_use]
2149    pub fn exists_stored(&self, oid: &ObjectId) -> bool {
2150        self.try_exists_stored(oid).unwrap_or(false)
2151    }
2152
2153    /// Fallible [`Self::exists_stored`]: errors from a custom primary store propagate.
2154    pub(crate) fn try_exists_stored(&self, oid: &ObjectId) -> Result<bool> {
2155        if oid.is_canonical_empty_tree() || self.overlay_read(oid).is_some() {
2156            return Ok(true);
2157        }
2158        match &self.primary {
2159            PrimaryStore::Custom(primary) => primary.contains(oid),
2160            PrimaryStore::Files(_) => Ok(self.with_pack_store_for(&self.objects_dir, || {
2161                store::local_object_stored(&self.objects_dir, oid)
2162            })),
2163        }
2164    }
2165
2166    /// Whether `oid` is stored on disk in this repository's object store (loose or
2167    /// non-promisor pack), without treating the canonical empty tree as virtually
2168    /// present.
2169    ///
2170    /// Use this when deciding whether a peer already holds an object for incremental
2171    /// local transfer; [`Self::exists`] and [`Self::exists_local`] treat the empty
2172    /// tree as present even when no object file exists.
2173    ///
2174    /// A failing custom primary store counts as "absent".
2175    #[must_use]
2176    pub fn exists_materialized_local(&self, oid: &ObjectId) -> bool {
2177        match &self.primary {
2178            PrimaryStore::Custom(primary) => primary.contains(oid).unwrap_or(false),
2179            PrimaryStore::Files(_) => self.with_pack_store_for(&self.objects_dir, || {
2180                exists_materialized_in_objects_dir(&self.objects_dir, oid)
2181            }),
2182        }
2183    }
2184
2185    /// Bring this repository's cached pack listing up to date with `objects/pack/`.
2186    ///
2187    /// Call once before a batch of [`Self::exists_materialized_local_without_rescan`]
2188    /// probes so packs written before the batch are visible.
2189    pub(crate) fn reprepare_local_packs(&self) {
2190        if self.primary.is_custom() {
2191            return;
2192        }
2193        self.with_pack_store_for(&self.objects_dir, || {
2194            let _ = crate::pack::reprepare_pack_directory_on_miss(&self.objects_dir);
2195        });
2196    }
2197
2198    /// Like [`Self::exists_materialized_local`], but a miss does not rescan
2199    /// `objects/pack/`.
2200    ///
2201    /// For walks that probe many objects that are expected to be absent (local
2202    /// clone/fetch/push boundary checks): each miss would otherwise list the pack
2203    /// directory again. Packs that appear after [`Self::reprepare_local_packs`] are
2204    /// not seen, so a miss can be stale; callers must treat it as "send anyway".
2205    pub(crate) fn exists_materialized_local_without_rescan(&self, oid: &ObjectId) -> bool {
2206        if self.primary.is_custom() {
2207            return self.exists_materialized_local(oid);
2208        }
2209        self.with_pack_store_for(&self.objects_dir, || {
2210            store::local_object_materialized_without_rescan(&self.objects_dir, oid)
2211        })
2212    }
2213
2214    /// Whether a custom primary holds no objects yet.
2215    ///
2216    /// Uses one enumeration pass and no `contains` / `contains_many` probes. Returns
2217    /// `Ok(false)` when the primary is files-backed.
2218    ///
2219    /// # Errors
2220    ///
2221    /// Propagates the primary store's [`ObjectStore::for_each_object`] failure.
2222    pub(crate) fn custom_primary_is_empty(&self) -> Result<bool> {
2223        use std::ops::ControlFlow;
2224        let PrimaryStore::Custom(primary) = &self.primary else {
2225            return Ok(false);
2226        };
2227        let mut empty = true;
2228        primary.for_each_object(&mut |oid| {
2229            let _ = oid;
2230            empty = false;
2231            ControlFlow::Break(())
2232        })?;
2233        Ok(empty)
2234    }
2235
2236    /// The ids from `oids` that the custom primary does not materialize, in input order.
2237    ///
2238    /// Asks the primary once with [`ObjectStore::contains_many`]. The canonical empty
2239    /// tree is not treated as present, and read sources and alternates are not consulted
2240    /// (same scope as [`Self::exists_materialized_local`]).
2241    ///
2242    /// # Errors
2243    ///
2244    /// Propagates the primary store failure. A files-backed primary answers each id with
2245    /// [`Self::exists_materialized_local`] instead.
2246    pub(crate) fn missing_materialized_many(&self, oids: &[ObjectId]) -> Result<Vec<ObjectId>> {
2247        let PrimaryStore::Custom(primary) = &self.primary else {
2248            return Ok(oids
2249                .iter()
2250                .filter(|oid| !self.exists_materialized_local(oid))
2251                .copied()
2252                .collect());
2253        };
2254        if oids.is_empty() {
2255            return Ok(Vec::new());
2256        }
2257        let present = primary.contains_many(oids)?;
2258        Ok(oids
2259            .iter()
2260            .zip(present)
2261            .filter_map(|(oid, has)| (!has).then_some(*oid))
2262            .collect())
2263    }
2264
2265    /// Whether `oid` is in this database: the primary store, any extra read source
2266    /// ([`OdbBuilder::push_read_source`]) or an alternate object directory.
2267    ///
2268    /// The canonical empty tree is always present. Sources are probed in the same order
2269    /// [`Self::read`] uses, and a source that fails stops the probe just as it stops a
2270    /// read, so `contains` never reports an object that `read` cannot return.
2271    ///
2272    /// # Errors
2273    ///
2274    /// The first source failure (for example an [`Error::Io`] from a network- or
2275    /// database-backed store), instead of reporting the object as present or missing.
2276    pub fn contains(&self, oid: &ObjectId) -> Result<bool> {
2277        self.probe_sources(oid, Err)
2278    }
2279
2280    /// Probe every source for `oid` in lookup order; `on_err` decides whether a failing
2281    /// source aborts the probe (`Err`) or is skipped (`Ok`).
2282    fn probe_sources(
2283        &self,
2284        oid: &ObjectId,
2285        mut on_err: impl FnMut(Error) -> Result<()>,
2286    ) -> Result<bool> {
2287        #[cfg(test)]
2288        self.exists_probe.fetch_add(1, Ordering::Relaxed);
2289        if self.is_empty_tree(oid) || self.overlay_read(oid).is_some() {
2290            return Ok(true);
2291        }
2292        let mut found = |probe: Result<bool>| match probe {
2293            Ok(present) => Ok(present),
2294            Err(err) => on_err(err).map(|()| false),
2295        };
2296        if found(self.open_primary().and_then(|p| p.contains(oid)))? {
2297            return Ok(true);
2298        }
2299        for src in &self.extra_read_sources {
2300            if found(src.contains(oid))? {
2301                return Ok(true);
2302            }
2303        }
2304        if !self.alternate_object_lookup_needed() {
2305            return Ok(false);
2306        }
2307        found(self.sources().and_then(|s| s.contains(oid)))
2308    }
2309
2310    /// [`Self::contains`] for every id in `oids`, one answer per id in input order.
2311    ///
2312    /// Each source is asked once about the ids no earlier source holds, through
2313    /// [`ObjectStore::contains_many`], so a database- or network-backed primary answers
2314    /// the whole batch in one round trip instead of one per id.
2315    ///
2316    /// # Errors
2317    ///
2318    /// The first source failure, as for [`Self::contains`].
2319    pub(crate) fn contains_many(&self, oids: &[ObjectId]) -> Result<Vec<bool>> {
2320        #[cfg(test)]
2321        self.exists_probe.fetch_add(oids.len(), Ordering::Relaxed);
2322        let mut present: Vec<bool> = oids
2323            .iter()
2324            .map(|oid| self.is_empty_tree(oid) || self.overlay_read(oid).is_some())
2325            .collect();
2326        let mut pending: Vec<usize> = (0..oids.len()).filter(|&i| !present[i]).collect();
2327        store::resolve_pending(oids, &mut present, &mut pending, |batch| {
2328            self.open_primary()?.contains_many(batch)
2329        })?;
2330        for src in &self.extra_read_sources {
2331            store::resolve_pending(oids, &mut present, &mut pending, |batch| {
2332                src.contains_many(batch)
2333            })?;
2334        }
2335        if !pending.is_empty() && self.alternate_object_lookup_needed() {
2336            store::resolve_pending(oids, &mut present, &mut pending, |batch| {
2337                self.sources()?.contains_many(batch)
2338            })?;
2339        }
2340        Ok(present)
2341    }
2342
2343    /// The oids from `oids` that [`Self::contains`] reports present, in input order.
2344    ///
2345    /// # Errors
2346    ///
2347    /// Propagates the first [`Self::contains`] failure.
2348    pub(crate) fn present_oids(
2349        &self,
2350        oids: impl IntoIterator<Item = ObjectId>,
2351    ) -> Result<Vec<ObjectId>> {
2352        self.partition_oids(oids, true)
2353    }
2354
2355    /// The oids from `oids` that [`Self::contains`] reports missing, in input order.
2356    ///
2357    /// # Errors
2358    ///
2359    /// Propagates the first [`Self::contains`] failure.
2360    pub(crate) fn missing_oids(
2361        &self,
2362        oids: impl IntoIterator<Item = ObjectId>,
2363    ) -> Result<Vec<ObjectId>> {
2364        self.partition_oids(oids, false)
2365    }
2366
2367    /// The oids from `oids` whose [`Self::contains_many`] answer equals `want_present`.
2368    fn partition_oids(
2369        &self,
2370        oids: impl IntoIterator<Item = ObjectId>,
2371        want_present: bool,
2372    ) -> Result<Vec<ObjectId>> {
2373        let oids: Vec<ObjectId> = oids.into_iter().collect();
2374        let present = self.contains_many(&oids)?;
2375        Ok(oids
2376            .into_iter()
2377            .zip(present)
2378            .filter_map(|(oid, has)| (has == want_present).then_some(oid))
2379            .collect())
2380    }
2381
2382    /// The oids from `oids` that are not stored locally per [`Self::exists_stored`]
2383    /// (alternates are not consulted), in input order.
2384    ///
2385    /// `objects/pack/` is rescanned once for the whole batch, not once per missing
2386    /// object: a partial clone asks this about thousands of absent blobs at a time.
2387    ///
2388    /// # Errors
2389    ///
2390    /// Propagates the first failure of a custom primary store.
2391    pub(crate) fn missing_stored_oids(
2392        &self,
2393        oids: impl IntoIterator<Item = ObjectId>,
2394    ) -> Result<Vec<ObjectId>> {
2395        if self.primary.is_custom() {
2396            return filter_oids(oids, |oid| self.try_exists_stored(oid).map(|has| !has));
2397        }
2398        self.reprepare_local_packs();
2399        self.with_pack_store_for(&self.objects_dir, || {
2400            filter_oids(oids, |oid| {
2401                Ok(!(oid.is_canonical_empty_tree()
2402                    || self.overlay_read(oid).is_some()
2403                    || store::local_object_stored_without_rescan(&self.objects_dir, oid)))
2404            })
2405        })
2406    }
2407
2408    /// Lenient [`Self::contains`]: a source that fails is skipped, so a later source can
2409    /// still answer `true` and an object no healthy source holds counts as absent.
2410    ///
2411    /// Use only for advisory probes. Where "missing" changes what happens next (what to
2412    /// fetch or send, whether a ref is broken), call [`Self::contains`] so a backend
2413    /// outage surfaces as an error rather than as a missing object.
2414    #[must_use]
2415    pub fn exists(&self, oid: &ObjectId) -> bool {
2416        self.probe_sources(oid, |_| Ok(())).unwrap_or(false)
2417    }
2418
2419    /// Run `f` with this [`Odb`]'s [`PackStore`] for `objects_dir` (primary or alternate).
2420    fn with_pack_store_for<R>(&self, objects_dir: &Path, f: impl FnOnce() -> R) -> R {
2421        let store = self.pack_store_for(objects_dir);
2422        PackStore::with_context(store, f)
2423    }
2424
2425    /// Run `f` with pack read caches for `objects_dir` without nesting away from the primary
2426    /// pack-read context (alternate directories during a primary object walk).
2427    pub(crate) fn with_objects_dir_pack_read_access<R>(
2428        &self,
2429        objects_dir: &Path,
2430        f: impl FnOnce() -> R,
2431    ) -> R {
2432        if PackStore::read_context_matches_objects_dir(objects_dir) {
2433            f()
2434        } else if PackStore::has_context() {
2435            pack::with_alternate_pack_store(self.pack_store_for(objects_dir), f)
2436        } else {
2437            PackStore::with_context(self.pack_store_for(objects_dir), f)
2438        }
2439    }
2440
2441    /// Skip probing the empty primary store when objects are expected from alternates.
2442    ///
2443    /// A later primary retry still runs on total miss ([`Self::object_not_found_after_primary_revalidate`])
2444    /// so locally materialized primary loose objects remain visible.
2445    fn skip_primary_for_alternate_backed_reads(&self) -> bool {
2446        !self.primary.is_custom()
2447            && self.alternates_enabled
2448            && self.alternate_object_lookup_needed()
2449            && crate::pack::pack_cache::primary_has_verified_empty_listing(&self.objects_dir)
2450    }
2451
2452    /// Run a read against the primary store.
2453    ///
2454    /// Only the files primary reads packs under `objects/`, so only it gets this database's
2455    /// pack-read context; installing that context costs a path copy and a cache warm-up per
2456    /// call, which a custom primary would pay on every object for nothing.
2457    fn with_primary_read_context<R>(&self, f: impl FnOnce() -> R) -> R {
2458        if self.primary.is_custom()
2459            || PackStore::read_context_matches_objects_dir(&self.objects_dir)
2460        {
2461            f()
2462        } else {
2463            self.with_pack_store_for(&self.objects_dir, f)
2464        }
2465    }
2466
2467    /// Pack store whose read context batch walks should install.
2468    ///
2469    /// Shared clones with a verified-empty primary borrow objects from the first file
2470    /// alternate; reading through the overlay on an empty primary store is slower than
2471    /// using that alternate as the active context for the walk.
2472    fn pack_read_context_store(&self) -> std::sync::Arc<crate::pack_store::PackStore> {
2473        if self.skip_primary_for_alternate_backed_reads() {
2474            if let Some(alt) = self.file_alternate_dirs_snapshot().first() {
2475                return self.pack_store_for(alt);
2476            }
2477        }
2478        self.pack_store_for(&self.objects_dir)
2479    }
2480
2481    /// Run `f` with pack read caches for this database's primary `objects/` directory.
2482    ///
2483    /// Use for batch workloads (for example `cat-file --batch`) so each object read does not
2484    /// reinstall thread-local pack context.
2485    pub fn with_pack_read_context<R>(&self, f: impl FnOnce() -> R) -> R {
2486        let store = self.pack_read_context_store();
2487        let on_primary = store.objects_dir() == self.objects_dir.as_path();
2488        crate::pack_store::PackStore::with_context(store, || {
2489            if on_primary {
2490                self.pin_shared_alternate_pack_store_if_needed();
2491            }
2492            f()
2493        })
2494    }
2495
2496    fn pin_shared_alternate_pack_store_if_needed(&self) {
2497        if !self.skip_primary_for_alternate_backed_reads() {
2498            return;
2499        }
2500        let alts = self.file_alternate_dirs_snapshot();
2501        let Some(alt) = alts.first() else {
2502            return;
2503        };
2504        let store = self.pack_store_for(alt);
2505        pack::with_alternate_pack_store(store, || ());
2506    }
2507
2508    /// Install the pack read context of [`Self::with_pack_read_context`] on the current
2509    /// thread until the returned guard drops (for long-lived worker threads).
2510    pub(crate) fn pack_read_context_guard(&self) -> crate::pack_store::PackReadContextGuard {
2511        let store = self.pack_read_context_store();
2512        let on_primary = store.objects_dir() == self.objects_dir.as_path();
2513        let guard = crate::pack_store::PackReadContextGuard::install(store);
2514        if on_primary {
2515            self.pin_shared_alternate_pack_store_if_needed();
2516        }
2517        guard
2518    }
2519
2520    /// Open a reader over the single local pack for a long object walk.
2521    ///
2522    /// Returns `None` unless [`Self::with_pack_read_context`] is active for this database,
2523    /// there is no custom primary store, and exactly one local pack exists (the conditions
2524    /// under which the files store's [`Self::read`] path opens the same reader per call). A
2525    /// reader miss is not authoritative: callers must fall back to [`Self::read`] for
2526    /// objects it does not find.
2527    pub(crate) fn open_session_pack_reader(&self) -> Result<Option<pack::SingleLocalPackReader>> {
2528        if self.primary.is_custom()
2529            || !PackStore::read_context_matches_objects_dir(&self.objects_dir)
2530        {
2531            return Ok(None);
2532        }
2533        self.sync_delta_base_cache_limit();
2534        pack::SingleLocalPackReader::open_allow_loose(&self.objects_dir)
2535    }
2536
2537    /// Touch the loose object file or pack file containing `oid`, matching Git's
2538    /// `odb_freshen_object` (updates mtime so age-based prune keeps recently re-referenced objects).
2539    ///
2540    /// Returns `true` if an on-disk object was found and touched.
2541    #[must_use]
2542    pub fn freshen_object(&self, oid: &ObjectId) -> bool {
2543        if self.is_empty_tree(oid) {
2544            return false;
2545        }
2546
2547        let loose = self.object_path(oid);
2548        if loose.is_file() {
2549            return self.touch_object_mtime(&loose).is_some();
2550        }
2551        self.freshen_packed_or_alternate(oid)
2552    }
2553
2554    /// [`Self::freshen_object`] without the loose probe in this repository's object
2555    /// directory: touch the local pack holding `oid` (cached listing, no rescan) or a
2556    /// loose or packed copy in an alternate object directory.
2557    fn freshen_packed_or_alternate(&self, oid: &ObjectId) -> bool {
2558        if self.is_empty_tree(oid) {
2559            return false;
2560        }
2561        if self.freshen_packed_in_objects_dir(&self.objects_dir, oid) {
2562            return true;
2563        }
2564
2565        let file_alts = self.file_alternate_dirs_snapshot();
2566        for alt_dir in file_alts.iter() {
2567            if self.freshen_object_in_objects_dir(alt_dir, oid) {
2568                return true;
2569            }
2570        }
2571
2572        for alt_dir in self.env_alternate_dirs_snapshot().iter() {
2573            if self.freshen_object_in_objects_dir(alt_dir, oid) {
2574                return true;
2575            }
2576        }
2577
2578        if let Ok(guard) = self.submodule_alternate_dirs.lock() {
2579            for alt_dir in guard.iter() {
2580                if self.freshen_object_in_objects_dir(alt_dir, oid) {
2581                    return true;
2582                }
2583            }
2584        }
2585
2586        false
2587    }
2588
2589    fn freshen_object_in_objects_dir(&self, objects_dir: &Path, oid: &ObjectId) -> bool {
2590        let loose = objects_dir
2591            .join(oid.loose_prefix())
2592            .join(oid.loose_suffix());
2593        if loose.is_file() {
2594            return self.touch_object_mtime(&loose).is_some();
2595        }
2596        self.freshen_packed_in_objects_dir(objects_dir, oid)
2597    }
2598
2599    fn freshen_packed_in_objects_dir(&self, objects_dir: &Path, oid: &ObjectId) -> bool {
2600        self.with_pack_store_for(objects_dir, || {
2601            let Ok(indexes) = pack::read_local_pack_indexes_cached(objects_dir) else {
2602                return false;
2603            };
2604            for idx in &indexes {
2605                if idx.contains(oid).unwrap_or(false) {
2606                    return self.freshen_pack_once(&idx.pack_path, idx.is_cruft);
2607                }
2608            }
2609            false
2610        })
2611    }
2612
2613    /// Touch `pack_path`'s mtime at most once for this [`Odb`], refreshing the pack cache signature.
2614    ///
2615    /// The path is recorded in [`Self::freshened_packs`] only after a successful touch, matching
2616    /// Git's `packed_git->freshened` assignment after `utime` succeeds.
2617    fn freshen_pack_once(&self, pack_path: &Path, is_cruft: bool) -> bool {
2618        let Ok(mut guard) = self.freshened_packs.lock() else {
2619            return false;
2620        };
2621        if guard.contains(pack_path) {
2622            return true;
2623        }
2624        if is_cruft {
2625            return false;
2626        }
2627        let Some(touched_at) = self.touch_object_mtime(pack_path) else {
2628            return false;
2629        };
2630        pack::refresh_pack_bytes_signature(pack_path, touched_at);
2631        guard.insert(pack_path.to_path_buf());
2632        true
2633    }
2634
2635    /// [`WriteOptions`] for storing many worktree blobs while staging (`add`, restage).
2636    ///
2637    /// Returns [`BULK_NEW_LOOSE_WRITE`] when this database has no local pack and no
2638    /// alternate object directory, so only the loose path can hold a copy and nothing
2639    /// else is probed. Otherwise the options also set [`WriteOptions::freshen_existing`],
2640    /// so content already stored in a pack or alternate is freshened instead of written
2641    /// again as a loose object. Call once per batch: the pack listing is read here, so
2642    /// workers probe already-loaded indexes.
2643    #[must_use]
2644    pub fn bulk_stage_write_options(&self) -> WriteOptions {
2645        let stored_beyond_loose = !self.primary.is_custom()
2646            && (self.alternate_object_lookup_needed()
2647                || self.with_pack_read_context(|| {
2648                    pack::read_local_pack_indexes_cached(&self.objects_dir)
2649                        .is_ok_and(|indexes| !indexes.is_empty())
2650                }));
2651        WriteOptions {
2652            freshen_existing: stored_beyond_loose,
2653            ..BULK_NEW_LOOSE_WRITE
2654        }
2655    }
2656
2657    /// When `oid` is already reachable, freshen it and return its id. Returns `None` when the
2658    /// object lives only in a pack and freshening failed so the caller can materialize a loose copy.
2659    fn try_freshen_existing(&self, oid: &ObjectId) -> Option<ObjectId> {
2660        if let Ok(primary) = self.files_primary() {
2661            if let Ok(Some(existing)) =
2662                primary.try_finish_duplicate_write(oid, WriteOptions::default())
2663            {
2664                return Some(existing);
2665            }
2666        }
2667        if !self.exists(oid) {
2668            return None;
2669        }
2670        if self.freshen_object(oid) {
2671            return Some(*oid);
2672        }
2673        None
2674    }
2675
2676    fn try_freshen_existing_local(&self, oid: &ObjectId) -> Option<ObjectId> {
2677        let primary = self.files_primary().ok()?;
2678        primary
2679            .try_finish_duplicate_write(
2680                oid,
2681                WriteOptions {
2682                    assume_loose_only_existence: true,
2683                    ..WriteOptions::default()
2684                },
2685            )
2686            .ok()
2687            .flatten()
2688    }
2689
2690    /// Whether an object is already stored for [`Self::write_with`] deduplication.
2691    ///
2692    /// Like [`Self::exists`], but the well-known empty tree counts as present only when
2693    /// materialized on disk (see [`Self::write_local`]).
2694    fn object_exists_for_write_skip(&self, oid: &ObjectId) -> bool {
2695        if self.is_empty_tree(oid) {
2696            self.exists_materialized_local(oid)
2697        } else {
2698            self.exists(oid)
2699        }
2700    }
2701
2702    /// Read a loose object file at `path`, verifying the uncompressed payload hashes to `expected_oid`.
2703    ///
2704    /// Git stores loose objects under paths derived from the OID; if the file contents hash to a
2705    /// different id (for example after a mistaken `mv`), this returns [`crate::error::ObjectError::LooseHashMismatch`].
2706    ///
2707    /// # Errors
2708    ///
2709    /// - [`crate::error::ObjectError::CorruptLoose`] — stored bytes could not be decoded (wraps zlib/header/EOF).
2710    /// - [`crate::error::ObjectError::LooseHashMismatch`] — payload OID does not match `expected_oid`.
2711    pub fn read_loose_verify_oid(path: &Path, expected_oid: &ObjectId) -> Result<Object> {
2712        LooseStore::read_verify_oid(path, expected_oid)
2713    }
2714
2715    fn local_loose(&self) -> Result<LooseStore> {
2716        self.primary
2717            .require_files_primary(FilesOnlyOperation::LooseWrite)?;
2718        Ok(LooseStore::new_with_negative_cache(
2719            self.objects_dir.clone(),
2720            self.hash_algo(),
2721            self.loose_compression()?,
2722            self.loose_negative_cache_for(&self.objects_dir),
2723        ))
2724    }
2725
2726    fn loose_at(&self, objects_dir: &Path) -> Result<LooseStore> {
2727        Ok(LooseStore::new_with_negative_cache(
2728            objects_dir.to_path_buf(),
2729            self.hash_algo(),
2730            self.loose_compression()?,
2731            self.loose_negative_cache_for(objects_dir),
2732        ))
2733    }
2734
2735    /// Read and decompress an object from the loose store.
2736    ///
2737    /// # Errors
2738    ///
2739    /// - [`crate::error::ObjectError::NotFound`] — no file at the expected path.
2740    /// - [`crate::error::ObjectError::CorruptLoose`] / [`crate::error::ObjectError::CorruptPacked`] — stored copy is damaged.
2741    pub fn read(&self, oid: &ObjectId) -> Result<Object> {
2742        self.read_impl(oid, true)
2743    }
2744
2745    /// `remember` keeps a copy in the session loose-read cache; callers that cache a
2746    /// parsed form themselves skip it.
2747    fn read_impl(&self, oid: &ObjectId, remember: bool) -> Result<Object> {
2748        if self.is_empty_tree(oid) {
2749            return Ok(Object {
2750                kind: ObjectKind::Tree,
2751                data: Vec::new(),
2752            });
2753        }
2754
2755        if let Some(obj) = self.session_cached_loose_read(oid) {
2756            return Ok(obj);
2757        }
2758
2759        if let Some(obj) = self.overlay_read(oid) {
2760            return Ok(obj);
2761        }
2762        if let Some(obj) = self.try_read_packed_in_batch_context(oid)? {
2763            return Ok(obj);
2764        }
2765
2766        let use_midx = self.multi_pack_index_reads_enabled();
2767        if use_midx {
2768            self.ensure_midx_prepared();
2769        }
2770
2771        self.sync_delta_base_cache_limit();
2772
2773        let mut unreadable_local_loose = None;
2774        if !self.skip_primary_for_alternate_backed_reads() {
2775            let primary = self.open_primary()?;
2776            let read_primary = || primary.read(oid);
2777            match self.with_primary_read_context(read_primary) {
2778                Ok(Some(obj)) => return self.finish_session_loose_read(oid, obj, remember),
2779                Ok(None) => {}
2780                Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
2781                    unreadable_local_loose = Some(err);
2782                }
2783                Err(err) => return Err(err),
2784            }
2785        }
2786
2787        if let Some(obj) = self.try_read_extra_sources(oid)? {
2788            return self.finish_session_loose_read(oid, obj, remember);
2789        }
2790
2791        if self.alternates_enabled {
2792            match self.sources()?.read(oid) {
2793                Ok(Some(obj)) => return self.finish_session_loose_read(oid, obj, remember),
2794                Ok(None) => {}
2795                Err(err) => return Err(err),
2796            }
2797        }
2798
2799        if let Some(err) = unreadable_local_loose {
2800            return Err(err);
2801        }
2802
2803        self.read_after_promisor_miss(oid)
2804    }
2805
2806    #[cold]
2807    #[inline(never)]
2808    fn read_after_promisor_miss(&self, oid: &ObjectId) -> Result<Object> {
2809        let mut lazy_retries = 0u32;
2810        loop {
2811            let Some(res) = self.resolve_promisor_miss(oid, lazy_retries)? else {
2812                return self.object_not_found_after_primary_revalidate(oid);
2813            };
2814            match res {
2815                crate::promisor_fetch::PromisorMissResolution::RetryAfterFetch => {
2816                    lazy_retries += 1;
2817                    if let Some(obj) = self.try_read_once(oid)? {
2818                        return Ok(obj);
2819                    }
2820                }
2821                crate::promisor_fetch::PromisorMissResolution::NotPromisorRepo => {
2822                    return self.object_not_found_after_primary_revalidate(oid);
2823                }
2824                crate::promisor_fetch::PromisorMissResolution::PromisedMissing(err) => {
2825                    return Err(err);
2826                }
2827            }
2828        }
2829    }
2830
2831    /// Read available storage without consulting the promisor fetcher.
2832    /// Missing objects return `None`; corrupt storage still returns an error.
2833    pub(crate) fn try_read_once(&self, oid: &ObjectId) -> Result<Option<Object>> {
2834        if self.is_empty_tree(oid) {
2835            return Ok(Some(Object {
2836                kind: ObjectKind::Tree,
2837                data: Vec::new(),
2838            }));
2839        }
2840
2841        if let Some(obj) = self.session_cached_loose_read(oid) {
2842            return Ok(Some(obj));
2843        }
2844
2845        if let Some(obj) = self.overlay_read(oid) {
2846            return Ok(Some(obj));
2847        }
2848        if let Some(obj) = self.try_read_packed_in_batch_context(oid)? {
2849            return Ok(Some(self.finish_session_loose_read(oid, obj, true)?));
2850        }
2851
2852        let use_midx = self.multi_pack_index_reads_enabled();
2853        if use_midx {
2854            self.ensure_midx_prepared();
2855        }
2856
2857        self.sync_delta_base_cache_limit();
2858
2859        let mut unreadable_local_loose = None;
2860        if !self.skip_primary_for_alternate_backed_reads() {
2861            let primary = self.open_primary()?;
2862            let read_primary = || primary.read(oid);
2863            match self.with_primary_read_context(read_primary) {
2864                Ok(Some(obj)) => return Ok(Some(self.finish_session_loose_read(oid, obj, true)?)),
2865                Ok(None) => {}
2866                Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
2867                    unreadable_local_loose = Some(err);
2868                }
2869                Err(err) => return Err(err),
2870            }
2871        }
2872
2873        if let Some(obj) = self.try_read_extra_sources(oid)? {
2874            return Ok(Some(self.finish_session_loose_read(oid, obj, true)?));
2875        }
2876
2877        if self.alternates_enabled {
2878            match self.sources()?.read(oid) {
2879                Ok(Some(obj)) => return Ok(Some(self.finish_session_loose_read(oid, obj, true)?)),
2880                Ok(None) => {}
2881                Err(err) => return Err(err),
2882            }
2883        }
2884
2885        if let Some(err) = unreadable_local_loose {
2886            return Err(err);
2887        }
2888
2889        Ok(None)
2890    }
2891
2892    fn resolve_promisor_miss(
2893        &self,
2894        oid: &ObjectId,
2895        lazy_retries: u32,
2896    ) -> Result<Option<crate::promisor_fetch::PromisorMissResolution>> {
2897        let (Some(caches), Some(env)) = (&self.shared_config_state, &self.shared_environment)
2898        else {
2899            return Ok(None);
2900        };
2901        Ok(Some(crate::promisor_fetch::resolve_promisor_read_miss(
2902            caches,
2903            self,
2904            oid,
2905            env.as_ref(),
2906            lazy_retries,
2907        )?))
2908    }
2909
2910    /// Fetch a batch of missing promisor objects before bulk blob reads (tree diffs, checkout).
2911    ///
2912    /// No-ops when lazy promisor fetch is unavailable; per-object lazy fetch remains the fallback.
2913    ///
2914    /// # Errors
2915    ///
2916    /// Propagates transport and pack ingest failures from the promisor fetcher.
2917    pub(crate) fn prefetch_promisor_read_batch(
2918        &self,
2919        oids: impl IntoIterator<Item = ObjectId>,
2920    ) -> Result<()> {
2921        let (Some(caches), Some(env)) = (&self.shared_config_state, &self.shared_environment)
2922        else {
2923            return Ok(());
2924        };
2925        crate::promisor_fetch::prefetch_promisor_read_batch(caches, self, env.as_ref(), oids)
2926    }
2927
2928    /// Read and decompress an object into `buf`, reusing its capacity across calls.
2929    ///
2930    /// Resolution order matches [`Self::read`]. Returns a borrowed view of the payload
2931    /// stored in `buf`.
2932    ///
2933    /// # Errors
2934    ///
2935    /// Same as [`Self::read`].
2936    pub fn read_into(&self, oid: &ObjectId, buf: &mut Vec<u8>) -> Result<ObjectKind> {
2937        if self.is_empty_tree(oid) {
2938            buf.clear();
2939            return Ok(ObjectKind::Tree);
2940        }
2941
2942        if let Some(obj) = self.session_cached_loose_read(oid) {
2943            buf.clear();
2944            buf.extend_from_slice(&obj.data);
2945            return Ok(obj.kind);
2946        }
2947
2948        if let Some(obj) = self.overlay_read(oid) {
2949            buf.clear();
2950            buf.extend_from_slice(&obj.data);
2951            return Ok(obj.kind);
2952        }
2953
2954        if let Some(kind) = self.try_read_packed_in_batch_context_into(oid, false, buf)? {
2955            return Ok(kind);
2956        }
2957
2958        let use_midx = self.multi_pack_index_reads_enabled();
2959        if use_midx {
2960            self.ensure_midx_prepared();
2961        }
2962
2963        self.sync_delta_base_cache_limit();
2964
2965        let mut unreadable_local_loose = None;
2966        if !self.skip_primary_for_alternate_backed_reads() {
2967            let primary = self.open_primary()?;
2968            let read_primary = || primary.read_into(oid, buf);
2969            match self.with_primary_read_context(read_primary) {
2970                Ok(Some(kind)) => return Ok(kind),
2971                Ok(None) => {}
2972                Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
2973                    unreadable_local_loose = Some(err);
2974                }
2975                Err(err) => return Err(err),
2976            }
2977        }
2978
2979        if let Some(kind) = self.try_read_into_extra_sources(oid, buf)? {
2980            return Ok(kind);
2981        }
2982
2983        if self.alternates_enabled {
2984            match self.sources()?.read_into(oid, buf) {
2985                Ok(Some(kind)) => return Ok(kind),
2986                Ok(None) => {}
2987                Err(err) => return Err(err),
2988            }
2989        }
2990
2991        if let Some(err) = unreadable_local_loose {
2992            return Err(err);
2993        }
2994
2995        self.read_into_after_promisor_miss(oid, buf)
2996    }
2997
2998    /// Like [`Self::read_into`], but keep delta bases resolved from local packs in the
2999    /// delta-base cache, as [`Self::read`] does.
3000    ///
3001    /// For walks that read many objects sharing delta chains (successive root trees) and do
3002    /// not want the per-session object copy [`Self::read`] makes. Objects outside the local
3003    /// object directory (overlay, alternates, promisor fetches) and any local read failure go
3004    /// through [`Self::read`], so errors and fallbacks match it. A custom primary has no local
3005    /// packs, so its objects go through [`Self::read_into`] and the store's
3006    /// [`ObjectStore::read_into`].
3007    ///
3008    /// # Errors
3009    ///
3010    /// Same as [`Self::read`].
3011    pub(crate) fn read_into_caching_delta_bases(
3012        &self,
3013        oid: &ObjectId,
3014        buf: &mut Vec<u8>,
3015    ) -> Result<ObjectKind> {
3016        if let Some(kind) = self.try_read_packed_in_batch_context_into(oid, true, buf)? {
3017            return Ok(kind);
3018        }
3019        let slot = match &self.primary {
3020            PrimaryStore::Custom(_) => return self.read_into(oid, buf),
3021            PrimaryStore::Files(slot) => slot,
3022        };
3023        if !self.is_empty_tree(oid) {
3024            if let Ok(files) = self.open_files_source(slot) {
3025                self.ensure_midx_prepared();
3026                self.sync_delta_base_cache_limit();
3027                let mut read = || files.read_into_with_delta_policy(oid, true, buf);
3028                let local = if PackStore::read_context_matches_objects_dir(&self.objects_dir) {
3029                    read()
3030                } else {
3031                    self.with_pack_store_for(&self.objects_dir, read)
3032                };
3033                if let Ok(Some(kind)) = local {
3034                    return Ok(kind);
3035                }
3036            }
3037        }
3038        let object = self.read(oid)?;
3039        buf.clear();
3040        buf.extend_from_slice(&object.data);
3041        Ok(object.kind)
3042    }
3043
3044    /// Read only the header block of commit `oid` into `buf` when a local pack stores it whole.
3045    ///
3046    /// `buf` then ends with the blank line that closes the headers: it parses as the commit
3047    /// with an empty message, giving its tree, parents and dates without inflating the message.
3048    /// The entry is fetched with a positioned read, so walks that touch many scattered commits
3049    /// do not keep pack pages resident. Returns `false` when this shortcut does not apply (a
3050    /// custom primary store, a loose or deltified commit, an object that is not a commit, very
3051    /// long headers); read the whole object instead.
3052    ///
3053    /// # Errors
3054    ///
3055    /// Propagates pack directory listing and pack index lookup errors.
3056    pub(crate) fn read_packed_commit_header_block_into(
3057        &self,
3058        oid: &ObjectId,
3059        buf: &mut Vec<u8>,
3060    ) -> Result<bool> {
3061        let PrimaryStore::Files(slot) = &self.primary else {
3062            return Ok(false);
3063        };
3064        let Ok(files) = self.open_files_source(slot) else {
3065            return Ok(false);
3066        };
3067        files.read_packed_commit_header_block_into(oid, buf)
3068    }
3069
3070    /// [`Self::read_packed_commit_header_block_into`] for many commits, setting up the pack
3071    /// lookup and read buffers once for the batch.
3072    ///
3073    /// Calls `found(i, header)` for each `oids[i]` the shortcut applies to; read the others
3074    /// whole. Nothing is called when the primary store is custom.
3075    ///
3076    /// # Errors
3077    ///
3078    /// Propagates pack directory listing and pack index lookup errors.
3079    pub(crate) fn read_packed_commit_header_blocks(
3080        &self,
3081        oids: &[ObjectId],
3082        found: impl FnMut(usize, &[u8]),
3083    ) -> Result<()> {
3084        let PrimaryStore::Files(slot) = &self.primary else {
3085            return Ok(());
3086        };
3087        let Ok(files) = self.open_files_source(slot) else {
3088            return Ok(());
3089        };
3090        files.read_packed_commit_header_blocks(oids, found)
3091    }
3092
3093    #[cold]
3094    #[inline(never)]
3095    fn read_into_after_promisor_miss(
3096        &self,
3097        oid: &ObjectId,
3098        buf: &mut Vec<u8>,
3099    ) -> Result<ObjectKind> {
3100        let mut lazy_retries = 0u32;
3101        loop {
3102            let Some(res) = self.resolve_promisor_miss(oid, lazy_retries)? else {
3103                return self.object_kind_not_found_after_primary_revalidate(oid, buf);
3104            };
3105            match res {
3106                crate::promisor_fetch::PromisorMissResolution::RetryAfterFetch => {
3107                    lazy_retries += 1;
3108                    if let Some(kind) = self.try_read_into_once(oid, buf)? {
3109                        return Ok(kind);
3110                    }
3111                }
3112                crate::promisor_fetch::PromisorMissResolution::NotPromisorRepo => {
3113                    return self.object_kind_not_found_after_primary_revalidate(oid, buf);
3114                }
3115                crate::promisor_fetch::PromisorMissResolution::PromisedMissing(err) => {
3116                    return Err(err);
3117                }
3118            }
3119        }
3120    }
3121
3122    /// [`Self::try_read_once`] into `buf`, reusing its capacity: missing objects are `None`
3123    /// without consulting the promisor fetcher, and corrupt storage is an error.
3124    pub(crate) fn try_read_into_once(
3125        &self,
3126        oid: &ObjectId,
3127        buf: &mut Vec<u8>,
3128    ) -> Result<Option<ObjectKind>> {
3129        if oid.is_well_known_empty_tree() {
3130            buf.clear();
3131            return Ok(Some(ObjectKind::Tree));
3132        }
3133
3134        if let Some(obj) = self.session_cached_loose_read(oid) {
3135            buf.clear();
3136            buf.extend_from_slice(&obj.data);
3137            return Ok(Some(obj.kind));
3138        }
3139
3140        if let Some(obj) = self.overlay_read(oid) {
3141            buf.clear();
3142            buf.extend_from_slice(&obj.data);
3143            return Ok(Some(obj.kind));
3144        }
3145
3146        if let Some(kind) = self.try_read_packed_in_batch_context_into(oid, false, buf)? {
3147            return Ok(Some(kind));
3148        }
3149
3150        let use_midx = self.multi_pack_index_reads_enabled();
3151        if use_midx {
3152            self.ensure_midx_prepared();
3153        }
3154
3155        self.sync_delta_base_cache_limit();
3156
3157        let mut unreadable_local_loose = None;
3158        if !self.skip_primary_for_alternate_backed_reads() {
3159            let primary = self.open_primary()?;
3160            let read_primary = || primary.read_into(oid, buf);
3161            match self.with_primary_read_context(read_primary) {
3162                Ok(Some(kind)) => return Ok(Some(kind)),
3163                Ok(None) => {}
3164                Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
3165                    unreadable_local_loose = Some(err);
3166                }
3167                Err(err) => return Err(err),
3168            }
3169        }
3170
3171        if let Some(kind) = self.try_read_into_extra_sources(oid, buf)? {
3172            return Ok(Some(kind));
3173        }
3174
3175        if self.alternates_enabled {
3176            match self.sources()?.read_into(oid, buf) {
3177                Ok(Some(kind)) => return Ok(Some(kind)),
3178                Ok(None) => {}
3179                Err(err) => return Err(err),
3180            }
3181        }
3182
3183        if let Some(err) = unreadable_local_loose {
3184            return Err(err);
3185        }
3186
3187        Ok(None)
3188    }
3189
3190    fn try_read_into_extra_sources(
3191        &self,
3192        oid: &ObjectId,
3193        buf: &mut Vec<u8>,
3194    ) -> Result<Option<ObjectKind>> {
3195        for src in &self.extra_read_sources {
3196            if let Some(kind) = src.read_into(oid, buf)? {
3197                return Ok(Some(kind));
3198            }
3199        }
3200        Ok(None)
3201    }
3202
3203    fn try_read_packed_in_batch_context_into(
3204        &self,
3205        oid: &ObjectId,
3206        populate_delta_lru: bool,
3207        buf: &mut Vec<u8>,
3208    ) -> Result<Option<ObjectKind>> {
3209        if self.primary.is_custom()
3210            || !PackStore::read_context_matches_objects_dir(&self.objects_dir)
3211            || self.skip_batch_packed_read_for_active_midx()
3212        {
3213            return Ok(None);
3214        }
3215        self.sync_delta_base_cache_limit();
3216        match pack::try_read_object_from_packs_with_options_into(
3217            &self.objects_dir,
3218            oid,
3219            pack::PackLookupOptions::ALL_LOCAL_PACKS,
3220            populate_delta_lru,
3221            buf,
3222        ) {
3223            Ok(kind) => Ok(Some(kind)),
3224            Err(Error::Object(ObjectError::NotFound { .. })) => Ok(None),
3225            Err(err) => Err(err),
3226        }
3227    }
3228
3229    /// Return the kind and uncompressed size of `oid` without loading the full object body.
3230    ///
3231    /// Resolution order matches [`Self::read`]: in-memory overlay, multi-pack-index, local packs
3232    /// (MRU order, skipping MIDX-covered indexes when MIDX is enabled), loose objects, a pack
3233    /// directory re-prepare and pack retry, then alternates.
3234    ///
3235    /// # Errors
3236    ///
3237    /// - [`crate::error::ObjectError::NotFound`] — no object with this id in any consulted store.
3238    /// - [`crate::error::ObjectError::CorruptLoose`] / [`crate::error::ObjectError::CorruptPacked`] — stored copy is damaged.
3239    pub fn read_info(&self, oid: &ObjectId) -> Result<ObjectInfo> {
3240        if self.is_empty_tree(oid) {
3241            return Ok(ObjectInfo {
3242                kind: ObjectKind::Tree,
3243                size: 0,
3244            });
3245        }
3246
3247        if let Some(obj) = self.overlay_read(oid) {
3248            return Ok(ObjectInfo {
3249                kind: obj.kind,
3250                size: u64::try_from(obj.data.len()).map_err(|_| {
3251                    Error::Object(ObjectError::Corrupt {
3252                        detail: "object size overflow".to_owned(),
3253                    })
3254                })?,
3255            });
3256        }
3257
3258        if let Some(info) = self.try_read_info_packed_in_batch_context(oid)? {
3259            return Ok(info);
3260        }
3261
3262        let use_midx = self.multi_pack_index_reads_enabled();
3263        if use_midx {
3264            self.ensure_midx_prepared();
3265        }
3266
3267        let mut unreadable_local_loose = None;
3268        if !self.skip_primary_for_alternate_backed_reads() {
3269            let primary = self.open_primary()?;
3270            match primary.read_info(oid) {
3271                Ok(Some(info)) => return Ok(info),
3272                Ok(None) => {}
3273                Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
3274                    unreadable_local_loose = Some(err);
3275                }
3276                Err(err) => return Err(err),
3277            }
3278        }
3279
3280        if let Some(info) = self.try_read_info_extra_sources(oid)? {
3281            return Ok(info);
3282        }
3283
3284        if self.alternates_enabled {
3285            match self.sources()?.read_info(oid) {
3286                Ok(Some(info)) => return Ok(info),
3287                Ok(None) => {}
3288                Err(err) => return Err(err),
3289            }
3290        }
3291
3292        if let Some(err) = unreadable_local_loose {
3293            return Err(err);
3294        }
3295
3296        self.read_info_after_promisor_miss(oid)
3297    }
3298
3299    /// Object metadata for local-only probes, serving, and maintenance.
3300    ///
3301    /// Like [`Self::read_info`], but does not resolve promisor misses by fetching
3302    /// from a remote; missing local objects return [`crate::error::ObjectError::NotFound`].
3303    pub(crate) fn read_info_without_fetch(&self, oid: &ObjectId) -> Result<ObjectInfo> {
3304        match self.try_read_info_once(oid)? {
3305            Some(info) => Ok(info),
3306            None => self.object_info_not_found_after_primary_revalidate(oid),
3307        }
3308    }
3309
3310    /// Kind of `oid` when this database stores it, for checks that must not accept an
3311    /// object that is only implied.
3312    ///
3313    /// Header-only like [`Self::read_info_without_fetch`] (no promisor fetch), except that
3314    /// the empty tree counts only when a copy is actually stored (the overlay, the primary
3315    /// store or an alternate), since `git fsck` reports a ref to an unstored one as missing.
3316    ///
3317    /// # Errors
3318    ///
3319    /// Read failures other than a missing object (corrupt headers, I/O, a failing custom
3320    /// store).
3321    pub(crate) fn stored_object_kind(&self, oid: &ObjectId) -> Result<Option<ObjectKind>> {
3322        if oid.is_well_known_empty_tree() && !self.empty_tree_stored(oid) {
3323            return Ok(None);
3324        }
3325        match self.try_read_info_once(oid) {
3326            Ok(info) => Ok(info.map(|info| info.kind)),
3327            Err(Error::Object(ObjectError::NotFound { .. })) => Ok(None),
3328            Err(err) => Err(err),
3329        }
3330    }
3331
3332    fn empty_tree_stored(&self, oid: &ObjectId) -> bool {
3333        if self.overlay_read(oid).is_some() || self.exists_materialized_local(oid) {
3334            return true;
3335        }
3336        if !self.alternates_enabled {
3337            return false;
3338        }
3339        let file_dirs = self.file_alternate_dirs_snapshot();
3340        let env_dirs = self.env_alternate_dirs_snapshot();
3341        file_dirs
3342            .iter()
3343            .chain(env_dirs.iter())
3344            .any(|dir| self.with_pack_store_for(dir, || store::local_object_materialized(dir, oid)))
3345    }
3346
3347    #[cold]
3348    #[inline(never)]
3349    fn read_info_after_promisor_miss(&self, oid: &ObjectId) -> Result<ObjectInfo> {
3350        let mut lazy_retries = 0u32;
3351        loop {
3352            let Some(res) = self.resolve_promisor_miss(oid, lazy_retries)? else {
3353                return self.object_info_not_found_after_primary_revalidate(oid);
3354            };
3355            match res {
3356                crate::promisor_fetch::PromisorMissResolution::PromisedMissing(err) => {
3357                    return Err(err);
3358                }
3359                crate::promisor_fetch::PromisorMissResolution::NotPromisorRepo => {
3360                    return self.object_info_not_found_after_primary_revalidate(oid);
3361                }
3362                crate::promisor_fetch::PromisorMissResolution::RetryAfterFetch => {
3363                    lazy_retries += 1;
3364                    if let Some(info) = self.try_read_info_once(oid)? {
3365                        return Ok(info);
3366                    }
3367                }
3368            }
3369        }
3370    }
3371
3372    /// Header-only [`Self::try_read_once`]: kind and size from available storage, without
3373    /// consulting the promisor fetcher. Missing objects return `None`.
3374    pub(crate) fn try_read_info_once(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
3375        if self.is_empty_tree(oid) {
3376            return Ok(Some(ObjectInfo {
3377                kind: ObjectKind::Tree,
3378                size: 0,
3379            }));
3380        }
3381
3382        if let Some(obj) = self.overlay_read(oid) {
3383            return Ok(Some(ObjectInfo {
3384                kind: obj.kind,
3385                size: u64::try_from(obj.data.len()).map_err(|_| {
3386                    Error::Object(ObjectError::Corrupt {
3387                        detail: "object size overflow".to_owned(),
3388                    })
3389                })?,
3390            }));
3391        }
3392
3393        if let Some(info) = self.try_read_info_packed_in_batch_context(oid)? {
3394            return Ok(Some(info));
3395        }
3396
3397        let use_midx = self.multi_pack_index_reads_enabled();
3398        if use_midx {
3399            self.ensure_midx_prepared();
3400        }
3401
3402        let mut unreadable_local_loose = None;
3403        if !self.skip_primary_for_alternate_backed_reads() {
3404            let primary = self.open_primary()?;
3405            match primary.read_info(oid) {
3406                Ok(Some(info)) => return Ok(Some(info)),
3407                Ok(None) => {}
3408                Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
3409                    unreadable_local_loose = Some(err);
3410                }
3411                Err(err) => return Err(err),
3412            }
3413        }
3414
3415        if let Some(info) = self.try_read_info_extra_sources(oid)? {
3416            return Ok(Some(info));
3417        }
3418
3419        if self.alternates_enabled {
3420            match self.sources()?.read_info(oid) {
3421                Ok(Some(info)) => return Ok(Some(info)),
3422                Ok(None) => {}
3423                Err(err) => return Err(err),
3424            }
3425        }
3426
3427        if let Some(err) = unreadable_local_loose {
3428            return Err(err);
3429        }
3430
3431        Ok(None)
3432    }
3433
3434    /// Read `oid` unless its payload is larger than `limit` bytes, in which case
3435    /// [`BoundedRead::Larger`] is returned (for example so the caller can stream it with
3436    /// [`Self::with_stream`] instead).
3437    ///
3438    /// Costs about one [`Self::read`]: a loose object is opened once and inflation stops at
3439    /// its header when it is too large, and an object stored whole in a pack is sized from its
3440    /// entry header before it is read. A pack delta is always read whole, since reconstructing
3441    /// it needs the full object in memory anyway.
3442    ///
3443    /// `cache_small` reuses and retains small loose objects for bulk checkout; callers
3444    /// doing isolated writes can bypass that bookkeeping.
3445    ///
3446    /// # Errors
3447    ///
3448    /// Same as [`Self::read`], including [`crate::error::ObjectError::NotFound`].
3449    pub(crate) fn read_unless_larger(
3450        &self,
3451        oid: &ObjectId,
3452        limit: u64,
3453        cache_small: bool,
3454    ) -> Result<BoundedRead> {
3455        if cache_small {
3456            if let Some(read) = self.session_loose_reads.lock().ok().and_then(|cache| {
3457                cache.get(oid).map(|obj| {
3458                    if obj.data.len() as u64 > limit {
3459                        BoundedRead::Larger
3460                    } else {
3461                        BoundedRead::Object(obj.clone())
3462                    }
3463                })
3464            }) {
3465                return Ok(read);
3466            }
3467        }
3468        if !self.primary.is_custom() && !self.multi_pack_index_reads_enabled() {
3469            if let Some(read) =
3470                pack::pack_cache::try_read_object_via_single_pack_reader_unless_whole_larger(
3471                    &self.objects_dir,
3472                    oid,
3473                    limit,
3474                )?
3475            {
3476                return Ok(read);
3477            }
3478        }
3479        if let Ok(files) = self.files_primary() {
3480            if self.multi_pack_index_reads_enabled() {
3481                self.ensure_midx_prepared();
3482            }
3483            match files.read_unless_larger(oid, limit)? {
3484                LocalSizedRead::Packed(Some(size)) if size > limit => {
3485                    return Ok(BoundedRead::Larger);
3486                }
3487                LocalSizedRead::Packed(_) => return self.read(oid).map(BoundedRead::Object),
3488                LocalSizedRead::Loose(BoundedRead::Object(obj)) => {
3489                    if cache_small && obj.data.len() <= SESSION_BOUNDED_LOOSE_CACHE_MAX {
3490                        self.remember_session_loose_read(oid, &obj);
3491                    }
3492                    return Ok(BoundedRead::Object(obj));
3493                }
3494                LocalSizedRead::Loose(read) => return Ok(read),
3495                LocalSizedRead::Missing => {}
3496            }
3497        }
3498        let info = self.read_info(oid)?;
3499        if info.size > limit {
3500            return Ok(BoundedRead::Larger);
3501        }
3502        self.read(oid).map(BoundedRead::Object)
3503    }
3504
3505    /// Open a stream over `oid`'s uncompressed payload (overlay, primary, then alternates).
3506    ///
3507    /// The returned stream owns its payload: it is read whole into memory before returning.
3508    /// Use [`Self::with_stream`] to read a large object in bounded memory.
3509    ///
3510    /// # Errors
3511    ///
3512    /// Propagates backend failures other than a missing object (`Ok(None)`).
3513    pub fn open_stream(&self, oid: &ObjectId) -> Result<Option<ObjectStream<'static>>> {
3514        self.with_stream(oid, materialize_stream)
3515    }
3516
3517    /// Run `f` on a stream over `oid`'s uncompressed payload (overlay, primary, then alternates).
3518    ///
3519    /// Unlike [`Self::open_stream`] the payload is not buffered: loose objects and objects
3520    /// stored whole in a pack are inflated as `f` reads, so memory stays bounded however large
3521    /// the object is. Objects stored as pack deltas are reconstructed in memory first.
3522    ///
3523    /// # Parameters
3524    ///
3525    /// - `oid` — the object to stream.
3526    /// - `f` — consumes the stream; its result is returned as `Ok(Some(_))`.
3527    ///
3528    /// # Errors
3529    ///
3530    /// Propagates backend failures other than a missing object (`Ok(None)`, and `f` is not
3531    /// called), and any error returned by `f`. A corrupt or truncated object surfaces as an
3532    /// [`std::io::Error`] from the stream's reader.
3533    pub fn with_stream<R>(
3534        &self,
3535        oid: &ObjectId,
3536        f: impl FnOnce(ObjectStream<'_>) -> Result<R>,
3537    ) -> Result<Option<R>> {
3538        use std::io::Cursor;
3539        if self.is_empty_tree(oid) {
3540            return f(ObjectStream {
3541                kind: ObjectKind::Tree,
3542                size: 0,
3543                reader: Box::new(std::io::empty()),
3544            })
3545            .map(Some);
3546        }
3547        if let Some(obj) = self.overlay_read(oid) {
3548            let size = u64::try_from(obj.data.len()).map_err(|_| {
3549                Error::Object(ObjectError::Corrupt {
3550                    detail: format!("object size overflow for {}", oid.to_hex()),
3551                })
3552            })?;
3553            return f(ObjectStream {
3554                kind: obj.kind,
3555                size,
3556                reader: Box::new(Cursor::new(obj.data)),
3557            })
3558            .map(Some);
3559        }
3560        if self.multi_pack_index_reads_enabled() {
3561            self.ensure_midx_prepared();
3562        }
3563        self.sync_delta_base_cache_limit();
3564        let primary = self.open_primary()?;
3565        let mut unreadable_local_loose = None;
3566        match primary.open_stream(oid) {
3567            Ok(Some(stream)) => return f(stream).map(Some),
3568            Ok(None) => {}
3569            Err(err) if primary.local_loose_exists_but_unreadable(oid, &err) => {
3570                unreadable_local_loose = Some(err);
3571            }
3572            Err(err) => return Err(err),
3573        }
3574        if let Some(stream) = self.try_open_stream_extra_sources(oid)? {
3575            return f(stream).map(Some);
3576        }
3577        if self.alternates_enabled {
3578            let sources = self.sources()?;
3579            let stream = sources.open_stream(oid)?;
3580            if let Some(stream) = stream {
3581                return f(stream).map(Some);
3582            }
3583        }
3584        if let Some(err) = unreadable_local_loose {
3585            return Err(err);
3586        }
3587        Ok(None)
3588    }
3589
3590    /// Invoke `f` for every object id reachable from this database until `f` returns [`ControlFlow::Break`].
3591    ///
3592    /// # Errors
3593    ///
3594    /// Propagates enumeration failures from any consulted backend.
3595    pub fn for_each_object(&self, f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>) -> Result<()> {
3596        let mut seen = oid_hash_set();
3597        let mut visit = |store: &dyn ObjectStore| -> Result<bool> {
3598            store::for_each_propagate_break(store, &mut |oid| {
3599                if !seen.insert(*oid) {
3600                    return ControlFlow::Continue(());
3601                }
3602                f(oid)
3603            })
3604        };
3605        if let Some(overlay) = self.overlay_store() {
3606            if visit(overlay.as_ref())? {
3607                return Ok(());
3608            }
3609        }
3610        if visit(self.open_primary()?.as_writable())? {
3611            return Ok(());
3612        }
3613        for src in &self.extra_read_sources {
3614            if visit(src.as_ref())? {
3615                return Ok(());
3616            }
3617        }
3618        if self.alternates_enabled {
3619            let _ = visit(self.sources()?.as_ref())?;
3620        }
3621        Ok(())
3622    }
3623
3624    /// Fill `out` with ids whose hex starts with `prefix` (deduplicated across overlay, primary, alternates).
3625    ///
3626    /// # Errors
3627    ///
3628    /// Returns [`crate::error::ObjectError::InvalidId`] when `prefix` is not valid hex.
3629    pub fn lookup_prefix(&self, prefix: &str, limit: usize, out: &mut Vec<ObjectId>) -> Result<()> {
3630        let mut seen: OidHashSet = out.iter().copied().collect();
3631        if let Some(overlay) = self.overlay_store() {
3632            append_lookup_prefix_layer(overlay.as_ref(), prefix, limit, out, &mut seen)?;
3633            if limit != 0 && out.len() >= limit {
3634                return Ok(());
3635            }
3636        }
3637        append_lookup_prefix_layer(
3638            self.open_primary()?.as_writable(),
3639            prefix,
3640            limit,
3641            out,
3642            &mut seen,
3643        )?;
3644        if limit != 0 && out.len() >= limit {
3645            return Ok(());
3646        }
3647        for src in &self.extra_read_sources {
3648            append_lookup_prefix_layer(src.as_ref(), prefix, limit, out, &mut seen)?;
3649            if limit != 0 && out.len() >= limit {
3650                return Ok(());
3651            }
3652        }
3653        if self.alternates_enabled {
3654            append_lookup_prefix_layer(self.sources()?.as_ref(), prefix, limit, out, &mut seen)?;
3655        }
3656        Ok(())
3657    }
3658
3659    /// Enumerate loose objects in this database's primary `objects/` directory as `(oid, path)`.
3660    ///
3661    /// Pack files and alternate object directories are not scanned.
3662    ///
3663    /// # Errors
3664    ///
3665    /// Propagates failures while opening the primary files source or walking loose storage.
3666    pub fn enumerate_local_loose_objects(&self) -> Result<Vec<(ObjectId, PathBuf)>> {
3667        let primary = self.files_primary()?;
3668        let loose = primary.loose_store();
3669        let mut out = Vec::new();
3670        loose.for_each_object(&mut |oid| {
3671            out.push((*oid, loose.object_path(oid)));
3672            ControlFlow::Continue(())
3673        })?;
3674        Ok(out)
3675    }
3676
3677    /// Enumerate loose objects under `objects_dir` as `(oid, path)`.
3678    pub(crate) fn enumerate_loose_objects_at(
3679        &self,
3680        objects_dir: &Path,
3681    ) -> Result<Vec<(ObjectId, PathBuf)>> {
3682        let loose = self.loose_at(objects_dir)?;
3683        let mut out = Vec::new();
3684        loose.for_each_object(&mut |oid| {
3685            out.push((*oid, loose.object_path(oid)));
3686            ControlFlow::Continue(())
3687        })?;
3688        Ok(out)
3689    }
3690
3691    /// Hash raw content of a given kind using this repository's hash algorithm.
3692    ///
3693    /// This does **not** write anything to disk.
3694    ///
3695    /// # Errors
3696    ///
3697    /// Returns [`crate::error::ObjectError::HashCollision`] when sha1dc detects a chosen-prefix collision.
3698    pub fn hash(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
3699        hash_object_data_with(self.hash_algo(), kind, data)
3700    }
3701
3702    /// Hash `size` payload bytes of `kind` read from `reader`, without storing anything.
3703    ///
3704    /// Memory use does not depend on `size`: the payload is read in fixed-size chunks. Exactly
3705    /// `size` bytes are consumed; anything after them is left unread.
3706    ///
3707    /// # Errors
3708    ///
3709    /// - [`crate::error::ObjectError::StreamTruncated`] — `reader` ended before `size` bytes.
3710    /// - [`Error::Io`] — reading failed.
3711    /// - [`crate::error::ObjectError::HashCollision`] — sha1dc detected a chosen-prefix collision.
3712    pub fn hash_stream(
3713        &self,
3714        kind: ObjectKind,
3715        size: u64,
3716        reader: &mut dyn std::io::Read,
3717    ) -> Result<ObjectId> {
3718        #[cfg(test)]
3719        self.hot_path_metrics().record_stream_hash();
3720        stream::hash_stream(self.hash_algo(), kind, size, reader)
3721    }
3722
3723    /// Store `size` payload bytes of `kind` read from `reader` and return the object id.
3724    ///
3725    /// Payloads below 1 MiB (`stream::STREAMED_WRITE_MIN_SIZE`) are read into memory and
3726    /// written like [`Self::write_with`]. From 1 MiB up to (but not including)
3727    /// [`Self::big_file_threshold`] they are hashed and deflated in fixed-size chunks into a
3728    /// loose object. At or above the threshold they go into a new single-object pack (at
3729    /// [`ConfigSet::pack_objects_zlib_level`]), as Git does for big files, so memory use does
3730    /// not depend on `size`. If the object already exists the new pack is discarded and the
3731    /// existing copy is freshened unless `options.silent` is set.
3732    ///
3733    /// A custom primary receives the stream through [`WritableObjectStore::write_stream`];
3734    /// while the in-memory overlay is active the object is buffered into the overlay.
3735    ///
3736    /// Exactly `size` bytes are consumed from `reader`.
3737    ///
3738    /// # Errors
3739    ///
3740    /// - [`crate::error::ObjectError::StreamTruncated`] — `reader` ended before `size` bytes.
3741    /// - [`Error::Io`] / [`crate::error::ObjectError::Zlib`] — reading, compressing, or writing failed.
3742    /// - [`crate::error::ObjectError::HashCollision`] — sha1dc detected a chosen-prefix collision.
3743    /// - Config errors from resolving the threshold or compression level.
3744    pub fn write_stream(
3745        &self,
3746        kind: ObjectKind,
3747        size: u64,
3748        reader: &mut dyn std::io::Read,
3749        options: WriteOptions,
3750    ) -> Result<ObjectId> {
3751        #[cfg(test)]
3752        self.hot_path_metrics().record_stream_write();
3753        if let PrimaryStore::Custom(primary) = &self.primary {
3754            if !self.overlay_active() {
3755                let oid = primary.write_stream(kind, size, reader, options)?;
3756                self.note_commit_object_written(kind);
3757                return Ok(oid);
3758            }
3759        }
3760        if self.overlay_active() || size < stream::STREAMED_WRITE_MIN_SIZE {
3761            let len = usize::try_from(size).map_err(|_| {
3762                Error::Object(ObjectError::Corrupt {
3763                    detail: format!("object size {size} exceeds address space"),
3764                })
3765            })?;
3766            let mut data = Vec::with_capacity(len);
3767            let read =
3768                std::io::Read::read_to_end(&mut std::io::Read::take(reader, size), &mut data)?;
3769            if read != len {
3770                return Err(Error::Object(ObjectError::StreamTruncated {
3771                    expected: size,
3772                    actual: read as u64,
3773                }));
3774            }
3775            return self.write_with(kind, &data, options);
3776        }
3777        if size < self.big_file_threshold()? {
3778            let loose = self.local_loose()?;
3779            let oid = loose.write_payload_stream(kind, size, reader, options)?;
3780            self.note_commit_object_written(kind);
3781            return Ok(oid);
3782        }
3783        let staged = stream::StagedPack::write(
3784            &self.objects_dir.join("pack"),
3785            self.hash_algo(),
3786            kind,
3787            size,
3788            reader,
3789            self.pack_compression()?,
3790        )?;
3791        let oid = staged.oid();
3792        if self.object_exists_for_write_skip(&oid) {
3793            if !options.silent {
3794                let _ = self.freshen_object(&oid);
3795            }
3796            return Ok(oid);
3797        }
3798        staged.install()?;
3799        self.invalidate_packs();
3800        self.note_commit_object_written(kind);
3801        Ok(oid)
3802    }
3803
3804    /// Object id of the empty tree for this store's hash algorithm.
3805    ///
3806    /// Hashes the canonical empty tree payload only; nothing is written to disk.
3807    ///
3808    /// # Errors
3809    ///
3810    /// Returns [`crate::error::ObjectError::HashCollision`] when sha1dc detects a chosen-prefix collision.
3811    pub fn empty_tree_oid(&self) -> Result<ObjectId> {
3812        self.hash(ObjectKind::Tree, b"")
3813    }
3814
3815    /// Whether `oid` is this repository's empty tree (virtually present when not on disk).
3816    #[must_use]
3817    pub fn is_empty_tree(&self, oid: &ObjectId) -> bool {
3818        empty_tree_oid_matches(self.hash_algo(), oid)
3819    }
3820
3821    /// Write an object to the loose store and return its [`ObjectId`].
3822    ///
3823    /// If the object already exists it is not overwritten (Git behaviour).
3824    ///
3825    /// The payload is stored as given, without fsck checks; callers that build tree,
3826    /// commit or tag bytes themselves should go through
3827    /// [`Objects::write`](crate::objects::Objects::write) instead.
3828    ///
3829    /// # Errors
3830    ///
3831    /// - [`Error::Io`] — could not create the directory or write the file.
3832    /// - [`crate::error::ObjectError::Zlib`] — compression failed.
3833    pub fn write(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
3834        self.write_with(kind, data, WriteOptions::default())
3835    }
3836
3837    /// Persist batched writes on a custom primary store.
3838    ///
3839    /// No-op for a files-backed primary. See [`WritableObjectStore::flush`].
3840    ///
3841    /// # Errors
3842    ///
3843    /// Propagates the primary store's flush failure.
3844    pub fn flush(&self) -> Result<()> {
3845        match &self.primary {
3846            PrimaryStore::Custom(primary) => primary.flush(),
3847            PrimaryStore::Files(_) => Ok(()),
3848        }
3849    }
3850
3851    /// Persist staged object writes before publishing refs or the index.
3852    ///
3853    /// On flush failure, rolls back unflushed writes on a custom primary so a later
3854    /// successful flush cannot make them durable.
3855    ///
3856    /// # Errors
3857    ///
3858    /// Propagates the primary store's flush failure after attempting [`Self::rollback`].
3859    pub fn flush_for_publish(&self) -> Result<()> {
3860        match &self.primary {
3861            PrimaryStore::Custom(primary) => primary.flush_for_publish(),
3862            PrimaryStore::Files(_) => Ok(()),
3863        }
3864    }
3865
3866    /// Discard unflushed writes on a custom primary store after a failed bulk ingest.
3867    ///
3868    /// No-op for a files-backed primary. See [`WritableObjectStore::rollback`].
3869    ///
3870    /// # Errors
3871    ///
3872    /// Propagates the primary store's rollback failure.
3873    pub fn rollback(&self) -> Result<()> {
3874        match &self.primary {
3875            PrimaryStore::Custom(primary) => primary.rollback(),
3876            PrimaryStore::Files(_) => Ok(()),
3877        }
3878    }
3879
3880    /// Create all 256 loose-object prefix directories (`objects/xx/`).
3881    ///
3882    /// Bulk `git add`-style staging calls this once before parallel loose writes. A no-op for
3883    /// custom primaries, which receive those writes instead of `objects/`.
3884    ///
3885    /// # Errors
3886    ///
3887    /// Returns [`Error::Io`] if a directory cannot be created.
3888    pub fn ensure_all_loose_prefix_dirs(&self) -> Result<()> {
3889        if self.primary.is_custom() {
3890            return Ok(());
3891        }
3892        self.local_loose()?.ensure_all_loose_prefix_dirs()
3893    }
3894
3895    /// Test-only: filesystem path for a loose object (see `grit-lib/tests/odb_abstraction_guard.rs`).
3896    #[cfg(test)]
3897    #[must_use]
3898    pub fn test_loose_object_path(&self, oid: &ObjectId) -> PathBuf {
3899        self.object_path(oid)
3900    }
3901
3902    /// Test-only: delete a loose object file if present.
3903    #[cfg(test)]
3904    pub fn test_remove_loose_object(&self, oid: &ObjectId) {
3905        let _ = fs::remove_file(self.object_path(oid));
3906    }
3907
3908    /// Count loose object files under this repository's `objects/` directory.
3909    ///
3910    /// # Errors
3911    ///
3912    /// Propagates directory enumeration failures from the loose store walker.
3913    pub fn count_loose_objects(&self) -> Result<usize> {
3914        let mut count = 0usize;
3915        for_each_loose_object_id(&self.objects_dir, self.hash_algo(), &mut |_| {
3916            count += 1;
3917            ControlFlow::Continue(())
3918        })?;
3919        Ok(count)
3920    }
3921
3922    /// Approximate object count for Git-style automatic `core.abbrev` sizing.
3923    ///
3924    /// Sums object counts from cached pack indexes. Loose objects are not counted, as in Git's
3925    /// approximate count, so the automatic abbreviation length matches Git's and never needs a
3926    /// walk of the 256 loose fan-out directories. Use [`Self::count_loose_objects`] when loose
3927    /// objects matter (for example to tell whether the database is empty).
3928    ///
3929    /// # Errors
3930    ///
3931    /// Propagates pack index listing failures.
3932    pub fn approximate_object_count(&self) -> Result<usize> {
3933        self.with_pack_read_context(|| {
3934            let indexes = pack::read_local_pack_indexes_cached(self.objects_dir())?;
3935            Ok(indexes.iter().map(|idx| idx.len()).sum())
3936        })
3937    }
3938
3939    /// Zlib-compress canonical loose store bytes using the repository's loose level.
3940    ///
3941    /// # Errors
3942    ///
3943    /// Returns [`crate::error::ObjectError::Zlib`] when compression fails.
3944    pub fn zlib_compress_loose_store(&self, store_bytes: &[u8]) -> Result<Vec<u8>> {
3945        self.local_loose()?.zlib_compress_store_bytes(store_bytes)
3946    }
3947
3948    /// Write a loose object from precomputed id and zlib-compressed store bytes.
3949    ///
3950    /// The caller must supply bytes that the internal zlib loose reader would expand to
3951    /// valid canonical store form (`"<kind> <len>\\0<payload>"`). Hashing and
3952    /// compression are skipped; use after parallel batch preparation.
3953    ///
3954    /// With a custom primary the bytes are inflated and stored through
3955    /// [`WritableObjectStore::write`] instead, so staging works on any backend.
3956    ///
3957    /// # Errors
3958    ///
3959    /// Same as [`Self::write`]; [`crate::error::ObjectError::Zlib`] or [`crate::error::ObjectError::Corrupt`] when a custom
3960    /// primary receives bytes that do not inflate to a valid object.
3961    pub fn write_loose_zlib_prehashed(
3962        &self,
3963        oid: &ObjectId,
3964        zlib_store: &[u8],
3965        options: WriteOptions,
3966    ) -> Result<ObjectId> {
3967        let slot = match &self.primary {
3968            PrimaryStore::Custom(_) => {
3969                let raw = decompress_zlib_loose_bytes(zlib_store)?;
3970                let obj = parse_object_bytes(&raw)?;
3971                return self.write_with(obj.kind, &obj.data, options);
3972            }
3973            PrimaryStore::Files(slot) => slot,
3974        };
3975        let primary = self.open_files_source(slot)?;
3976        if let Some(existing) = primary.try_finish_duplicate_write(oid, options)? {
3977            return Ok(existing);
3978        }
3979        if options.freshen_existing && self.freshen_packed_or_alternate(oid) {
3980            return Ok(*oid);
3981        }
3982
3983        let already_exists = !(options.trust_new_loose || options.assume_loose_only_existence)
3984            && self.object_exists_for_write_skip(oid);
3985
3986        if self.overlay_active() && !already_exists {
3987            if let Ok(raw) = decompress_zlib_loose_bytes(zlib_store) {
3988                if let Ok(obj) = parse_object_bytes(&raw) {
3989                    if self.overlay_store_object(*oid, obj.kind, &obj.data) {
3990                        return Ok(*oid);
3991                    }
3992                }
3993            }
3994        }
3995
3996        if already_exists {
3997            if !options.silent {
3998                let _ = self.freshen_object(oid);
3999            }
4000            return Ok(*oid);
4001        }
4002
4003        primary.write_zlib_prehashed(oid, zlib_store, options)
4004    }
4005
4006    /// Write blob `data` whose id `oid` the caller already computed.
4007    ///
4008    /// On a files primary the content is deflated straight into the loose object file, so
4009    /// no compressed copy is held in memory; a custom primary gets
4010    /// [`Self::write_with`].
4011    pub(crate) fn write_blob_prehashed(
4012        &self,
4013        oid: &ObjectId,
4014        data: &[u8],
4015        options: WriteOptions,
4016    ) -> Result<ObjectId> {
4017        let slot = match &self.primary {
4018            PrimaryStore::Custom(_) => {
4019                return self.write_with(ObjectKind::Blob, data, options);
4020            }
4021            PrimaryStore::Files(slot) => slot,
4022        };
4023        let primary = self.open_files_source(slot)?;
4024        if let Some(existing) = primary.try_finish_duplicate_write(oid, options)? {
4025            return Ok(existing);
4026        }
4027        if options.freshen_existing && self.freshen_packed_or_alternate(oid) {
4028            return Ok(*oid);
4029        }
4030        let already_exists = !(options.trust_new_loose || options.assume_loose_only_existence)
4031            && self.object_exists_for_write_skip(oid);
4032        if self.overlay_active()
4033            && !already_exists
4034            && self.overlay_store_object(*oid, ObjectKind::Blob, data)
4035        {
4036            return Ok(*oid);
4037        }
4038        if already_exists {
4039            if !options.silent {
4040                let _ = self.freshen_object(oid);
4041            }
4042            return Ok(*oid);
4043        }
4044        primary
4045            .loose_store()
4046            .write_prehashed(oid, ObjectKind::Blob, data, options)
4047    }
4048    /// Like [`Self::write`], with control over freshen behaviour on existing objects.
4049    ///
4050    /// With a custom primary, grit does not probe read sources or alternates before
4051    /// writing: [`WritableObjectStore::write`] is idempotent and duplicate detection
4052    /// belongs in the store. Objects reachable only through a read source are still
4053    /// copied into the primary when written here (same as [`Self::write_local`] on a
4054    /// files primary). [`WriteOptions::trust_new_loose`] and
4055    /// [`WriteOptions::assume_loose_only_existence`] apply only to the files-backed
4056    /// primary path.
4057    pub fn write_with(
4058        &self,
4059        kind: ObjectKind,
4060        data: &[u8],
4061        options: WriteOptions,
4062    ) -> Result<ObjectId> {
4063        let oid = hash_object_data_with(self.hash_algo(), kind, data)?;
4064
4065        let slot = match &self.primary {
4066            PrimaryStore::Custom(primary) => {
4067                if self.overlay_active() && self.overlay_store_object(oid, kind, data) {
4068                    return Ok(oid);
4069                }
4070                let oid = WritableObjectStore::write(primary.as_ref(), kind, data, options)?;
4071                self.note_commit_object_written(kind);
4072                return Ok(oid);
4073            }
4074            PrimaryStore::Files(slot) => slot,
4075        };
4076        let primary = self.open_files_source(slot)?;
4077        if let Some(existing) = primary.try_finish_duplicate_write(&oid, options)? {
4078            return Ok(existing);
4079        }
4080        if options.freshen_existing && self.freshen_packed_or_alternate(&oid) {
4081            return Ok(oid);
4082        }
4083
4084        let already_exists = !(options.trust_new_loose || options.assume_loose_only_existence)
4085            && self.object_exists_for_write_skip(&oid);
4086
4087        // When the in-memory overlay is active, keep the object in memory only (unless it is
4088        // already present on disk, in which case nothing new needs to be written anyway).
4089        if self.overlay_active() && !already_exists && self.overlay_store_object(oid, kind, data) {
4090            return Ok(oid);
4091        }
4092
4093        if already_exists {
4094            if !options.silent {
4095                let _ = self.freshen_object(&oid);
4096            }
4097            return Ok(oid);
4098        }
4099
4100        let oid = WritableObjectStore::write(primary.as_ref(), kind, data, options)?;
4101        self.note_commit_object_written(kind);
4102        Ok(oid)
4103    }
4104
4105    /// Write an object as a loose file in this object directory only.
4106    ///
4107    /// Unlike [`Self::write`], this ignores `info/alternates` and
4108    /// `GIT_ALTERNATE_OBJECT_DIRECTORIES`: if the object exists only in an
4109    /// alternate store, it is still written here. That matches how Git's
4110    /// `unpack-objects` materializes every packed object into the receiving
4111    /// repository even when the same OID is already reachable via alternates
4112    /// (see `t5519-push-alternates`).
4113    ///
4114    /// The well-known empty tree is still written when no loose file exists yet,
4115    /// even though [`Self::exists_local`] treats it as virtually present.
4116    ///
4117    /// # Errors
4118    ///
4119    /// Same as [`Self::write`].
4120    pub fn write_local(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
4121        self.primary
4122            .require_files_primary(FilesOnlyOperation::LooseWrite)?;
4123        let oid = hash_object_data_with(self.hash_algo(), kind, data)?;
4124
4125        if let Some(existing) = self.try_freshen_existing_local(&oid) {
4126            return Ok(existing);
4127        }
4128
4129        let oid = self
4130            .local_loose()?
4131            .write(kind, data, WriteOptions::default())?;
4132        self.note_commit_object_written(kind);
4133        Ok(oid)
4134    }
4135
4136    /// Persist one object to the repository primary (custom store or loose files).
4137    ///
4138    /// Unlike [`Self::write`], never routes through the mem overlay, so callers can
4139    /// flush overlay contents after disabling it.
4140    fn write_into_primary(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
4141        match &self.primary {
4142            PrimaryStore::Custom(primary) => {
4143                let oid = WritableObjectStore::write(
4144                    primary.as_ref(),
4145                    kind,
4146                    data,
4147                    WriteOptions::default(),
4148                )?;
4149                self.note_commit_object_written(kind);
4150                Ok(oid)
4151            }
4152            PrimaryStore::Files(_) => self.write_local(kind, data),
4153        }
4154    }
4155
4156    /// Like [`Self::write_local`], but stores payload bytes supplied chunk-by-chunk (pack unpack).
4157    pub(crate) fn write_local_stream_with(
4158        &self,
4159        kind: ObjectKind,
4160        size: u64,
4161        supply: impl FnMut(&mut dyn FnMut(&[u8]) -> Result<()>) -> Result<()>,
4162    ) -> Result<ObjectId> {
4163        self.primary
4164            .require_files_primary(FilesOnlyOperation::LooseWrite)?;
4165        let loose = self.local_loose()?;
4166        let oid = loose.write_payload_stream_with(
4167            kind,
4168            size,
4169            WriteOptions::default(),
4170            self.pack_compression()?,
4171            supply,
4172        )?;
4173        self.note_commit_object_written(kind);
4174        Ok(oid)
4175    }
4176
4177    /// Write a loose object file when it is missing, even if [`Self::exists`] is true because
4178    /// the object lives only in a pack.
4179    ///
4180    /// Used when materializing a partial-clone layout: objects must be duplicated as loose files
4181    /// before local packs are removed. Unlike [`Self::write_local`], objects present only in a
4182    /// promisor pack are still written because [`Self::exists_local`] treats those as absent.
4183    pub fn write_loose_materialize(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
4184        self.primary
4185            .require_files_primary(FilesOnlyOperation::LooseWrite)?;
4186        let oid = hash_object_data_with(self.hash_algo(), kind, data)?;
4187        if let Ok(primary) = self.files_primary() {
4188            if let Ok(Some(existing)) = primary
4189                .loose_store()
4190                .try_finish_if_loose_present(&oid, WriteOptions::default())
4191            {
4192                return Ok(existing);
4193            }
4194        }
4195
4196        self.local_loose()?
4197            .write(kind, data, WriteOptions::default())
4198    }
4199
4200    /// Write an already-serialized object (header + data) to the loose store.
4201    ///
4202    /// Useful when the caller has the full store bytes (e.g. from stdin with
4203    /// `--literally`).
4204    ///
4205    /// # Errors
4206    ///
4207    /// - [`crate::error::ObjectError::Corrupt`] — the provided bytes don't form a valid header.
4208    /// - [`Error::Io`] / [`crate::error::ObjectError::Zlib`] — storage errors.
4209    pub fn write_raw(&self, store_bytes: &[u8]) -> Result<ObjectId> {
4210        let obj = parse_object_bytes(store_bytes)?;
4211        let oid = hash_object_data_with(self.hash_algo(), obj.kind, &obj.data)?;
4212
4213        if let PrimaryStore::Custom(primary) = &self.primary {
4214            if self.exists(&oid) {
4215                return Ok(oid);
4216            }
4217            if self.overlay_active() && self.overlay_store_object(oid, obj.kind, &obj.data) {
4218                return Ok(oid);
4219            }
4220            return WritableObjectStore::write(
4221                primary.as_ref(),
4222                obj.kind,
4223                &obj.data,
4224                WriteOptions::default(),
4225            );
4226        }
4227
4228        if let Some(existing) = self.try_freshen_existing(&oid) {
4229            return Ok(existing);
4230        }
4231
4232        self.local_loose()?
4233            .write_store_prehashed(&oid, store_bytes, WriteOptions::default())
4234    }
4235
4236    /// Like [`Self::write_raw`] but only consults this object directory, not alternates.
4237    ///
4238    /// See [`Self::write_local`].
4239    ///
4240    /// # Errors
4241    ///
4242    /// Same as [`Self::write_raw`].
4243    pub fn write_raw_local(&self, store_bytes: &[u8]) -> Result<ObjectId> {
4244        self.primary
4245            .require_files_primary(FilesOnlyOperation::LooseWrite)?;
4246        let obj = parse_object_bytes(store_bytes)?;
4247        let oid = hash_object_data_with(self.hash_algo(), obj.kind, &obj.data)?;
4248        if let Some(existing) = self.try_freshen_existing_local(&oid) {
4249            return Ok(existing);
4250        }
4251
4252        self.local_loose()?
4253            .write_store_prehashed(&oid, store_bytes, WriteOptions::default())
4254    }
4255
4256    /// Update `path`'s mtime to "now" (Git `utime(path, NULL)`), returning whether it succeeded.
4257    fn touch_object_mtime(&self, path: &Path) -> Option<std::time::SystemTime> {
4258        #[cfg(test)]
4259        self.hot_path_test_metrics.record_freshen();
4260        crate::fs_readonly::set_file_times_now(path)
4261    }
4262}
4263
4264/// Hash the canonical store bytes of an object (`"<kind> <len>\0<data>"`) with
4265/// the given hash algorithm.
4266fn hash_object_data_with(algo: HashAlgo, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
4267    hash::hash_object(algo, kind, data)
4268}
4269
4270/// Whether `oid` is Git's empty tree for `algo` (including the legacy SHA-1 typo OID).
4271#[must_use]
4272pub(crate) fn empty_tree_oid_matches(algo: HashAlgo, oid: &ObjectId) -> bool {
4273    oid.is_empty_tree_for(algo)
4274}
4275
4276/// Zlib-compress blob `data` in loose-object form (`"blob <len>\\0<payload>"`) without first
4277/// copying it behind the header.
4278pub(crate) fn zlib_compress_blob_loose(
4279    data: &[u8],
4280    compression: flate2::Compression,
4281) -> Result<Vec<u8>> {
4282    use std::io::Write as _;
4283    let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), compression);
4284    let zlib_err = |e: std::io::Error| {
4285        Error::Object(ObjectError::Zlib {
4286            detail: e.to_string(),
4287        })
4288    };
4289    write!(encoder, "{} {}\0", ObjectKind::Blob, data.len()).map_err(zlib_err)?;
4290    encoder.write_all(data).map_err(zlib_err)?;
4291    encoder.finish().map_err(zlib_err)
4292}
4293
4294fn append_lookup_prefix_layer(
4295    store: &dyn ObjectStore,
4296    prefix: &str,
4297    limit: usize,
4298    out: &mut Vec<ObjectId>,
4299    seen: &mut OidHashSet,
4300) -> Result<()> {
4301    let mut scratch = Vec::new();
4302    store.lookup_prefix(prefix, 0, &mut scratch)?;
4303    for oid in scratch {
4304        if seen.insert(oid) {
4305            out.push(oid);
4306            if limit != 0 && out.len() >= limit {
4307                return Ok(());
4308            }
4309        }
4310    }
4311    Ok(())
4312}
4313
4314fn materialize_stream(stream: ObjectStream<'_>) -> Result<ObjectStream<'static>> {
4315    use std::io::{Cursor, Read};
4316    let ObjectStream {
4317        kind,
4318        size,
4319        mut reader,
4320    } = stream;
4321    let mut payload = Vec::new();
4322    reader.read_to_end(&mut payload).map_err(Error::Io)?;
4323    Ok(ObjectStream {
4324        kind,
4325        size,
4326        reader: Box::new(Cursor::new(payload)),
4327    })
4328}
4329
4330/// Parse a colon-separated alternates string, handling double-quoted entries
4331/// with octal escape sequences.
4332fn parse_alternate_env(val: &str) -> Vec<PathBuf> {
4333    let mut result = Vec::new();
4334    let mut chars = val.chars().peekable();
4335    while chars.peek().is_some() {
4336        if chars.peek() == Some(&':') {
4337            chars.next();
4338            continue;
4339        }
4340        if chars.peek() == Some(&'"') {
4341            // Try quoted parsing; if EOF is hit without closing quote,
4342            // fall back to treating the whole segment as a raw path.
4343            chars.next(); // consume the opening '"'
4344            let saved: Vec<char> = chars.clone().collect();
4345            let mut path = String::new();
4346            let mut properly_closed = false;
4347            loop {
4348                match chars.next() {
4349                    None => break,
4350                    Some('"') => {
4351                        properly_closed = true;
4352                        break;
4353                    }
4354                    Some('\\') => match chars.peek() {
4355                        Some(c) if c.is_ascii_digit() => {
4356                            let mut oct = String::new();
4357                            for _ in 0..3 {
4358                                if let Some(&c) = chars.peek() {
4359                                    if c.is_ascii_digit() {
4360                                        oct.push(c);
4361                                        chars.next();
4362                                    } else {
4363                                        break;
4364                                    }
4365                                } else {
4366                                    break;
4367                                }
4368                            }
4369                            if let Ok(byte) = u8::from_str_radix(&oct, 8) {
4370                                path.push(byte as char);
4371                            }
4372                        }
4373                        Some(_) => {
4374                            if let Some(c) = chars.next() {
4375                                match c {
4376                                    'n' => path.push('\n'),
4377                                    't' => path.push('\t'),
4378                                    'r' => path.push('\r'),
4379                                    _ => path.push(c),
4380                                }
4381                            }
4382                        }
4383                        None => {}
4384                    },
4385                    Some(c) => path.push(c),
4386                }
4387            }
4388            if !properly_closed {
4389                // Broken quoting: fall back to treating raw value (with leading ")
4390                // as a literal path.
4391                let raw: String = std::iter::once('"').chain(saved).collect();
4392                // Extract up to ':' or end
4393                let raw_path = raw.split(':').next().unwrap_or(&raw);
4394                if !raw_path.is_empty() {
4395                    result.push(PathBuf::from(raw_path));
4396                }
4397                // Advance past the ':' in the original chars (we consumed the saved copy)
4398                // Since chars is now at EOF, we need to handle remaining items.
4399                // Actually, we consumed chars fully. Let's reconstruct from raw.
4400                let remainder = &raw[raw_path.len()..];
4401                if let Some(rest) = remainder.strip_prefix(':') {
4402                    // Parse remaining entries
4403                    result.extend(parse_alternate_env(rest));
4404                }
4405                return result;
4406            } else if !path.is_empty() {
4407                result.push(PathBuf::from(path));
4408            }
4409        } else {
4410            let mut path = String::new();
4411            while let Some(&c) = chars.peek() {
4412                if c == ':' {
4413                    break;
4414                }
4415                path.push(c);
4416                chars.next();
4417            }
4418            if !path.is_empty() {
4419                result.push(PathBuf::from(path));
4420            }
4421        }
4422    }
4423    result
4424}
4425
4426fn system_time_to_file_time(t: std::time::SystemTime) -> FileTime {
4427    let dur = t
4428        .duration_since(std::time::SystemTime::UNIX_EPOCH)
4429        .unwrap_or_default();
4430    FileTime::from_unix_time(
4431        i64::try_from(dur.as_secs()).unwrap_or(i64::MAX),
4432        dur.subsec_nanos(),
4433    )
4434}
4435
4436fn superseded_pack_indexes(
4437    pack_dir: &Path,
4438    keep_pack: &Path,
4439    retained_packs: &HashSet<PathBuf>,
4440    inventory: &RepackPackInventorySnapshot,
4441) -> Result<Vec<(PathBuf, std::time::SystemTime)>> {
4442    let keep_stem = keep_pack
4443        .file_stem()
4444        .and_then(|s| s.to_str())
4445        .ok_or_else(|| {
4446            Error::Io(std::io::Error::new(
4447                std::io::ErrorKind::InvalidInput,
4448                "bad pack path",
4449            ))
4450        })?;
4451    if !pack_dir.is_dir() {
4452        return Ok(Vec::new());
4453    }
4454    let mut out = Vec::new();
4455    for entry in fs::read_dir(pack_dir).map_err(Error::Io)? {
4456        let entry = entry.map_err(Error::Io)?;
4457        let name = entry.file_name();
4458        let name_str = name.to_string_lossy();
4459        if name_str == keep_stem || name_str.starts_with(&format!("{keep_stem}.")) {
4460            continue;
4461        }
4462        if !name_str.ends_with(".idx") {
4463            continue;
4464        }
4465        let idx_path = entry.path();
4466        let pack_path = idx_path.with_extension("pack");
4467        if !pack_path.is_file() {
4468            continue;
4469        }
4470        if inventory.kept_at_inventory.contains(&pack_path)
4471            || pack_path.with_extension("promisor").is_file()
4472            || retained_packs.contains(&pack_path)
4473            || !inventory.pack_paths.contains(&pack_path)
4474        {
4475            continue;
4476        }
4477        let pack_mtime = fs::metadata(&pack_path)
4478            .and_then(|m| m.modified())
4479            .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
4480        out.push((idx_path, pack_mtime));
4481    }
4482    Ok(out)
4483}
4484
4485fn oids_in_inventory_kept_packs(
4486    pack_dir: &Path,
4487    keep_pack: &Path,
4488    inventory_kept_packs: &HashSet<PathBuf>,
4489) -> Result<OidHashSet> {
4490    let keep_stem = keep_pack.file_stem().and_then(|s| s.to_str()).unwrap_or("");
4491    let mut oids = oid_hash_set();
4492    for pack_path in inventory_kept_packs {
4493        let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str()) else {
4494            continue;
4495        };
4496        if stem == keep_stem {
4497            continue;
4498        }
4499        if pack_path.parent().is_some_and(|p| p != pack_dir) {
4500            continue;
4501        }
4502        let idx_path = pack_path.with_extension("idx");
4503        if idx_path.is_file() {
4504            oids.extend(PackedObjects::object_ids_from_index_path(&idx_path)?);
4505        }
4506    }
4507    Ok(oids)
4508}
4509
4510#[cfg(test)]
4511mod tests {
4512    #![allow(clippy::expect_used, clippy::unwrap_used)]
4513
4514    use super::*;
4515    use tempfile::TempDir;
4516
4517    #[test]
4518    fn round_trip_blob() {
4519        let dir = TempDir::new().unwrap();
4520        let odb = Odb::new(dir.path());
4521        let data = b"hello world";
4522        let oid = odb.write(ObjectKind::Blob, data).unwrap();
4523        let obj = odb.read(&oid).unwrap();
4524        assert_eq!(obj.kind, ObjectKind::Blob);
4525        assert_eq!(obj.data, data);
4526    }
4527
4528    #[test]
4529    fn known_blob_hash() {
4530        // Verified: echo -n "hello" | git hash-object --stdin
4531        //        => b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0
4532        let oid = HashAlgo::Sha1
4533            .hash_object(ObjectKind::Blob, b"hello")
4534            .expect("hash");
4535        assert_eq!(oid.to_hex(), "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0");
4536    }
4537
4538    /// Pack `oids` into one new pack and drop their loose copies.
4539    fn pack_objects(objects: &Path, oids: &[ObjectId]) {
4540        let odb = Odb::new(objects);
4541        let pack = crate::pack_objects::build_pack_from_send_list(
4542            &odb,
4543            oids,
4544            &HashSet::new(),
4545            &crate::pack_objects::PackBuildOptions::default(),
4546            &HashMap::new(),
4547        )
4548        .unwrap();
4549        for oid in oids {
4550            fs::remove_file(oid.loose_path_in(objects)).unwrap();
4551        }
4552        crate::index_pack::install_pack_bytes(
4553            pack,
4554            &odb,
4555            &crate::index_pack::IngestPackOptions::default(),
4556        )
4557        .unwrap();
4558    }
4559
4560    #[test]
4561    fn general_reads_cache_trees_and_tiny_blobs_but_not_larger_blobs() {
4562        let dir = TempDir::new().unwrap();
4563        let odb = Odb::new(dir.path());
4564        let blob = odb
4565            .write(
4566                ObjectKind::Blob,
4567                &vec![b'x'; SESSION_READ_BLOB_CACHE_MAX + 1],
4568            )
4569            .unwrap();
4570        let tiny = odb.write(ObjectKind::Blob, b"tiny\n").unwrap();
4571        let tree = odb
4572            .write(
4573                ObjectKind::Tree,
4574                &crate::objects::serialize_tree(&[crate::objects::TreeEntry {
4575                    mode: 0o100644,
4576                    name: b"f".to_vec(),
4577                    oid: blob,
4578                }]),
4579            )
4580            .unwrap();
4581        assert_eq!(
4582            odb.read(&blob).unwrap().data.len(),
4583            SESSION_READ_BLOB_CACHE_MAX + 1
4584        );
4585        assert!(odb.session_loose_reads.lock().unwrap().is_empty());
4586        let tree_bytes = odb.read(&tree).unwrap().data;
4587        assert_eq!(odb.read(&tiny).unwrap().data, b"tiny\n");
4588        for oid in [blob, tree, tiny] {
4589            let hex = oid.to_hex();
4590            fs::remove_file(dir.path().join(&hex[..2]).join(&hex[2..])).unwrap();
4591        }
4592        assert_eq!(odb.read(&tree).unwrap().data, tree_bytes, "tree reused");
4593        assert_eq!(odb.read(&tiny).unwrap().data, b"tiny\n", "tiny blob reused");
4594        assert!(odb.read(&blob).is_err(), "blob was not retained");
4595    }
4596
4597    #[test]
4598    fn session_read_cache_is_bounded_by_bytes_and_entries() {
4599        let mut cache = SessionLooseReads::default();
4600        let chunk = SESSION_LOOSE_CACHE_MAX_BYTES / 4;
4601        let object = |len: usize| Object {
4602            kind: ObjectKind::Tree,
4603            data: vec![0; len],
4604        };
4605        let oid = |n: u32| {
4606            let mut raw = [0u8; 20];
4607            raw[..4].copy_from_slice(&n.to_be_bytes());
4608            ObjectId::from_bytes(&raw).unwrap()
4609        };
4610        for n in 0..4 {
4611            cache.insert(oid(n), &object(chunk));
4612        }
4613        assert_eq!(cache.bytes, SESSION_LOOSE_CACHE_MAX_BYTES);
4614        cache.insert(oid(4), &object(1));
4615        assert_eq!(cache.bytes, 1, "exceeding the byte budget starts over");
4616        assert!(cache.get(&oid(0)).is_none());
4617        cache.insert(oid(4), &object(10));
4618        assert_eq!(cache.bytes, 10, "replacing an entry drops its old size");
4619        cache.insert(oid(5), &object(SESSION_LOOSE_CACHE_MAX_BYTES + 1));
4620        assert!(
4621            cache.get(&oid(5)).is_none(),
4622            "oversized objects are never kept"
4623        );
4624        assert!(cache.get(&oid(4)).is_some());
4625        for n in 10..(10 + SESSION_LOOSE_CACHE_MAX_ENTRIES as u32 + 2) {
4626            cache.insert(oid(n), &object(1));
4627        }
4628        assert!(cache.objects.len() <= SESSION_LOOSE_CACHE_MAX_ENTRIES + 1);
4629        assert!(cache.bytes <= SESSION_LOOSE_CACHE_MAX_BYTES);
4630    }
4631
4632    fn bounded_read_fixture() -> (TempDir, PathBuf, ObjectId, ObjectId) {
4633        let dir = TempDir::new().unwrap();
4634        let objects = dir.path().to_path_buf();
4635        let odb = Odb::new(&objects);
4636        let small = odb.write(ObjectKind::Blob, b"small blob\n").unwrap();
4637        let big: Vec<u8> = (0..300_000u32).flat_map(|i| i.to_le_bytes()).collect();
4638        let big = odb.write(ObjectKind::Blob, &big).unwrap();
4639        (dir, objects, small, big)
4640    }
4641
4642    fn assert_bounded_reads(odb: &Odb, small: &ObjectId, big: &ObjectId) {
4643        match odb.read_unless_larger(small, 1000, false).unwrap() {
4644            BoundedRead::Object(obj) => assert_eq!(obj.data, b"small blob\n"),
4645            BoundedRead::Larger => panic!("small blob is within the limit"),
4646        }
4647        assert!(matches!(
4648            odb.read_unless_larger(big, 1000, false).unwrap(),
4649            BoundedRead::Larger
4650        ));
4651        match odb.read_unless_larger(big, 1_200_000, false).unwrap() {
4652            BoundedRead::Object(obj) => assert_eq!(obj.data.len(), 1_200_000),
4653            BoundedRead::Larger => panic!("limit equal to the size reads the object"),
4654        }
4655        let missing = ObjectId::from_hex("1234567890123456789012345678901234567890").unwrap();
4656        assert!(matches!(
4657            odb.read_unless_larger(&missing, 1000, false),
4658            Err(Error::Object(ObjectError::NotFound { .. }))
4659        ));
4660    }
4661
4662    #[test]
4663    fn read_unless_larger_sizes_loose_objects_from_their_header() {
4664        let (_dir, objects, small, big) = bounded_read_fixture();
4665        assert_bounded_reads(&Odb::new(&objects), &small, &big);
4666    }
4667
4668    #[test]
4669    fn read_unless_larger_sizes_packed_objects_in_and_out_of_read_context() {
4670        let (_dir, objects, small, big) = bounded_read_fixture();
4671        pack_objects(&objects, &[small, big]);
4672        let odb = Odb::new(&objects);
4673        assert_bounded_reads(&odb, &small, &big);
4674        odb.with_pack_read_context(|| assert_bounded_reads(&odb, &small, &big));
4675    }
4676
4677    #[test]
4678    fn parsed_tree_reads_keep_no_raw_copy_in_the_session_cache() {
4679        let (_dir, objects, small, _big) = bounded_read_fixture();
4680        let odb = Odb::new(&objects);
4681        let entries = [crate::objects::TreeEntry {
4682            mode: 0o100644,
4683            name: b"small".to_vec(),
4684            oid: small,
4685        }];
4686        let tree = odb
4687            .write(ObjectKind::Tree, &crate::objects::serialize_tree(&entries))
4688            .unwrap();
4689        for packed in [false, true] {
4690            if packed {
4691                pack_objects(&objects, &[tree]);
4692            }
4693            let odb = Odb::new(&objects);
4694            assert_eq!(*odb.cached_tree_entries(&tree).unwrap(), entries);
4695            assert!(odb.session_cached_loose_read(&tree).is_none());
4696            assert!(Arc::ptr_eq(
4697                &odb.cached_tree_entries(&tree).unwrap(),
4698                &odb.cached_tree_entries(&tree).unwrap()
4699            ));
4700            assert_eq!(odb.read(&tree).unwrap().kind, ObjectKind::Tree);
4701            assert!(
4702                odb.session_cached_loose_read(&tree).is_some(),
4703                "plain reads still use the session cache (packed: {packed})"
4704            );
4705        }
4706    }
4707
4708    #[test]
4709    fn read_unless_larger_reuses_small_loose_reads_but_never_caches_big_ones() {
4710        let (_dir, objects, small, big) = bounded_read_fixture();
4711        let odb = Odb::new(&objects);
4712        assert_bounded_reads(&odb, &small, &big);
4713        assert!(odb.session_loose_reads.lock().unwrap().is_empty());
4714        assert!(matches!(
4715            odb.read_unless_larger(&small, 1000, true).unwrap(),
4716            BoundedRead::Object(_)
4717        ));
4718        assert!(matches!(
4719            odb.read_unless_larger(&big, 1_200_000, true).unwrap(),
4720            BoundedRead::Object(_)
4721        ));
4722        for oid in [small, big] {
4723            let hex = oid.to_hex();
4724            fs::remove_file(objects.join(&hex[..2]).join(&hex[2..])).unwrap();
4725        }
4726        match odb.read_unless_larger(&small, 1000, true).unwrap() {
4727            BoundedRead::Object(obj) => assert_eq!(obj.data, b"small blob\n"),
4728            BoundedRead::Larger => panic!("small blob is within the limit"),
4729        }
4730        assert!(matches!(
4731            odb.read_unless_larger(&small, 4, true),
4732            Ok(BoundedRead::Larger)
4733        ));
4734        assert!(matches!(
4735            odb.read_unless_larger(&big, 1_200_000, true),
4736            Err(Error::Object(ObjectError::NotFound { .. }))
4737        ));
4738    }
4739
4740    #[test]
4741    fn read_unless_larger_finds_objects_across_several_packs() {
4742        let (_dir, objects, small, big) = bounded_read_fixture();
4743        pack_objects(&objects, &[small]);
4744        pack_objects(&objects, &[big]);
4745        let odb = Odb::new(&objects);
4746        odb.with_pack_read_context(|| assert_bounded_reads(&odb, &small, &big));
4747    }
4748
4749    #[test]
4750    fn parse_object_header_prefix_unknown_kind_is_typed_error() {
4751        let err = crate::odb::store::loose::parse_object_header_prefix(b"not-a-git-kind 0\0")
4752            .unwrap_err();
4753        assert!(matches!(
4754            err,
4755            Error::Object(ObjectError::UnknownType { .. })
4756        ));
4757    }
4758
4759    fn git_dir_with_config(config: &str) -> (TempDir, PathBuf, PathBuf) {
4760        let dir = TempDir::new().unwrap();
4761        let git_dir = dir.path().join(".git");
4762        let objects = git_dir.join("objects");
4763        fs::create_dir_all(&objects).unwrap();
4764        fs::write(git_dir.join("config"), config).unwrap();
4765        (dir, git_dir, objects)
4766    }
4767
4768    /// Zlib FLEVEL flag (upper two bits of the second header byte).
4769    fn zlib_flevel(compressed: &[u8]) -> u8 {
4770        assert!(compressed.len() >= 2);
4771        (compressed[1] >> 6) & 3
4772    }
4773
4774    fn tmp_loose_object_paths(objects: &Path) -> Vec<PathBuf> {
4775        let mut tmp = Vec::new();
4776        let Ok(shards) = fs::read_dir(objects) else {
4777            return tmp;
4778        };
4779        for shard in shards.flatten() {
4780            if !shard.file_type().is_ok_and(|t| t.is_dir()) {
4781                continue;
4782            }
4783            let Ok(files) = fs::read_dir(shard.path()) else {
4784                continue;
4785            };
4786            for file in files.flatten() {
4787                let name = file.file_name();
4788                if name.to_string_lossy().starts_with("tmp_") {
4789                    tmp.push(file.path());
4790                }
4791            }
4792        }
4793        tmp
4794    }
4795
4796    #[test]
4797    fn loose_write_honours_level() {
4798        let payload: Vec<u8> = (0..4096).map(|i| (i % 251) as u8).collect();
4799
4800        let (_dir, git_dir, objects) = git_dir_with_config("");
4801        let odb = Odb::new(&objects).with_config_git_dir(git_dir.clone());
4802        let oid_default = odb.write(ObjectKind::Blob, &payload).unwrap();
4803        let bytes_default = fs::read(odb.object_path(&oid_default)).unwrap();
4804        assert!(zlib_flevel(&bytes_default) <= 1);
4805        assert_eq!(odb.read(&oid_default).unwrap().data, payload);
4806
4807        for level in -1i32..=9 {
4808            let config = format!("[core]\n\tloosecompression = {level}\n");
4809            let (_dir, git_dir, objects) = git_dir_with_config(&config);
4810            let odb = Odb::new(&objects).with_config_git_dir(git_dir);
4811            let byte = u8::try_from(level.rem_euclid(256)).unwrap_or(0);
4812            let bytes: Vec<u8> = vec![byte; 512];
4813            let oid = odb.write(ObjectKind::Blob, &bytes).unwrap();
4814            let on_disk = fs::read(odb.object_path(&oid)).unwrap();
4815            assert!(on_disk.len() >= 2, "level {level}");
4816            assert_eq!(odb.read(&oid).unwrap().data, bytes.as_slice());
4817        }
4818
4819        let config = "[core]\n\tcompression = 9\n";
4820        let (_dir, git_dir, objects) = git_dir_with_config(config);
4821        let odb = Odb::new(&objects).with_config_git_dir(git_dir);
4822        let oid = odb.write(ObjectKind::Blob, &payload).unwrap();
4823        assert_eq!(zlib_flevel(&fs::read(odb.object_path(&oid)).unwrap()), 3);
4824
4825        let config = "[core]\n\tcompression = 0\n\tloosecompression = 1\n";
4826        let (_dir, git_dir, objects) = git_dir_with_config(config);
4827        let odb = Odb::new(&objects).with_config_git_dir(git_dir);
4828        let oid = odb.write(ObjectKind::Blob, &payload).unwrap();
4829        assert_eq!(zlib_flevel(&fs::read(odb.object_path(&oid)).unwrap()), 0);
4830
4831        let config = "[core]\n\tloosecompression = 99\n";
4832        let (_dir, git_dir, objects) = git_dir_with_config(config);
4833        let odb = Odb::new(&objects).with_config_git_dir(git_dir);
4834        assert!(odb.write(ObjectKind::Blob, b"x").is_err());
4835        assert!(tmp_loose_object_paths(&objects).is_empty());
4836    }
4837
4838    fn git_run(dir: &Path, args: &[&str]) -> std::process::Output {
4839        std::process::Command::new("git") // hygiene: git fixture comparison in cfg(test) module
4840            .current_dir(dir)
4841            .args(args)
4842            .env("GIT_CONFIG_GLOBAL", "/dev/null")
4843            .env("GIT_CONFIG_SYSTEM", "/dev/null")
4844            .env("GIT_AUTHOR_NAME", "T")
4845            .env("GIT_AUTHOR_EMAIL", "t@example.com")
4846            .env("GIT_COMMITTER_NAME", "T")
4847            .env("GIT_COMMITTER_EMAIL", "t@example.com")
4848            .output()
4849            .unwrap()
4850    }
4851
4852    fn git_in(dir: &Path, args: &[&str]) {
4853        let out = git_run(dir, args);
4854        assert!(
4855            out.status.success(),
4856            "git {:?}: {}",
4857            args,
4858            String::from_utf8_lossy(&out.stderr)
4859        );
4860    }
4861
4862    fn git_rev_parse_oid(dir: &Path, spec: &str) -> ObjectId {
4863        let out = git_run(dir, &["rev-parse", spec]);
4864        assert!(
4865            out.status.success(),
4866            "git rev-parse {spec}: {}",
4867            String::from_utf8_lossy(&out.stderr)
4868        );
4869        ObjectId::from_hex(std::str::from_utf8(&out.stdout).unwrap().trim()).unwrap()
4870    }
4871
4872    #[test]
4873    fn write_loose_zlib_prehashed_matches_write() {
4874        let dir = TempDir::new().unwrap();
4875        let objects = dir.path().join("objects");
4876        let odb = Odb::new(&objects);
4877        let data = b"parallel prehash path";
4878        let oid_normal = odb.write(ObjectKind::Blob, data).unwrap();
4879
4880        let dir2 = TempDir::new().unwrap();
4881        let objects2 = dir2.path().join("objects");
4882        let odb2 = Odb::new(&objects2);
4883        let oid = hash::hash_object(odb2.hash_algo(), ObjectKind::Blob, data).expect("hash");
4884        assert_eq!(oid, oid_normal);
4885        let zlib =
4886            super::zlib_compress_blob_loose(data, odb2.loose_compression().unwrap()).unwrap();
4887        let oid2 = odb2
4888            .write_loose_zlib_prehashed(
4889                &oid,
4890                &zlib,
4891                WriteOptions {
4892                    assume_loose_only_existence: true,
4893                    ..WriteOptions::default()
4894                },
4895            )
4896            .unwrap();
4897        assert_eq!(oid2, oid_normal);
4898        assert_eq!(
4899            fs::read(odb2.object_path(&oid2)).unwrap(),
4900            fs::read(odb.object_path(&oid_normal)).unwrap()
4901        );
4902    }
4903
4904    #[test]
4905    fn write_blob_prehashed_matches_write_and_skips_existing_objects() {
4906        let dir = TempDir::new().unwrap();
4907        let odb = Odb::new(&dir.path().join("objects"));
4908        let data = vec![7u8; 100_000];
4909        let oid_normal = odb.write(ObjectKind::Blob, &data).unwrap();
4910
4911        let dir2 = TempDir::new().unwrap();
4912        let odb2 = Odb::new(&dir2.path().join("objects"));
4913        let oid = hash::hash_object(odb2.hash_algo(), ObjectKind::Blob, &data).unwrap();
4914        let options = WriteOptions {
4915            assume_loose_only_existence: true,
4916            ..WriteOptions::default()
4917        };
4918        assert_eq!(
4919            odb2.write_blob_prehashed(&oid, &data, options).unwrap(),
4920            oid
4921        );
4922        assert_eq!(oid, oid_normal);
4923        assert!(odb2.object_path(&oid).is_file());
4924        let obj = odb2.read(&oid).unwrap();
4925        assert_eq!(
4926            (obj.kind, obj.data.as_slice()),
4927            (ObjectKind::Blob, data.as_slice())
4928        );
4929
4930        // An existing object is kept as is, even when handed different bytes for its id.
4931        assert_eq!(
4932            odb2.write_blob_prehashed(&oid, b"other", options).unwrap(),
4933            oid
4934        );
4935        assert_eq!(odb2.read(&oid).unwrap().data, data);
4936    }
4937
4938    #[test]
4939    fn write_loose_zlib_prehashed_routes_to_custom_primary() {
4940        use crate::objects::HashAlgo;
4941        use std::sync::Arc;
4942
4943        let dir = TempDir::new().unwrap();
4944        let objects = dir.path().join("objects");
4945        fs::create_dir_all(&objects).unwrap();
4946        let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
4947        let odb = OdbBuilder::new().build(&objects, Some(store.clone()));
4948        let data = b"staged through a custom primary";
4949        let oid = hash::hash_object(HashAlgo::Sha1, ObjectKind::Blob, data).unwrap();
4950        let zlib = super::zlib_compress_blob_loose(data, Compression::fast()).unwrap();
4951
4952        odb.ensure_all_loose_prefix_dirs().unwrap();
4953        let written = odb
4954            .write_loose_zlib_prehashed(&oid, &zlib, WriteOptions::default())
4955            .unwrap();
4956        assert_eq!(written, oid);
4957        assert!(store.contains(&oid).unwrap());
4958        assert_eq!(odb.read(&oid).unwrap().data, data);
4959        assert_eq!(
4960            fs::read_dir(&objects).unwrap().count(),
4961            0,
4962            "no loose shard directories or files beside a custom primary"
4963        );
4964
4965        assert!(odb
4966            .write_loose_zlib_prehashed(&oid, b"not zlib", WriteOptions::default())
4967            .is_err());
4968    }
4969
4970    #[test]
4971    fn custom_primary_write_skips_odb_contains_probes() {
4972        use crate::objects::HashAlgo;
4973        use std::ops::ControlFlow;
4974        use std::sync::atomic::{AtomicUsize, Ordering};
4975        use std::sync::Arc;
4976
4977        #[derive(Debug)]
4978        struct Counting(MemoryStore, AtomicUsize, AtomicUsize);
4979
4980        impl ObjectStore for Counting {
4981            fn hash_algo(&self) -> HashAlgo {
4982                self.0.hash_algo()
4983            }
4984            fn read(&self, oid: &ObjectId) -> Result<Option<Object>> {
4985                self.0.read(oid)
4986            }
4987            fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
4988                self.0.read_info(oid)
4989            }
4990            fn contains(&self, oid: &ObjectId) -> Result<bool> {
4991                self.1.fetch_add(1, Ordering::Relaxed);
4992                self.0.contains(oid)
4993            }
4994            fn contains_many(&self, oids: &[ObjectId]) -> Result<Vec<bool>> {
4995                self.2.fetch_add(1, Ordering::Relaxed);
4996                self.0.contains_many(oids)
4997            }
4998            fn for_each_object(
4999                &self,
5000                f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>,
5001            ) -> Result<()> {
5002                self.0.for_each_object(f)
5003            }
5004        }
5005
5006        impl WritableObjectStore for Counting {
5007            fn write(
5008                &self,
5009                kind: ObjectKind,
5010                data: &[u8],
5011                options: WriteOptions,
5012            ) -> Result<ObjectId> {
5013                self.0.write(kind, data, options)
5014            }
5015            fn freshen(&self, oid: &ObjectId) -> Result<bool> {
5016                self.0.freshen(oid)
5017            }
5018        }
5019
5020        let dir = TempDir::new().unwrap();
5021        let objects = dir.path().join("objects");
5022        fs::create_dir_all(&objects).unwrap();
5023        let primary = Arc::new(Counting(
5024            MemoryStore::new(HashAlgo::Sha1),
5025            AtomicUsize::new(0),
5026            AtomicUsize::new(0),
5027        ));
5028        let read_source = Arc::new(Counting(
5029            MemoryStore::new(HashAlgo::Sha1),
5030            AtomicUsize::new(0),
5031            AtomicUsize::new(0),
5032        ));
5033        read_source
5034            .0
5035            .write(ObjectKind::Blob, b"only upstream", WriteOptions::default())
5036            .unwrap();
5037        let odb = OdbBuilder::new()
5038            .push_read_source(read_source.clone())
5039            .build(&objects, Some(primary.clone()));
5040
5041        odb.write(ObjectKind::Blob, b"new local").unwrap();
5042        assert_eq!(primary.1.load(Ordering::Relaxed), 0);
5043        assert_eq!(read_source.1.load(Ordering::Relaxed), 0);
5044
5045        odb.write(ObjectKind::Blob, b"only upstream").unwrap();
5046        assert_eq!(primary.1.load(Ordering::Relaxed), 0);
5047        assert!(primary
5048            .0
5049            .contains(
5050                &hash::hash_object(HashAlgo::Sha1, ObjectKind::Blob, b"only upstream").unwrap()
5051            )
5052            .unwrap());
5053    }
5054
5055    /// Re-writing an object that already exists as a loose file must not replace it; Git
5056    /// only touches mtime via [`Self::freshen_object`].
5057    #[test]
5058    fn write_existing_loose_does_not_rewrite() {
5059        let dir = TempDir::new().unwrap();
5060        let objects = dir.path().join("objects");
5061        fs::create_dir_all(&objects).unwrap();
5062        let odb = Odb::new(&objects);
5063        let payload = b"already loose";
5064        let oid = odb.write(ObjectKind::Blob, payload).unwrap();
5065        let path = odb.object_path(&oid);
5066        let before_bytes = fs::read(&path).unwrap();
5067        let meta_before = fs::metadata(&path).unwrap();
5068        let before_mtime = filetime::FileTime::from_last_modification_time(&meta_before);
5069        #[cfg(unix)]
5070        let ino_before = {
5071            use std::os::unix::fs::MetadataExt;
5072            meta_before.ino()
5073        };
5074        std::thread::sleep(std::time::Duration::from_millis(20));
5075        let oid2 = odb.write(ObjectKind::Blob, payload).unwrap();
5076        assert_eq!(oid, oid2);
5077        assert_eq!(fs::read(&path).unwrap(), before_bytes);
5078        let meta_after = fs::metadata(&path).unwrap();
5079        let after_mtime = filetime::FileTime::from_last_modification_time(&meta_after);
5080        assert!(
5081            after_mtime >= before_mtime,
5082            "expected freshen to bump or preserve mtime"
5083        );
5084        #[cfg(unix)]
5085        {
5086            use std::os::unix::fs::MetadataExt;
5087            assert_eq!(
5088                meta_after.ino(),
5089                ino_before,
5090                "rewrite must not replace the loose object file"
5091            );
5092        }
5093    }
5094
5095    /// Objects present only in a pack must not be duplicated as loose files on [`Self::write`].
5096    #[cfg_attr(
5097        not(feature = "full-tests"),
5098        ignore = "starts system git or is heavy; run with --features full-tests"
5099    )]
5100    #[test]
5101    fn write_skips_loose_when_object_in_pack_only() {
5102        let dir = TempDir::new().unwrap();
5103        git_in(dir.path(), &["init", "-q"]);
5104        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
5105        git_in(dir.path(), &["config", "user.name", "T"]);
5106        fs::write(dir.path().join("f"), b"pack-only payload").unwrap();
5107        git_in(dir.path(), &["add", "f"]);
5108        git_in(dir.path(), &["commit", "-m", "c"]);
5109        git_in(dir.path(), &["repack", "-ad"]);
5110        let objects = dir.path().join(".git").join("objects");
5111        let odb = Odb::new(&objects);
5112        let oid = odb.write(ObjectKind::Blob, b"pack-only payload").unwrap();
5113        assert!(!odb.object_path(&oid).exists());
5114        assert!(odb.exists(&oid));
5115    }
5116
5117    /// Same as pack-only: alternates satisfy [`Self::exists`] without a local loose copy.
5118    #[cfg_attr(
5119        not(feature = "full-tests"),
5120        ignore = "starts system git or is heavy; run with --features full-tests"
5121    )]
5122    #[test]
5123    fn write_freshens_loose_object_in_alternate() {
5124        use filetime::FileTime;
5125        use std::thread;
5126        use std::time::Duration;
5127
5128        let alt = TempDir::new().unwrap();
5129        git_in(alt.path(), &["init", "-q", "--bare"]);
5130        git_in(alt.path(), &["config", "user.email", "t@example.com"]);
5131        let alt_objects = alt.path().join("objects");
5132        let alt_odb = Odb::new(&alt_objects);
5133        let payload = b"alternate-loose";
5134        let oid = alt_odb.write(ObjectKind::Blob, payload).unwrap();
5135        let alt_loose = alt_odb.object_path(&oid);
5136
5137        let primary = TempDir::new().unwrap();
5138        let primary_objects = primary.path().join("objects");
5139        fs::create_dir_all(primary_objects.join("info")).unwrap();
5140        fs::write(
5141            primary_objects.join("info").join("alternates"),
5142            format!("{}\n", alt_objects.display()),
5143        )
5144        .unwrap();
5145        let odb = Odb::new(&primary_objects);
5146        thread::sleep(Duration::from_millis(50));
5147        let before = FileTime::from_last_modification_time(&fs::metadata(&alt_loose).unwrap());
5148        filetime::set_file_mtime(&alt_loose, before).unwrap();
5149
5150        let oid2 = odb.write(ObjectKind::Blob, payload).unwrap();
5151        assert_eq!(oid, oid2);
5152        assert!(!odb.object_path(&oid).exists());
5153        let after = FileTime::from_last_modification_time(&fs::metadata(&alt_loose).unwrap());
5154        assert!(after > before, "write must freshen alternate loose object");
5155    }
5156
5157    #[cfg_attr(
5158        not(feature = "full-tests"),
5159        ignore = "starts system git or is heavy; run with --features full-tests"
5160    )]
5161    #[test]
5162    fn write_freshens_packed_object_in_alternate() {
5163        use filetime::FileTime;
5164        use std::thread;
5165        use std::time::Duration;
5166
5167        let alt = TempDir::new().unwrap();
5168        git_in(alt.path(), &["init", "-q"]);
5169        git_in(alt.path(), &["config", "user.email", "t@example.com"]);
5170        git_in(alt.path(), &["config", "user.name", "T"]);
5171        let payload = b"alternate-pack";
5172        fs::write(alt.path().join("f"), payload).unwrap();
5173        git_in(alt.path(), &["add", "f"]);
5174        git_in(alt.path(), &["commit", "-m", "c"]);
5175        git_in(alt.path(), &["repack", "-ad"]);
5176        let alt_objects = alt.path().join(".git").join("objects");
5177        let alt_odb = Odb::new(&alt_objects);
5178        let oid = alt_odb.write(ObjectKind::Blob, payload).unwrap();
5179        let pack_path = fs::read_dir(alt_objects.join("pack"))
5180            .unwrap()
5181            .flatten()
5182            .find(|e| e.path().extension().is_some_and(|x| x == "pack"))
5183            .unwrap()
5184            .path();
5185        thread::sleep(Duration::from_millis(50));
5186        let before = FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5187
5188        let primary = TempDir::new().unwrap();
5189        let primary_objects = primary.path().join("objects");
5190        fs::create_dir_all(primary_objects.join("info")).unwrap();
5191        fs::write(
5192            primary_objects.join("info").join("alternates"),
5193            format!("{}\n", alt_objects.display()),
5194        )
5195        .unwrap();
5196        pack::clear_pack_cache();
5197        let odb = Odb::new(&primary_objects);
5198        assert!(odb.exists(&oid));
5199        let oid2 = odb.write(ObjectKind::Blob, payload).unwrap();
5200        assert_eq!(oid, oid2);
5201        assert!(!odb.object_path(&oid).exists());
5202        let after = FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5203        assert!(after >= before, "write must freshen alternate pack");
5204    }
5205
5206    #[cfg_attr(
5207        not(feature = "full-tests"),
5208        ignore = "starts system git or is heavy; run with --features full-tests"
5209    )]
5210    #[test]
5211    fn write_skips_loose_when_object_only_in_alternate() {
5212        let alt = TempDir::new().unwrap();
5213        git_in(alt.path(), &["init", "-q", "--bare"]);
5214        git_in(alt.path(), &["config", "user.email", "t@example.com"]);
5215        let alt_objects = alt.path().join("objects");
5216        let alt_odb = Odb::new(&alt_objects);
5217        let payload = b"alternate-only";
5218        let oid = alt_odb.write(ObjectKind::Blob, payload).unwrap();
5219
5220        let primary = TempDir::new().unwrap();
5221        let primary_objects = primary.path().join("objects");
5222        fs::create_dir_all(primary.path().join("objects").join("info")).unwrap();
5223        fs::write(
5224            primary
5225                .path()
5226                .join("objects")
5227                .join("info")
5228                .join("alternates"),
5229            format!("{}\n", alt_objects.display()),
5230        )
5231        .unwrap();
5232        let odb = Odb::new(&primary_objects);
5233        assert!(odb.exists(&oid));
5234        let oid2 = odb.write(ObjectKind::Blob, payload).unwrap();
5235        assert_eq!(oid, oid2);
5236        assert!(!odb.object_path(&oid).exists());
5237    }
5238
5239    #[cfg_attr(
5240        not(feature = "full-tests"),
5241        ignore = "starts system git or is heavy; run with --features full-tests"
5242    )]
5243    #[test]
5244    fn write_with_mem_overlay_stays_in_memory() {
5245        let dir = TempDir::new().unwrap();
5246        let objects = dir.path().join("objects");
5247        fs::create_dir_all(&objects).unwrap();
5248        let odb = Odb::new(&objects);
5249        odb.enable_mem_overlay();
5250        let payload = b"overlay blob";
5251        let oid = odb.write(ObjectKind::Blob, payload).unwrap();
5252        assert!(!odb.object_path(&oid).exists());
5253        assert_eq!(odb.read(&oid).unwrap().data, payload);
5254        odb.disable_mem_overlay();
5255        assert!(odb.read(&oid).is_err());
5256    }
5257
5258    #[test]
5259    fn persist_mem_overlay_writes_through_custom_primary() {
5260        use crate::objects::HashAlgo;
5261        use std::sync::Arc;
5262
5263        let dir = TempDir::new().unwrap();
5264        let objects = dir.path().join("objects");
5265        fs::create_dir_all(&objects).unwrap();
5266        let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
5267        let odb = OdbBuilder::new().build(&objects, Some(store.clone()));
5268        odb.enable_mem_overlay();
5269        let payload = b"overlay blob";
5270        let oid = odb.write(ObjectKind::Blob, payload).unwrap();
5271        assert!(!store.contains(&oid).unwrap());
5272        odb.persist_mem_overlay().unwrap();
5273        assert!(store.contains(&oid).unwrap());
5274        assert_eq!(odb.read(&oid).unwrap().data, payload);
5275        assert!(!odb.object_path(&oid).exists());
5276    }
5277
5278    #[test]
5279    fn read_alternates_relative_path_and_symlinked_objects_dir() {
5280        use crate::pack::read_alternates_recursive;
5281
5282        let layout = TempDir::new().unwrap();
5283        let alt_objects = layout.path().join("alt-store").join("objects");
5284        fs::create_dir_all(&alt_objects).unwrap();
5285        let primary_objects = layout.path().join("repo").join("objects");
5286        fs::create_dir_all(primary_objects.join("info")).unwrap();
5287        fs::write(
5288            primary_objects.join("info").join("alternates"),
5289            "../../alt-store/objects\n",
5290        )
5291        .unwrap();
5292        let resolved = read_alternates_recursive(&primary_objects).unwrap();
5293        let alt_canonical = alt_objects
5294            .canonicalize_simplified()
5295            .unwrap_or(alt_objects.clone());
5296        assert!(
5297            resolved.iter().any(|p| {
5298                p.canonicalize_simplified().unwrap_or_else(|_| p.clone()) == alt_canonical
5299            }),
5300            "relative alternate entry should resolve: {resolved:?}"
5301        );
5302
5303        #[cfg(unix)]
5304        {
5305            let link_parent = TempDir::new().unwrap();
5306            std::os::unix::fs::symlink(&primary_objects, link_parent.path().join("objects-link"))
5307                .unwrap();
5308            let via_link =
5309                read_alternates_recursive(&link_parent.path().join("objects-link")).unwrap();
5310            assert!(
5311                !via_link.is_empty(),
5312                "alternates through symlinked objects dir: {via_link:?}"
5313            );
5314        }
5315    }
5316    #[test]
5317    fn empty_tree_exists_without_hex() {
5318        let odb = Odb::new(std::path::Path::new("/nonexistent/objects"));
5319        let canon = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904").unwrap();
5320        let legacy = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf899d69f7c6948d4").unwrap();
5321        assert!(odb.exists(&canon));
5322        assert!(odb.exists(&legacy));
5323        assert!(odb.exists_local(&canon));
5324        assert!(!odb.freshen_object(&canon));
5325    }
5326
5327    #[test]
5328    fn sha256_empty_tree_virtual_read_without_loose_file() {
5329        use crate::objects::HashAlgo;
5330        use std::sync::Arc;
5331
5332        let dir = TempDir::new().unwrap();
5333        let objects = dir.path().join("objects");
5334        fs::create_dir_all(&objects).unwrap();
5335        let store = Arc::new(MemoryStore::new(HashAlgo::Sha256));
5336        let odb = OdbBuilder::new().build(&objects, Some(store));
5337        let empty = odb.empty_tree_oid().expect("hash empty tree");
5338        assert!(!odb.exists_materialized_local(&empty));
5339        assert!(odb.exists_local(&empty));
5340        assert!(odb.is_empty_tree(&empty));
5341        let obj = odb.read(&empty).expect("virtual read empty tree");
5342        assert_eq!(obj.kind, ObjectKind::Tree);
5343        assert!(obj.data.is_empty());
5344    }
5345
5346    #[test]
5347    fn empty_tree_oid_and_object_id_empty_tree_match_sha1() {
5348        let odb = Odb::new(std::path::Path::new("/nonexistent/objects"));
5349        let from_odb = odb.empty_tree_oid().expect("empty tree oid");
5350        assert_eq!(from_odb, ObjectId::empty_tree());
5351        assert!(odb.is_empty_tree(&ObjectId::empty_tree()));
5352    }
5353
5354    #[test]
5355    fn empty_tree_virtual_presence_skips_materialized_local() {
5356        let dir = TempDir::new().unwrap();
5357        let objects = dir.path().join("objects");
5358        fs::create_dir_all(&objects).unwrap();
5359        let odb = Odb::new(&objects);
5360        let canon = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904").unwrap();
5361        assert!(odb.exists_local(&canon));
5362        assert!(!odb.exists_materialized_local(&canon));
5363    }
5364
5365    #[test]
5366    fn write_materializes_well_known_empty_tree() {
5367        let dir = TempDir::new().unwrap();
5368        let objects = dir.path().join("objects");
5369        fs::create_dir_all(&objects).unwrap();
5370        let odb = Odb::new(&objects);
5371        let canon = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904").unwrap();
5372        assert!(!odb.exists_materialized_local(&canon));
5373        let oid = odb
5374            .write(crate::objects::ObjectKind::Tree, &[])
5375            .expect("write empty tree");
5376        assert_eq!(oid, canon);
5377        assert!(odb.exists_materialized_local(&canon));
5378    }
5379
5380    #[test]
5381    fn append_alternate_objects_line_errors_on_unreadable_existing_file() {
5382        let dir = TempDir::new().unwrap();
5383        let objects = dir.path().join("objects");
5384        fs::create_dir_all(objects.join("info")).unwrap();
5385        let alt_path = objects.join("info/alternates");
5386        fs::write(&alt_path, b"not valid utf-8 \xff\n").unwrap();
5387        let err = Odb::append_alternate_objects_line(&objects, Path::new("/tmp/other/objects"))
5388            .unwrap_err();
5389        assert!(matches!(err, Error::Io(_)));
5390        assert_eq!(fs::read(&alt_path).unwrap(), b"not valid utf-8 \xff\n");
5391    }
5392
5393    #[test]
5394    fn append_file_alternate_refreshes_cached_snapshot() {
5395        let primary = TempDir::new().unwrap();
5396        let alternate = TempDir::new().unwrap();
5397        let alt_objects = alternate.path().join("objects");
5398        std::fs::create_dir_all(&alt_objects).unwrap();
5399        let alt_odb = Odb::new(&alt_objects);
5400        let oid = alt_odb.write(ObjectKind::Blob, b"via-alternate").unwrap();
5401
5402        let primary_objects = primary.path().join("objects");
5403        std::fs::create_dir_all(primary_objects.join("info")).unwrap();
5404        let primary_odb = Odb::new(&primary_objects);
5405        assert!(!primary_odb.exists(&oid));
5406        let _ = primary_odb.file_alternate_dirs_snapshot();
5407        primary_odb.append_file_alternate(&alt_objects).unwrap();
5408        assert!(primary_odb.exists(&oid));
5409    }
5410
5411    #[test]
5412    fn exists_via_env_alternate_dirs_at_construction() {
5413        let primary = TempDir::new().unwrap();
5414        let alternate = TempDir::new().unwrap();
5415        let alt_objects = alternate.path().join("objects");
5416        std::fs::create_dir_all(&alt_objects).unwrap();
5417        let alt_odb = Odb::new(&alt_objects);
5418        let oid = alt_odb.write(ObjectKind::Blob, b"env-alt").unwrap();
5419
5420        let primary_objects = primary.path().join("objects");
5421        std::fs::create_dir_all(&primary_objects).unwrap();
5422        let primary_odb = Odb::new(&primary_objects).with_env_alternate_dirs(vec![alt_objects]);
5423        assert!(primary_odb.exists(&oid));
5424    }
5425
5426    fn flaky_odb(objects: &Path) -> (Odb, Arc<store::flaky::FlakyStore>) {
5427        let flaky = store::flaky::FlakyStore::new();
5428        let odb = OdbBuilder::new().build(objects, Some(flaky.clone()));
5429        (odb, flaky)
5430    }
5431
5432    #[test]
5433    fn contains_reports_primary_failure_instead_of_missing() {
5434        let dir = TempDir::new().unwrap();
5435        let (odb, flaky) = flaky_odb(dir.path());
5436        let oid = odb.write(ObjectKind::Blob, b"stored").unwrap();
5437        assert!(odb.contains(&oid).unwrap());
5438
5439        flaky.fail_all(true);
5440        assert!(store::flaky::is_injected(&odb.read(&oid).unwrap_err()));
5441        assert!(store::flaky::is_injected(&odb.contains(&oid).unwrap_err()));
5442        assert!(
5443            !odb.exists(&oid),
5444            "exists() keeps treating failures as absent"
5445        );
5446        assert!(odb.contains(&odb.empty_tree_oid().unwrap()).unwrap());
5447
5448        let try_local = odb.try_exists_local(&oid).unwrap_err();
5449        assert!(store::flaky::is_injected(&try_local));
5450        assert!(!odb.exists_local(&oid));
5451        let try_stored = odb.try_exists_stored(&oid).unwrap_err();
5452        assert!(store::flaky::is_injected(&try_stored));
5453        assert!(!odb.exists_stored(&oid));
5454    }
5455
5456    #[test]
5457    fn contains_reports_extra_read_source_failure() {
5458        let dir = TempDir::new().unwrap();
5459        let flaky = store::flaky::FlakyStore::new();
5460        let odb = OdbBuilder::new()
5461            .push_read_source(flaky.clone())
5462            .alternates(false)
5463            .build(dir.path(), None);
5464        let local = odb.write(ObjectKind::Blob, b"in primary").unwrap();
5465        let absent = HashAlgo::Sha1
5466            .hash_object(ObjectKind::Blob, b"nowhere")
5467            .unwrap();
5468        assert!(!odb.contains(&absent).unwrap());
5469
5470        flaky.fail_contains(true);
5471        assert!(
5472            odb.contains(&local).unwrap(),
5473            "primary hit wins over a failing source"
5474        );
5475        assert!(store::flaky::is_injected(
5476            &odb.contains(&absent).unwrap_err()
5477        ));
5478        assert!(!odb.exists(&absent));
5479    }
5480
5481    #[test]
5482    fn contains_reports_primary_failure_even_when_later_source_has_object() {
5483        let dir = TempDir::new().unwrap();
5484        let extra = Arc::new(store::MemoryStore::new(HashAlgo::Sha1));
5485        let flaky = store::flaky::FlakyStore::new();
5486        let odb = OdbBuilder::new()
5487            .push_read_source(extra.clone())
5488            .build(dir.path(), Some(flaky.clone()));
5489        let oid = extra
5490            .write(ObjectKind::Blob, b"extra", WriteOptions::default())
5491            .unwrap();
5492        assert!(odb.contains(&oid).unwrap());
5493
5494        flaky.fail_all(true);
5495        assert!(store::flaky::is_injected(&odb.read(&oid).unwrap_err()));
5496        assert!(
5497            store::flaky::is_injected(&odb.contains(&oid).unwrap_err()),
5498            "contains must agree with read"
5499        );
5500        assert!(odb.exists(&oid), "exists() skips the failing primary");
5501    }
5502
5503    #[test]
5504    fn contains_reports_alternate_failure() {
5505        let primary = TempDir::new().unwrap();
5506        let alternate = TempDir::new().unwrap();
5507        let alt_objects = alternate.path().join("objects");
5508        std::fs::create_dir_all(&alt_objects).unwrap();
5509        let primary_objects = primary.path().join("objects");
5510        std::fs::create_dir_all(&primary_objects).unwrap();
5511        let odb = Odb::new(&primary_objects).with_env_alternate_dirs(vec![alt_objects]);
5512        let local = odb.write(ObjectKind::Blob, b"local").unwrap();
5513        let absent = HashAlgo::Sha1
5514            .hash_object(ObjectKind::Blob, b"nowhere")
5515            .unwrap();
5516
5517        // Files alternates skip unreadable packs, so stand a failing store in for the
5518        // composite the alternate directories resolve to.
5519        let flaky = store::flaky::FlakyStore::new();
5520        odb.sources().unwrap();
5521        odb.alternate_sources_cache.write().unwrap().sources = Some(Arc::new(CompositeStore::new(
5522            vec![flaky.clone()],
5523            HashAlgo::Sha1,
5524        )));
5525        assert!(!odb.contains(&absent).unwrap());
5526
5527        flaky.fail_contains(true);
5528        assert!(odb.contains(&local).unwrap());
5529        assert!(store::flaky::is_injected(
5530            &odb.contains(&absent).unwrap_err()
5531        ));
5532        assert!(!odb.exists(&absent));
5533    }
5534
5535    #[test]
5536    fn contains_on_files_backend_covers_present_absent_empty_tree_and_alternate() {
5537        let primary = TempDir::new().unwrap();
5538        let alternate = TempDir::new().unwrap();
5539        let alt_objects = alternate.path().join("objects");
5540        std::fs::create_dir_all(&alt_objects).unwrap();
5541        let alt_oid = Odb::new(&alt_objects)
5542            .write(ObjectKind::Blob, b"alternate")
5543            .unwrap();
5544        let primary_objects = primary.path().join("objects");
5545        std::fs::create_dir_all(&primary_objects).unwrap();
5546        let odb = Odb::new(&primary_objects).with_env_alternate_dirs(vec![alt_objects]);
5547        let present = odb.write(ObjectKind::Blob, b"present").unwrap();
5548        let absent = HashAlgo::Sha1
5549            .hash_object(ObjectKind::Blob, b"absent")
5550            .unwrap();
5551
5552        assert!(odb.contains(&present).unwrap());
5553        assert!(odb.contains(&odb.empty_tree_oid().unwrap()).unwrap());
5554        assert!(odb.contains(&alt_oid).unwrap());
5555        assert!(!odb.contains(&absent).unwrap());
5556        let empty_tree = odb.empty_tree_oid().unwrap();
5557        assert_eq!(
5558            odb.contains_many(&[present, absent, alt_oid, empty_tree])
5559                .unwrap(),
5560            vec![true, false, true, true]
5561        );
5562        assert!(odb.contains_many(&[]).unwrap().is_empty());
5563        assert_eq!(
5564            odb.present_oids([present, absent, alt_oid]).unwrap(),
5565            vec![present, alt_oid]
5566        );
5567        assert_eq!(
5568            odb.missing_oids([present, absent, alt_oid]).unwrap(),
5569            vec![absent]
5570        );
5571        assert_eq!(
5572            odb.missing_stored_oids([present, absent, alt_oid]).unwrap(),
5573            vec![absent, alt_oid],
5574            "stored ignores alternates"
5575        );
5576    }
5577
5578    #[test]
5579    fn missing_stored_oids_sees_packs_written_since_the_last_probe() {
5580        let dir = TempDir::new().unwrap();
5581        let odb = Odb::new(dir.path());
5582        let other = TempDir::new().unwrap();
5583        let source = Odb::new(other.path());
5584        let blobs: Vec<ObjectId> = (0..3)
5585            .map(|i| {
5586                source
5587                    .write(ObjectKind::Blob, format!("b{i}").as_bytes())
5588                    .unwrap()
5589            })
5590            .collect();
5591        assert_eq!(odb.missing_stored_oids(blobs.clone()).unwrap(), blobs);
5592        // Another writer adds a pack with two of them.
5593        let pack = crate::pack_objects::build_pack_from_send_list(
5594            &source,
5595            &blobs[..2],
5596            &std::collections::HashSet::new(),
5597            &crate::pack_objects::PackBuildOptions::default(),
5598            &std::collections::HashMap::new(),
5599        )
5600        .unwrap();
5601        crate::index_pack::install_pack_bytes(pack, &Odb::new(dir.path()), &Default::default())
5602            .unwrap();
5603        assert_eq!(
5604            odb.missing_stored_oids(blobs.clone()).unwrap(),
5605            vec![blobs[2]]
5606        );
5607    }
5608
5609    #[test]
5610    fn oid_filters_propagate_backend_failure() {
5611        let dir = TempDir::new().unwrap();
5612        let (odb, flaky) = flaky_odb(dir.path());
5613        let oid = odb.write(ObjectKind::Blob, b"x").unwrap();
5614        assert_eq!(odb.contains_many(&[oid]).unwrap(), vec![true]);
5615        flaky.fail_contains(true);
5616        assert!(store::flaky::is_injected(
5617            &odb.contains_many(&[oid]).unwrap_err()
5618        ));
5619        assert!(store::flaky::is_injected(
5620            &odb.present_oids([oid]).unwrap_err()
5621        ));
5622        assert!(store::flaky::is_injected(
5623            &odb.missing_oids([oid]).unwrap_err()
5624        ));
5625        assert!(store::flaky::is_injected(
5626            &odb.missing_stored_oids([oid]).unwrap_err()
5627        ));
5628    }
5629
5630    #[test]
5631    fn write_existing_loose_uses_path_stat_not_exists() {
5632        let dir = TempDir::new().unwrap();
5633        let odb = Odb::new(dir.path());
5634        let oid = odb.write(ObjectKind::Blob, b"once").unwrap();
5635        let path = odb.object_path(&oid);
5636        assert!(path.is_file());
5637        odb.reset_exists_probe();
5638        let oid2 = odb.write(ObjectKind::Blob, b"once").unwrap();
5639        assert_eq!(oid, oid2);
5640        assert_eq!(
5641            odb.exists_probe_count(),
5642            0,
5643            "loose fast path must not call exists()"
5644        );
5645    }
5646
5647    #[cfg_attr(
5648        not(feature = "full-tests"),
5649        ignore = "starts system git or is heavy; run with --features full-tests"
5650    )]
5651    #[test]
5652    fn exists_and_write_after_invalidate_packs_use_odb_store() {
5653        let dir = TempDir::new().unwrap();
5654        git_in(dir.path(), &["init", "-q"]);
5655        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
5656        git_in(dir.path(), &["config", "user.name", "T"]);
5657        let payload = b"invalidate-pack-exists";
5658        fs::write(dir.path().join("f"), payload).unwrap();
5659        git_in(dir.path(), &["add", "f"]);
5660        git_in(dir.path(), &["commit", "-m", "c"]);
5661        git_in(dir.path(), &["repack", "-ad"]);
5662        let objects = dir.path().join(".git").join("objects");
5663        let odb = Odb::new(&objects);
5664        let oid = odb.hash(ObjectKind::Blob, payload).expect("hash");
5665        assert!(odb.exists(&oid), "blob must live in pack after repack");
5666        let pack_dir = objects.join("pack");
5667        for entry in fs::read_dir(&pack_dir).unwrap().flatten() {
5668            let path = entry.path();
5669            if path.extension().is_some_and(|e| e == "pack" || e == "idx") {
5670                fs::remove_file(path).unwrap();
5671            }
5672        }
5673        odb.invalidate_packs();
5674        assert!(
5675            !odb.exists(&oid),
5676            "exists must not read stale legacy pack listing after invalidate_packs"
5677        );
5678        let oid2 = odb.write(ObjectKind::Blob, payload).unwrap();
5679        assert_eq!(oid, oid2);
5680        assert!(
5681            odb.object_path(&oid).is_file(),
5682            "write must materialize loose object when pack copy is gone"
5683        );
5684        odb.read(&oid).expect("read after write");
5685    }
5686
5687    #[cfg_attr(
5688        not(feature = "full-tests"),
5689        ignore = "starts system git or is heavy; run with --features full-tests"
5690    )]
5691    #[test]
5692    fn write_uses_single_exists_probe_when_not_loose() {
5693        let dir = TempDir::new().unwrap();
5694        git_in(dir.path(), &["init", "-q"]);
5695        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
5696        git_in(dir.path(), &["config", "user.name", "T"]);
5697        fs::write(dir.path().join("f"), b"probe-once").unwrap();
5698        git_in(dir.path(), &["add", "f"]);
5699        git_in(dir.path(), &["commit", "-m", "c"]);
5700        git_in(dir.path(), &["repack", "-ad"]);
5701        let objects = dir.path().join(".git").join("objects");
5702        let odb = Odb::new(&objects);
5703        let oid = odb.write(ObjectKind::Blob, b"probe-once").unwrap();
5704        assert!(!odb.object_path(&oid).exists());
5705        odb.reset_exists_probe();
5706        let oid2 = odb.write(ObjectKind::Blob, b"probe-once").unwrap();
5707        assert_eq!(oid, oid2);
5708        assert_eq!(
5709            odb.exists_probe_count(),
5710            1,
5711            "pack/alternate write path must call exists() exactly once"
5712        );
5713    }
5714    #[test]
5715    fn write_existing_object_freshens() {
5716        use filetime::FileTime;
5717        use std::fs;
5718        use std::thread;
5719        use std::time::Duration;
5720
5721        let dir = TempDir::new().unwrap();
5722        let odb = Odb::new(dir.path());
5723        let oid = odb.write(ObjectKind::Blob, b"hello").unwrap();
5724        let path = odb.object_path(&oid);
5725        thread::sleep(Duration::from_millis(50));
5726        let before = FileTime::from_last_modification_time(&fs::metadata(&path).unwrap());
5727        filetime::set_file_mtime(&path, before).unwrap();
5728
5729        let _ = odb.write(ObjectKind::Blob, b"hello").unwrap();
5730        let after = FileTime::from_last_modification_time(&fs::metadata(&path).unwrap());
5731        assert!(
5732            after > before,
5733            "rewriting an existing loose object must freshen its mtime"
5734        );
5735    }
5736
5737    #[test]
5738    fn freshen_pack_once_per_odb() {
5739        use filetime::FileTime;
5740        use flate2::write::ZlibEncoder;
5741        use flate2::Compression;
5742        use std::fs;
5743        use std::io::Write;
5744        use std::thread;
5745        use std::time::Duration;
5746
5747        fn append_pack_object(buf: &mut Vec<u8>, type_code: u8, data: &[u8]) {
5748            let mut size = data.len();
5749            let first = ((type_code & 0x7) << 4) | (size & 0x0f) as u8;
5750            size >>= 4;
5751            if size > 0 {
5752                buf.push(first | 0x80);
5753                while size > 0 {
5754                    let b = (size & 0x7f) as u8;
5755                    size >>= 7;
5756                    buf.push(if size > 0 { b | 0x80 } else { b });
5757                }
5758            } else {
5759                buf.push(first);
5760            }
5761            let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
5762            enc.write_all(data).unwrap();
5763            buf.extend_from_slice(&enc.finish().unwrap());
5764        }
5765
5766        fn write_v2_idx(
5767            idx_path: &Path,
5768            pack_path: &Path,
5769            entries: &[(ObjectId, u64)],
5770        ) -> Result<()> {
5771            let mut sorted = entries.to_vec();
5772            sorted.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
5773            let n = sorted.len();
5774            let mut fanout = [0u32; 256];
5775            for byte in 0u32..256 {
5776                let count = sorted
5777                    .iter()
5778                    .filter(|(oid, _)| u32::from(oid.as_bytes()[0]) <= byte)
5779                    .count();
5780                fanout[byte as usize] = u32::try_from(count).unwrap_or(u32::MAX);
5781            }
5782            let mut buf = Vec::new();
5783            buf.extend_from_slice(b"\xfftOc");
5784            buf.extend_from_slice(&2u32.to_be_bytes());
5785            for f in fanout {
5786                buf.extend_from_slice(&f.to_be_bytes());
5787            }
5788            for (oid, _) in &sorted {
5789                buf.extend_from_slice(oid.as_bytes());
5790            }
5791            for _ in 0..n {
5792                buf.extend_from_slice(&0u32.to_be_bytes());
5793            }
5794            for (_, off) in &sorted {
5795                buf.extend_from_slice(&u32::try_from(*off).unwrap_or(0x8000_0000).to_be_bytes());
5796            }
5797            let pack_bytes = fs::read(pack_path)?;
5798            buf.extend_from_slice(&pack_bytes[pack_bytes.len() - 20..]);
5799            buf.extend_from_slice(&HashAlgo::Sha1.checksum_digest(&buf));
5800            fs::write(idx_path, buf)?;
5801            Ok(())
5802        }
5803
5804        let dir = TempDir::new().unwrap();
5805        let objects_dir = dir.path();
5806        let odb = Odb::new(objects_dir);
5807
5808        let oid_a = odb.write(ObjectKind::Blob, b"alpha").unwrap();
5809        let oid_b = odb.write(ObjectKind::Blob, b"beta").unwrap();
5810        fs::remove_file(odb.object_path(&oid_a)).unwrap();
5811        fs::remove_file(odb.object_path(&oid_b)).unwrap();
5812
5813        let mut pack = Vec::new();
5814        pack.extend_from_slice(b"PACK");
5815        pack.extend_from_slice(&2u32.to_be_bytes());
5816        pack.extend_from_slice(&2u32.to_be_bytes());
5817        let off_a = pack.len() as u64;
5818        append_pack_object(&mut pack, 3, b"alpha");
5819        let off_b = pack.len() as u64;
5820        append_pack_object(&mut pack, 3, b"beta");
5821        pack.extend_from_slice(&HashAlgo::Sha1.checksum_digest(&pack));
5822
5823        let pack_dir = objects_dir.join("pack");
5824        fs::create_dir_all(&pack_dir).unwrap();
5825        let pack_path = pack_dir.join("test-177.pack");
5826        let idx_path = pack_dir.join("test-177.idx");
5827        fs::write(&pack_path, &pack).unwrap();
5828        write_v2_idx(&idx_path, &pack_path, &[(oid_a, off_a), (oid_b, off_b)]).unwrap();
5829        odb.invalidate_packs();
5830
5831        thread::sleep(Duration::from_millis(50));
5832        let before = FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5833
5834        assert!(odb.freshen_object(&oid_a));
5835        let after_first = FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5836        assert!(after_first > before);
5837
5838        assert!(odb.freshen_object(&oid_b));
5839        let after_second =
5840            FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5841        assert_eq!(
5842            after_second, after_first,
5843            "second freshen of another object in the same pack must not touch the pack again"
5844        );
5845    }
5846
5847    #[test]
5848    fn write_existing_packed_object_freshens_pack() {
5849        use filetime::FileTime;
5850        use flate2::write::ZlibEncoder;
5851        use flate2::Compression;
5852        use std::fs;
5853        use std::io::Write;
5854        use std::thread;
5855        use std::time::Duration;
5856
5857        let dir = TempDir::new().unwrap();
5858        let objects_dir = dir.path();
5859        let odb = Odb::new(objects_dir);
5860        let oid = odb.write(ObjectKind::Blob, b"packed-only").unwrap();
5861        fs::remove_file(odb.object_path(&oid)).unwrap();
5862
5863        let mut pack = Vec::new();
5864        pack.extend_from_slice(b"PACK");
5865        pack.extend_from_slice(&2u32.to_be_bytes());
5866        pack.extend_from_slice(&1u32.to_be_bytes());
5867        let off = pack.len() as u64;
5868        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
5869        enc.write_all(b"packed-only").unwrap();
5870        let compressed = enc.finish().unwrap();
5871        pack.push(0x30 | 0x03); // blob len 11
5872        pack.extend_from_slice(&compressed);
5873        pack.extend_from_slice(&HashAlgo::Sha1.checksum_digest(&pack));
5874
5875        let pack_dir = objects_dir.join("pack");
5876        fs::create_dir_all(&pack_dir).unwrap();
5877        let pack_path = pack_dir.join("single-177.pack");
5878        fs::write(&pack_path, &pack).unwrap();
5879        // Minimal idx: reuse logic from freshen_pack_once_per_odb via inline write
5880        let idx_path = pack_dir.join("single-177.idx");
5881        let mut sorted = [(oid, off)];
5882        sorted.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
5883        let mut fanout = [0u32; 256];
5884        for byte in 0u32..256 {
5885            fanout[byte as usize] = if u32::from(oid.as_bytes()[0]) <= byte {
5886                1
5887            } else {
5888                0
5889            };
5890        }
5891        let mut buf = Vec::new();
5892        buf.extend_from_slice(b"\xfftOc");
5893        buf.extend_from_slice(&2u32.to_be_bytes());
5894        for f in fanout {
5895            buf.extend_from_slice(&f.to_be_bytes());
5896        }
5897        buf.extend_from_slice(oid.as_bytes());
5898        buf.extend_from_slice(&0u32.to_be_bytes());
5899        buf.extend_from_slice(&(off as u32).to_be_bytes());
5900        buf.extend_from_slice(&pack[pack.len() - 20..]);
5901        buf.extend_from_slice(&HashAlgo::Sha1.checksum_digest(&buf));
5902        fs::write(&idx_path, buf).unwrap();
5903        odb.invalidate_packs();
5904
5905        thread::sleep(Duration::from_millis(50));
5906        let before = FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5907
5908        odb.write(ObjectKind::Blob, b"packed-only").unwrap();
5909
5910        let after = FileTime::from_last_modification_time(&fs::metadata(&pack_path).unwrap());
5911        assert!(
5912            after > before,
5913            "write of an existing packed object must freshen the pack mtime"
5914        );
5915    }
5916
5917    /// When a local pack is indexed but its `.pack` path cannot be utime'd, [`Odb::write`]
5918    /// materializes a loose copy (Git `write_object_file` fallback). Replacing the pack file
5919    /// with a directory simulates a failed freshen without requiring a root-owned pack.
5920    #[cfg_attr(
5921        not(feature = "full-tests"),
5922        ignore = "starts system git or is heavy; run with --features full-tests"
5923    )]
5924    #[test]
5925    fn write_materializes_loose_when_pack_freshen_fails() {
5926        let dir = TempDir::new().unwrap();
5927        git_in(dir.path(), &["init", "-q"]);
5928        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
5929        git_in(dir.path(), &["config", "user.name", "T"]);
5930        let payload = b"packed-fallback";
5931        fs::write(dir.path().join("f"), payload).unwrap();
5932        git_in(dir.path(), &["add", "f"]);
5933        git_in(dir.path(), &["commit", "-m", "c"]);
5934        git_in(dir.path(), &["repack", "-ad"]);
5935        let objects = dir.path().join(".git").join("objects");
5936        let odb = Odb::new(&objects);
5937        let oid = odb.write(ObjectKind::Blob, payload).unwrap();
5938        assert!(!odb.object_path(&oid).exists());
5939        assert!(odb.exists(&oid));
5940
5941        let pack_path = fs::read_dir(objects.join("pack"))
5942            .unwrap()
5943            .flatten()
5944            .find(|e| e.path().extension().is_some_and(|x| x == "pack"))
5945            .unwrap()
5946            .path();
5947        fs::remove_file(&pack_path).unwrap();
5948        fs::create_dir(&pack_path).unwrap();
5949        odb.invalidate_packs();
5950        assert!(!odb.freshen_object(&oid));
5951
5952        odb.write(ObjectKind::Blob, payload).unwrap();
5953        assert!(odb.object_path(&oid).exists());
5954    }
5955    #[test]
5956    fn write_with_options_silent_skips_freshen_on_existing_loose_object() {
5957        let dir = TempDir::new().unwrap();
5958        let odb = Odb::new(dir.path());
5959        let oid = odb.write(ObjectKind::Blob, b"stable").unwrap();
5960        let path = odb.object_path(&oid);
5961        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
5962        std::thread::sleep(std::time::Duration::from_millis(20));
5963        let again = odb
5964            .write_with(
5965                ObjectKind::Blob,
5966                b"stable",
5967                WriteOptions {
5968                    silent: true,
5969                    ..WriteOptions::default()
5970                },
5971            )
5972            .unwrap();
5973        assert_eq!(oid, again);
5974        let after = std::fs::metadata(&path).unwrap().modified().unwrap();
5975        assert_eq!(before, after);
5976
5977        let touched = odb
5978            .write_with(
5979                ObjectKind::Blob,
5980                b"stable",
5981                WriteOptions {
5982                    silent: false,
5983                    ..WriteOptions::default()
5984                },
5985            )
5986            .unwrap();
5987        assert_eq!(oid, touched);
5988        let freshened = std::fs::metadata(&path).unwrap().modified().unwrap();
5989        assert!(freshened >= before);
5990    }
5991
5992    #[cfg_attr(
5993        not(feature = "full-tests"),
5994        ignore = "starts system git or is heavy; run with --features full-tests"
5995    )]
5996    #[test]
5997    fn promisor_marker_checked_once_per_prepare() {
5998        use crate::pack::{
5999            clear_pack_cache, pack_cache_test_guard, test_pack_marker_stat_count,
6000            test_reset_pack_marker_stat_count,
6001        };
6002
6003        let _guard = pack_cache_test_guard();
6004        let dir = TempDir::new().unwrap();
6005        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6006        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6007        git_in(dir.path(), &["config", "user.name", "T"]);
6008        for i in 0..64 {
6009            fs::write(dir.path().join(format!("f{i}.txt")), format!("body {i}")).unwrap();
6010            git_in(dir.path(), &["add", "."]);
6011            git_in(dir.path(), &["commit", "-m", &format!("c{i}")]);
6012        }
6013        git_in(dir.path(), &["repack", "-a", "-d"]);
6014        let objects = dir.path().join(".git/objects");
6015        let oid = git_rev_parse_oid(dir.path(), "HEAD");
6016
6017        clear_pack_cache();
6018        test_reset_pack_marker_stat_count();
6019        let pack_count = fs::read_dir(objects.join("pack"))
6020            .unwrap()
6021            .filter_map(|e| e.ok())
6022            .filter(|e| e.path().extension().is_some_and(|x| x == "pack"))
6023            .count();
6024        let expected_prepare_stats = u64::try_from(pack_count * 2).unwrap();
6025        let odb = Odb::new(&objects);
6026        let before_prepare = test_pack_marker_stat_count();
6027        assert!(odb.exists_local(&oid));
6028        assert_eq!(
6029            test_pack_marker_stat_count().saturating_sub(before_prepare),
6030            expected_prepare_stats,
6031            "prepare should stat promisor and mtimes once per pack"
6032        );
6033
6034        test_reset_pack_marker_stat_count();
6035        for _ in 0..10_000 {
6036            let before_probe = test_pack_marker_stat_count();
6037            assert!(odb.exists_local(&oid));
6038            assert_eq!(
6039                test_pack_marker_stat_count(),
6040                before_probe,
6041                "cached sidecar flags must not stat markers on each exists_local probe"
6042            );
6043        }
6044    }
6045
6046    #[cfg_attr(
6047        not(feature = "full-tests"),
6048        ignore = "starts system git or is heavy; run with --features full-tests"
6049    )]
6050    #[test]
6051    fn promisor_marker_added_after_prepare_is_seen_after_reprepare() {
6052        use crate::pack::{
6053            clear_pack_cache, pack_cache_test_guard, reprepare_pack_directory_on_miss,
6054        };
6055
6056        let _guard = pack_cache_test_guard();
6057        let dir = TempDir::new().unwrap();
6058        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6059        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6060        git_in(dir.path(), &["config", "user.name", "T"]);
6061        fs::write(dir.path().join("one.txt"), b"x").unwrap();
6062        git_in(dir.path(), &["add", "one.txt"]);
6063        git_in(dir.path(), &["commit", "-m", "one"]);
6064        git_in(dir.path(), &["repack", "-a", "-d"]);
6065        let objects = dir.path().join(".git/objects");
6066        let oid = git_rev_parse_oid(dir.path(), "HEAD");
6067
6068        clear_pack_cache();
6069        let odb = Odb::new(&objects);
6070        assert!(odb.exists_local(&oid));
6071
6072        let pack_path = fs::read_dir(objects.join("pack"))
6073            .unwrap()
6074            .filter_map(|e| e.ok())
6075            .map(|e| e.path())
6076            .find(|p| p.extension().is_some_and(|x| x == "pack"))
6077            .unwrap();
6078        fs::write(pack_path.with_extension("promisor"), b"").unwrap();
6079        filetime::set_file_mtime(objects.join("pack"), filetime::FileTime::now()).unwrap();
6080
6081        assert!(
6082            odb.with_pack_store_for(&objects, || {
6083                reprepare_pack_directory_on_miss(&objects).unwrap()
6084            }),
6085            "pack directory change must require reprepare"
6086        );
6087        assert!(
6088            !odb.exists_local(&oid),
6089            "promisor marker must hide pack objects after reprepare refreshed sidecar flags"
6090        );
6091    }
6092
6093    #[cfg_attr(
6094        not(feature = "full-tests"),
6095        ignore = "starts system git or is heavy; run with --features full-tests"
6096    )]
6097    #[test]
6098    fn git_promisor_marker_pack_not_materialized_for_exists_local() {
6099        use crate::pack::clear_pack_cache;
6100
6101        let dir = TempDir::new().unwrap();
6102        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6103        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6104        git_in(dir.path(), &["config", "user.name", "T"]);
6105        fs::write(dir.path().join("blob.txt"), b"git promisor compat").unwrap();
6106        git_in(dir.path(), &["add", "blob.txt"]);
6107        git_in(dir.path(), &["commit", "-m", "seed"]);
6108        git_in(dir.path(), &["repack", "-a", "-d"]);
6109        let objects = dir.path().join(".git/objects");
6110        let oid = git_rev_parse_oid(dir.path(), "HEAD");
6111        let pack_path = fs::read_dir(objects.join("pack"))
6112            .unwrap()
6113            .filter_map(|e| e.ok())
6114            .map(|e| e.path())
6115            .find(|p| p.extension().is_some_and(|x| x == "pack"))
6116            .unwrap();
6117        fs::write(pack_path.with_extension("promisor"), b"").unwrap();
6118
6119        clear_pack_cache();
6120        let odb = Odb::new(&objects);
6121        assert!(
6122            !odb.exists_local(&oid),
6123            "git-written pack with .promisor must not count as local materialization"
6124        );
6125
6126        let cat = git_run(dir.path(), &["cat-file", "-e", &oid.to_hex()]);
6127        assert!(
6128            cat.status.success(),
6129            "git still resolves the object in a promisor-marked pack"
6130        );
6131    }
6132
6133    #[cfg_attr(
6134        not(feature = "full-tests"),
6135        ignore = "starts system git or is heavy; run with --features full-tests"
6136    )]
6137    #[test]
6138    fn packed_object_read_avoids_loose_path_open() {
6139        use crate::hot_path_test_metrics::HotPathMetricsScope;
6140        use crate::pack::clear_pack_cache;
6141
6142        let dir = TempDir::new().unwrap();
6143        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6144        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6145        git_in(dir.path(), &["config", "user.name", "T"]);
6146        fs::write(dir.path().join("packed.txt"), b"packed-only payload").unwrap();
6147        git_in(dir.path(), &["add", "packed.txt"]);
6148        git_in(dir.path(), &["commit", "-m", "pack"]);
6149        git_in(dir.path(), &["repack", "-a", "-d"]);
6150        let objects = dir.path().join(".git/objects");
6151        let oid = git_rev_parse_oid(dir.path(), "HEAD");
6152
6153        clear_pack_cache();
6154        let odb = Odb::new(&objects);
6155        odb.hot_path_metrics().set_loose_open_counting(true);
6156        odb.hot_path_metrics().reset_loose_path_open_attempts();
6157        let _scope = HotPathMetricsScope::install(odb.hot_path_metrics_arc());
6158
6159        let obj = odb.read(&oid).expect("packed read");
6160        assert_eq!(obj.kind, ObjectKind::Commit);
6161        assert_eq!(
6162            odb.hot_path_metrics().loose_path_open_attempts(),
6163            0,
6164            "packed objects must not attempt a loose-path open"
6165        );
6166    }
6167
6168    #[cfg_attr(
6169        not(feature = "full-tests"),
6170        ignore = "starts system git or is heavy; run with --features full-tests"
6171    )]
6172    #[test]
6173    fn initial_clone_ref_batch_hits_packed_commit_once_for_many_refs() {
6174        use std::sync::Arc;
6175
6176        use crate::hot_path_test_metrics::HotPathMetricsScope;
6177        use crate::pack::clear_pack_cache;
6178        use crate::refs::commit_initial_clone_ref_updates_on_store;
6179        use crate::refs::store::{Expected, ObjectCheckedRefStore, RawRef, RefName, RefUpdate};
6180
6181        const N: usize = 4096;
6182        let dir = TempDir::new().unwrap();
6183        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6184        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6185        git_in(dir.path(), &["config", "user.name", "T"]);
6186        fs::write(dir.path().join("packed.txt"), b"payload").unwrap();
6187        git_in(dir.path(), &["add", "packed.txt"]);
6188        git_in(dir.path(), &["commit", "-m", "pack"]);
6189        git_in(dir.path(), &["repack", "-a", "-d"]);
6190        let git_dir = dir.path().join(".git");
6191        let objects = git_dir.join("objects");
6192        let head = git_rev_parse_oid(dir.path(), "HEAD");
6193
6194        clear_pack_cache();
6195        let odb = Odb::new(&objects).with_config_git_dir(git_dir.clone());
6196        odb.hot_path_metrics().set_loose_open_counting(true);
6197        odb.hot_path_metrics().reset_loose_path_open_attempts();
6198        let metrics = odb.hot_path_metrics_arc();
6199        let _scope = HotPathMetricsScope::install(Arc::clone(&metrics));
6200        let inner = crate::refs::store::open_ref_store(&git_dir).expect("refs");
6201        let store = ObjectCheckedRefStore::new(inner, odb);
6202        let updates: Vec<RefUpdate> = (0..N)
6203            .map(|i| RefUpdate {
6204                name: RefName::from_trusted(format!("refs/remotes/origin/b/{i}")),
6205                new_value: Some(RawRef::Direct(head)),
6206                expected: Expected::Any,
6207                reflog: None,
6208                flags: Default::default(),
6209            })
6210            .collect();
6211        commit_initial_clone_ref_updates_on_store(&store, updates).expect("initial refs");
6212        assert!(
6213            metrics.loose_path_open_attempts() <= 1,
6214            "many refs at one packed oid must not open a loose path per ref (got {})",
6215            metrics.loose_path_open_attempts()
6216        );
6217        git_in(dir.path(), &["fsck"]);
6218    }
6219
6220    #[cfg_attr(
6221        not(feature = "full-tests"),
6222        ignore = "starts system git or is heavy; run with --features full-tests"
6223    )]
6224    #[test]
6225    fn packed_reads_after_first_pack_load_do_not_stat_pack_dir() {
6226        use crate::hot_path_test_metrics::HotPathMetricsScope;
6227        use crate::pack::{clear_pack_cache, pack_cache_test_guard};
6228
6229        let _guard = pack_cache_test_guard();
6230        let dir = TempDir::new().unwrap();
6231        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6232        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6233        git_in(dir.path(), &["config", "user.name", "T"]);
6234        for i in 0..32 {
6235            fs::write(dir.path().join("f.txt"), format!("body {i}")).unwrap();
6236            git_in(dir.path(), &["add", "f.txt"]);
6237            git_in(dir.path(), &["commit", "-q", "-m", &format!("c{i}")]);
6238        }
6239        git_in(dir.path(), &["repack", "-a", "-d"]);
6240        let objects = dir.path().join(".git/objects");
6241        let commits: Vec<ObjectId> = (0..32)
6242            .map(|n| git_rev_parse_oid(dir.path(), &format!("HEAD~{n}")))
6243            .collect();
6244
6245        clear_pack_cache();
6246        let odb = Odb::new(&objects);
6247        let _scope = HotPathMetricsScope::install(odb.hot_path_metrics_arc());
6248        odb.with_pack_read_context(|| {
6249            // The first read lists the pack directory and maps the pack for the first time.
6250            let first = odb.read(&commits[0]).expect("first packed read");
6251            assert_eq!(first.kind, ObjectKind::Commit);
6252
6253            odb.hot_path_metrics().reset_pack_dir_stats();
6254            odb.hot_path_metrics().set_stamp_counting(true);
6255            for oid in &commits[1..] {
6256                let obj = odb.read(oid).expect("packed read");
6257                assert_eq!(obj.kind, ObjectKind::Commit);
6258                odb.read_info(oid).expect("packed read_info");
6259            }
6260            odb.hot_path_metrics().set_stamp_counting(false);
6261        });
6262        assert_eq!(
6263            odb.hot_path_metrics().pack_dir_stat_calls(),
6264            0,
6265            "loading a pack for the first time must keep the trusted pack listing"
6266        );
6267    }
6268
6269    #[cfg_attr(
6270        not(feature = "full-tests"),
6271        ignore = "starts system git or is heavy; run with --features full-tests"
6272    )]
6273    #[test]
6274    fn alternate_packed_reads_do_not_rescan_local_pack_dir() {
6275        use crate::hot_path_test_metrics::HotPathMetricsScope;
6276        use crate::pack::{clear_pack_cache, pack_cache};
6277
6278        let upstream = TempDir::new().unwrap();
6279        git_in(upstream.path(), &["init", "-q", "-b", "main"]);
6280        git_in(upstream.path(), &["config", "user.email", "t@example.com"]);
6281        git_in(upstream.path(), &["config", "user.name", "T"]);
6282        fs::write(
6283            upstream.path().join("payload.txt"),
6284            b"alternate-only-in-upstream",
6285        )
6286        .unwrap();
6287        git_in(upstream.path(), &["add", "payload.txt"]);
6288        git_in(upstream.path(), &["commit", "-m", "seed"]);
6289        for n in 0..48 {
6290            let name = format!("blob-{n}.txt");
6291            fs::write(
6292                upstream.path().join(&name),
6293                format!("alternate-only-payload-{n}").as_bytes(),
6294            )
6295            .unwrap();
6296            git_in(upstream.path(), &["add", name.as_str()]);
6297            git_in(
6298                upstream.path(),
6299                &["commit", "-m", &format!("packed commit {n}")],
6300            );
6301        }
6302        git_in(upstream.path(), &["repack", "-a", "-d"]);
6303        let rev_out = git_run(upstream.path(), &["rev-list", "HEAD"]);
6304        assert!(rev_out.status.success());
6305        let oids: Vec<ObjectId> = std::str::from_utf8(&rev_out.stdout)
6306            .unwrap()
6307            .lines()
6308            .filter(|line| !line.is_empty())
6309            .map(|line| ObjectId::from_hex(line.trim()).expect("rev-list oid"))
6310            .collect();
6311        assert!(
6312            oids.len() >= 32,
6313            "need many distinct commit oids for metadata regression"
6314        );
6315
6316        let layout = TempDir::new().unwrap();
6317        git_in(
6318            layout.path(),
6319            &[
6320                "clone",
6321                "-q",
6322                "--shared",
6323                upstream.path().to_str().unwrap(),
6324                "shared",
6325            ],
6326        );
6327        let objects = layout.path().join("shared/.git/objects");
6328        let local_pack = objects.join("pack");
6329
6330        clear_pack_cache();
6331        let odb = Odb::new(&objects);
6332        odb.hot_path_metrics().set_loose_open_counting(true);
6333        odb.hot_path_metrics().set_loose_metadata_counting(true);
6334        odb.hot_path_metrics().set_stamp_counting(true);
6335        odb.hot_path_metrics().reset_loose_path_open_attempts();
6336        odb.hot_path_metrics().reset_loose_metadata_probes();
6337        odb.hot_path_metrics().reset_pack_dir_metadata_probes();
6338        let _scope = HotPathMetricsScope::install(odb.hot_path_metrics_arc());
6339        pack_cache::test_reset_dir_rescan_count(&local_pack);
6340        let upstream_pack = upstream.path().join(".git/objects/pack");
6341        let upstream_objects = upstream.path().join(".git/objects");
6342        let upstream_store = odb.pack_store_for(&upstream_objects);
6343        pack_cache::test_reset_dir_rescan_count_on_store(&upstream_store, &upstream_pack);
6344        odb.with_pack_read_context(|| {
6345            for oid in &oids {
6346                odb.read(oid).expect("alternate warmup read");
6347            }
6348            let after_first = pack_cache::test_dir_rescan_count(&local_pack);
6349            let after_first_alt =
6350                pack_cache::test_dir_rescan_count_on_store(&upstream_store, &upstream_pack);
6351            let loose_after_first = odb.hot_path_metrics().loose_path_open_attempts();
6352            let root_meta_after_first = odb.hot_path_metrics().loose_objects_root_metadata_probes();
6353            let fanout_meta_after_first = odb.hot_path_metrics().loose_fanout_metadata_probes();
6354            let exists_meta_after_first = odb.hot_path_metrics().loose_path_exists_probes();
6355            let loose_meta_after_first = odb.hot_path_metrics().loose_metadata_probe_total();
6356            let pack_dir_meta_after_first = odb.hot_path_metrics().pack_dir_metadata_probes();
6357            for _ in 0..2 {
6358                for oid in &oids {
6359                    odb.read(oid).expect("repeat alternate read");
6360                }
6361            }
6362            assert_eq!(
6363                odb.hot_path_metrics().loose_path_open_attempts(),
6364                loose_after_first,
6365                "alternate hits must not stat loose paths on the empty primary after warmup"
6366            );
6367            assert_eq!(
6368                odb.hot_path_metrics().loose_objects_root_metadata_probes(),
6369                root_meta_after_first,
6370                "known-absent fanout must not re-stat the objects root after warmup"
6371            );
6372            assert_eq!(
6373                odb.hot_path_metrics().loose_fanout_metadata_probes(),
6374                fanout_meta_after_first,
6375                "known-absent fanout must not re-stat fanout directories after warmup"
6376            );
6377            assert_eq!(
6378                odb.hot_path_metrics().loose_path_exists_probes(),
6379                exists_meta_after_first,
6380                "known-absent fanout must not is_file/is_dir loose paths after warmup"
6381            );
6382            assert_eq!(
6383                odb.hot_path_metrics().loose_metadata_probe_total(),
6384                loose_meta_after_first,
6385                "no loose metadata probes after warmup across distinct alternate oids"
6386            );
6387            assert_eq!(
6388                odb.hot_path_metrics().pack_dir_metadata_probes(),
6389                pack_dir_meta_after_first,
6390                "alternate catalog hits must not stat pack directories after warmup"
6391            );
6392            assert_eq!(
6393                pack_cache::test_dir_rescan_count(&local_pack),
6394                after_first,
6395                "alternate hits must not re-list the local pack directory"
6396            );
6397            assert_eq!(
6398                pack_cache::test_dir_rescan_count_on_store(&upstream_store, &upstream_pack),
6399                after_first_alt,
6400                "alternate hits must not re-list the alternate pack directory"
6401            );
6402
6403            let fresh = b"loose in primary after warmup\n";
6404            let local_oid = odb.write(ObjectKind::Blob, fresh).expect("local loose");
6405            let obj = odb.read(&local_oid).expect("read local loose after warmup");
6406            assert_eq!(obj.data.as_slice(), fresh);
6407        });
6408    }
6409
6410    #[cfg_attr(
6411        not(feature = "full-tests"),
6412        ignore = "starts system git or is heavy; run with --features full-tests"
6413    )]
6414    #[test]
6415    fn external_loose_write_visible_on_first_read_after_alternate_warmup() {
6416        use std::process::{Command, Stdio};
6417
6418        use crate::pack::clear_pack_cache;
6419
6420        let upstream = TempDir::new().unwrap();
6421        git_in(upstream.path(), &["init", "-q", "-b", "main"]);
6422        git_in(upstream.path(), &["config", "user.email", "t@example.com"]);
6423        git_in(upstream.path(), &["config", "user.name", "T"]);
6424        fs::write(upstream.path().join("seed.txt"), b"upstream seed").unwrap();
6425        git_in(upstream.path(), &["add", "seed.txt"]);
6426        git_in(upstream.path(), &["commit", "-m", "seed"]);
6427        git_in(upstream.path(), &["repack", "-a", "-d"]);
6428        let warm_oid = git_rev_parse_oid(upstream.path(), "HEAD");
6429
6430        let layout = TempDir::new().unwrap();
6431        git_in(
6432            layout.path(),
6433            &[
6434                "clone",
6435                "-q",
6436                "--shared",
6437                upstream.path().to_str().unwrap(),
6438                "shared",
6439            ],
6440        );
6441        let objects = layout.path().join("shared/.git/objects");
6442
6443        clear_pack_cache();
6444        let odb = Odb::new(&objects);
6445        odb.with_pack_read_context(|| {
6446            odb.read(&warm_oid).expect("warm alternate-packed commit");
6447        });
6448
6449        let payload = b"external loose after alternate warmup\n";
6450        let local_oid = odb.hash(ObjectKind::Blob, payload).unwrap();
6451        let mut child = Command::new("git")
6452            .args(["hash-object", "-w", "--stdin"])
6453            .stdin(Stdio::piped())
6454            .stdout(Stdio::piped())
6455            .env("GIT_OBJECT_DIRECTORY", &objects)
6456            .env("GIT_CONFIG_GLOBAL", "/dev/null")
6457            .env("GIT_CONFIG_SYSTEM", "/dev/null")
6458            .spawn()
6459            .expect("git hash-object");
6460        if let Some(mut stdin) = child.stdin.take() {
6461            use std::io::Write;
6462            stdin.write_all(payload).unwrap();
6463        }
6464        let out = child.wait_with_output().expect("git wait");
6465        assert!(
6466            out.status.success(),
6467            "git hash-object: {}",
6468            String::from_utf8_lossy(&out.stderr)
6469        );
6470        assert_eq!(
6471            String::from_utf8_lossy(&out.stdout).trim(),
6472            local_oid.to_hex()
6473        );
6474
6475        let obj = odb
6476            .read(&local_oid)
6477            .expect("first read after external primary loose write must succeed");
6478        assert_eq!(obj.data.as_slice(), payload);
6479    }
6480
6481    #[test]
6482    fn loose_only_read_records_loose_path_open() {
6483        use crate::hot_path_test_metrics::HotPathMetricsScope;
6484
6485        let dir = TempDir::new().unwrap();
6486        let objects = dir.path().join("objects");
6487        fs::create_dir_all(&objects).unwrap();
6488        let odb = Odb::new(&objects);
6489        let oid = odb
6490            .write(ObjectKind::Blob, b"loose-only")
6491            .expect("write loose");
6492        odb.hot_path_metrics().set_loose_open_counting(true);
6493        odb.hot_path_metrics().reset_loose_path_open_attempts();
6494        let _scope = HotPathMetricsScope::install(odb.hot_path_metrics_arc());
6495
6496        odb.read(&oid).expect("loose read");
6497        assert_eq!(
6498            odb.hot_path_metrics().loose_path_open_attempts(),
6499            1,
6500            "loose fallback must record a path open attempt"
6501        );
6502    }
6503
6504    #[cfg_attr(
6505        not(feature = "full-tests"),
6506        ignore = "starts system git or is heavy; run with --features full-tests"
6507    )]
6508    #[test]
6509    fn loose_and_packed_copies_return_identical_bytes() {
6510        use crate::pack::clear_pack_cache;
6511
6512        let dir = TempDir::new().unwrap();
6513        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6514        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6515        git_in(dir.path(), &["config", "user.name", "T"]);
6516        fs::write(dir.path().join("dup.txt"), b"duplicate loose and packed\n").unwrap();
6517        git_in(dir.path(), &["add", "dup.txt"]);
6518        git_in(dir.path(), &["commit", "-m", "seed"]);
6519        let objects = dir.path().join(".git/objects");
6520        let tree_oid = git_rev_parse_oid(dir.path(), "HEAD^{tree}");
6521        git_in(dir.path(), &["repack", "-a"]);
6522        clear_pack_cache();
6523        let odb = Odb::new(&objects);
6524        let loose_path = tree_oid.loose_path_in(&objects);
6525        assert!(
6526            loose_path.is_file(),
6527            "loose copy must remain after repack -a"
6528        );
6529        let loose = Odb::read_loose_verify_oid(&loose_path, &tree_oid).expect("loose tree");
6530        let packed = odb.read(&tree_oid).expect("packed tree");
6531        assert_eq!(packed.data, loose.data);
6532        assert_eq!(packed.kind, loose.kind);
6533    }
6534
6535    #[cfg_attr(
6536        not(feature = "full-tests"),
6537        ignore = "starts system git or is heavy; run with --features full-tests"
6538    )]
6539    #[test]
6540    fn freshly_written_loose_object_visible_before_repack() {
6541        let dir = TempDir::new().unwrap();
6542        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6543        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6544        git_in(dir.path(), &["config", "user.name", "T"]);
6545        fs::write(dir.path().join("seed.txt"), b"seed").unwrap();
6546        git_in(dir.path(), &["add", "seed.txt"]);
6547        git_in(dir.path(), &["commit", "-m", "seed"]);
6548        git_in(dir.path(), &["repack", "-a", "-d"]);
6549        let objects = dir.path().join(".git/objects");
6550        let odb = Odb::new(&objects);
6551        let fresh = b"brand-new loose blob\n";
6552        let oid = odb.write(ObjectKind::Blob, fresh).expect("loose write");
6553        let obj = odb.read(&oid).expect("immediate loose read");
6554        assert_eq!(obj.data.as_slice(), fresh);
6555    }
6556
6557    #[cfg_attr(
6558        not(feature = "full-tests"),
6559        ignore = "starts system git or is heavy; run with --features full-tests"
6560    )]
6561    #[test]
6562    fn pack_added_after_first_read_found_via_odb_reprepare() {
6563        use crate::pack::{clear_pack_cache, pack_cache_test_guard};
6564
6565        let _guard = pack_cache_test_guard();
6566        clear_pack_cache();
6567        let dir = TempDir::new().unwrap();
6568        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6569        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6570        git_in(dir.path(), &["config", "user.name", "T"]);
6571        fs::write(dir.path().join("a.txt"), b"pack-a").unwrap();
6572        git_in(dir.path(), &["add", "a.txt"]);
6573        git_in(dir.path(), &["commit", "-m", "a"]);
6574        git_in(dir.path(), &["repack", "-a", "-d"]);
6575        let objects = dir.path().join(".git/objects");
6576        let pack_dir = objects.join("pack");
6577        let git_dir = dir.path().join(".git");
6578
6579        let odb = Odb::new(&objects).with_config_git_dir(git_dir);
6580        let warm_oid = git_rev_parse_oid(dir.path(), "HEAD");
6581        odb.read(&warm_oid).expect("warm read");
6582
6583        fs::write(dir.path().join("b.txt"), b"pack-b").unwrap();
6584        git_in(dir.path(), &["add", "b.txt"]);
6585        git_in(dir.path(), &["commit", "-m", "b"]);
6586        let new_oid = git_rev_parse_oid(dir.path(), "HEAD");
6587
6588        std::thread::sleep(std::time::Duration::from_secs(1));
6589        filetime::set_file_mtime(&pack_dir, filetime::FileTime::now()).unwrap();
6590
6591        let obj = odb.read(&new_oid).expect("new pack via reprepare");
6592        assert_eq!(obj.kind, ObjectKind::Commit);
6593    }
6594
6595    #[cfg_attr(
6596        not(feature = "full-tests"),
6597        ignore = "starts system git or is heavy; run with --features full-tests"
6598    )]
6599    #[test]
6600    fn external_pack_drop_in_visible_after_empty_primary_miss() {
6601        use crate::pack::{clear_pack_cache, pack_cache_test_guard};
6602
6603        let _guard = pack_cache_test_guard();
6604        clear_pack_cache();
6605        let source = TempDir::new().unwrap();
6606        git_in(source.path(), &["init", "-q", "-b", "main"]);
6607        git_in(source.path(), &["config", "user.email", "t@example.com"]);
6608        git_in(source.path(), &["config", "user.name", "T"]);
6609        fs::write(source.path().join("drop-in.txt"), b"external pack payload").unwrap();
6610        git_in(source.path(), &["add", "drop-in.txt"]);
6611        git_in(source.path(), &["commit", "-m", "drop-in"]);
6612        git_in(source.path(), &["repack", "-a", "-d"]);
6613        let commit_oid = git_rev_parse_oid(source.path(), "HEAD");
6614        let source_pack = source.path().join(".git/objects/pack");
6615        let (pack_path, idx_path) = fs::read_dir(&source_pack)
6616            .unwrap()
6617            .filter_map(|e| e.ok())
6618            .map(|e| e.path())
6619            .find_map(|path| {
6620                path.extension()
6621                    .is_some_and(|ext| ext == "pack")
6622                    .then(|| (path.clone(), path.with_extension("idx")))
6623            })
6624            .expect("source pack");
6625
6626        let bare = TempDir::new().unwrap();
6627        let objects = bare.path().join("objects");
6628        fs::create_dir_all(objects.join("pack")).unwrap();
6629        let odb = Odb::new(&objects);
6630        assert!(
6631            odb.read(&commit_oid).is_err(),
6632            "empty primary must miss before the pack exists"
6633        );
6634
6635        std::thread::sleep(std::time::Duration::from_secs(1));
6636        let dest_pack = objects
6637            .join("pack")
6638            .join(pack_path.file_name().expect("pack basename"));
6639        let dest_idx = objects
6640            .join("pack")
6641            .join(idx_path.file_name().expect("idx basename"));
6642        fs::copy(&pack_path, &dest_pack).unwrap();
6643        fs::copy(&idx_path, &dest_idx).unwrap();
6644
6645        let obj = odb
6646            .read(&commit_oid)
6647            .expect("external pack drop-in must be visible after reprepare");
6648        assert_eq!(obj.kind, ObjectKind::Commit);
6649    }
6650
6651    #[cfg_attr(
6652        not(feature = "full-tests"),
6653        ignore = "starts system git or is heavy; run with --features full-tests"
6654    )]
6655    #[test]
6656    fn late_midx_after_warm_read_resolves_new_commit() {
6657        use crate::pack::{clear_pack_cache, pack_cache_test_guard};
6658
6659        let _guard = pack_cache_test_guard();
6660        clear_pack_cache();
6661        let dir = TempDir::new().unwrap();
6662        git_in(dir.path(), &["init", "-q", "-b", "main"]);
6663        git_in(dir.path(), &["config", "user.email", "t@example.com"]);
6664        git_in(dir.path(), &["config", "user.name", "T"]);
6665        fs::write(dir.path().join("a.txt"), b"pack-a").unwrap();
6666        git_in(dir.path(), &["add", "a.txt"]);
6667        git_in(dir.path(), &["commit", "-m", "a"]);
6668        git_in(dir.path(), &["repack", "-a", "-d"]);
6669        let objects = dir.path().join(".git/objects");
6670        let git_dir = dir.path().join(".git");
6671        assert!(
6672            crate::midx::cached_tip_midx_path(&objects.join("pack")).is_none(),
6673            "fixture starts without a MIDX"
6674        );
6675
6676        let odb = Odb::new(&objects).with_config_git_dir(git_dir);
6677        let warm_oid = git_rev_parse_oid(dir.path(), "HEAD");
6678        odb.read(&warm_oid).expect("warm read before MIDX exists");
6679
6680        fs::write(dir.path().join("b.txt"), b"pack-b").unwrap();
6681        git_in(dir.path(), &["add", "b.txt"]);
6682        git_in(dir.path(), &["commit", "-m", "b"]);
6683        git_in(dir.path(), &["repack", "-a", "-d"]);
6684        git_in(dir.path(), &["multi-pack-index", "write"]);
6685        let new_oid = git_rev_parse_oid(dir.path(), "HEAD");
6686
6687        let cat = git_run(dir.path(), &["cat-file", "-e", &new_oid.to_hex()]);
6688        assert!(
6689            cat.status.success(),
6690            "system git must resolve the new commit"
6691        );
6692
6693        let obj = odb
6694            .read(&new_oid)
6695            .expect("MIDX-covered commit after late MIDX write");
6696        assert_eq!(obj.kind, ObjectKind::Commit);
6697        assert!(
6698            crate::midx::cached_tip_midx_path(&objects.join("pack")).is_some(),
6699            "successful read after late MIDX must refresh the tip cache"
6700        );
6701    }
6702}