Skip to main content

git_internal/internal/pack/
decode.rs

1//! Streaming pack decoder that validates headers, inflates entries, rebuilds deltas (including zstd),
2//! and populates caches/metadata for downstream consumers.
3
4#[cfg(not(unix))]
5use std::io::{Seek, SeekFrom};
6#[cfg(unix)]
7use std::os::unix::fs::FileExt;
8use std::{
9    fs::File,
10    io::{self, BufRead, Cursor, Read, Write},
11    path::{Path, PathBuf},
12    sync::{
13        Arc, Mutex, OnceLock,
14        atomic::{AtomicUsize, Ordering},
15    },
16    thread::{self, JoinHandle},
17    time::Instant,
18};
19
20use axum::Error;
21use bytes::Bytes;
22use dashmap::DashMap;
23use flate2::bufread::ZlibDecoder;
24use futures_util::{Stream, StreamExt};
25use tempfile::NamedTempFile;
26use threadpool::ThreadPool;
27use tokio::sync::mpsc::UnboundedSender;
28use uuid::Uuid;
29
30pub use crate::internal::pack::stats::PackStats;
31use crate::{
32    errors::GitError,
33    hash::{HashKind, ObjectHash, get_hash_kind, set_hash_kind},
34    internal::{
35        metadata::{EntryMeta, MetaAttached},
36        object::types::ObjectType,
37        pack::{
38            DEFAULT_TMP_DIR, Pack,
39            cache::{_Cache, Caches},
40            cache_object::{CacheObject, CacheObjectInfo, MemSizeRecorder},
41            channel_reader::StreamBufReader,
42            entry::Entry,
43            pack_index, utils,
44            waitlist::Waitlist,
45            wrapper::Wrapper,
46        },
47    },
48    utils::{CountingReader, HashAlgorithm},
49    zstdelta,
50};
51
52/// A reader that counts bytes read and optionally computes the object CRC32 needed for idx metadata.
53struct CrcCountingReader<R> {
54    inner: R,
55    bytes_read: u64,
56    crc: Option<crc32fast::Hasher>,
57}
58
59impl<R: Read> Read for CrcCountingReader<R> {
60    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
61        let n = self.inner.read(buf)?;
62        self.bytes_read += n as u64;
63        if let Some(crc) = &mut self.crc {
64            crc.update(&buf[..n]);
65        }
66        Ok(n)
67    }
68}
69impl<R: BufRead> BufRead for CrcCountingReader<R> {
70    fn fill_buf(&mut self) -> io::Result<&[u8]> {
71        self.inner.fill_buf()
72    }
73    fn consume(&mut self, amt: usize) {
74        if let Some(crc) = &mut self.crc {
75            let buf = self.inner.fill_buf().unwrap_or(&[]);
76            crc.update(&buf[..amt.min(buf.len())]);
77        }
78        self.bytes_read += amt as u64;
79        self.inner.consume(amt);
80    }
81}
82
83impl<R> CrcCountingReader<R> {
84    fn crc32(&mut self) -> u32 {
85        self.crc
86            .take()
87            .map(crc32fast::Hasher::finalize)
88            .unwrap_or(0)
89    }
90}
91
92/// For the convenience of passing parameters
93type DecodeCallback = Arc<dyn Fn(MetaAttached<Entry, EntryMeta>) + Sync + Send>;
94
95struct SharedParams {
96    pub pool: Arc<ThreadPool>,
97    pub waitlist: Arc<Waitlist>,
98    pub caches: Arc<Caches>,
99    pub cache_objs_mem_size: Arc<AtomicUsize>,
100    pub callback: Option<DecodeCallback>,
101    pub retention: Option<Arc<DecodeRetention>>,
102    pub skip_unneeded_objects: bool,
103    pub error: Mutex<Option<GitError>>,
104}
105
106#[derive(Default)]
107struct DecodeRetention {
108    offset_remaining: DashMap<usize, usize>,
109    hash_remaining: DashMap<ObjectHash, usize>,
110}
111
112struct DecodeScan {
113    retention: DecodeRetention,
114    object_hashes: Option<Vec<ObjectHash>>,
115    /// idx CRC32 per object (pack order), verified while decoding when CRCs are tracked.
116    object_crcs: Option<Vec<u32>>,
117    /// idx offset per object (pack order), verified against each object's real start offset.
118    object_offsets: Option<Vec<usize>>,
119    pack_hash: Option<ObjectHash>,
120    pack_hash_check: Option<PackHashCheck>,
121}
122
123struct PackHashCheck {
124    payload_hash: ObjectHash,
125    trailer_hash: ObjectHash,
126}
127
128struct DecodeRetentionMode {
129    retention: Option<Arc<DecodeRetention>>,
130    skip_unneeded_objects: bool,
131}
132
133struct DecodeOptions {
134    retention_mode: DecodeRetentionMode,
135    known_hashes: Option<Vec<ObjectHash>>,
136    known_crcs: Option<Vec<u32>>,
137    known_offsets: Option<Vec<usize>>,
138    expected_pack_hash: Option<ObjectHash>,
139    verify_pack_stream_hash: bool,
140    sync_base_callbacks: bool,
141}
142
143struct TeeReader<'a, R, W> {
144    reader: &'a mut R,
145    writer: &'a mut W,
146    write_error: Option<io::Error>,
147    payload_hash: HashAlgorithm,
148    hash_tail: Vec<u8>,
149    hash_size: usize,
150}
151
152#[derive(Clone, Copy)]
153enum FileDecodeMode {
154    RetainAll,
155    SkipUnneeded,
156}
157
158impl DecodeRetentionMode {
159    fn none() -> Self {
160        Self {
161            retention: None,
162            skip_unneeded_objects: false,
163        }
164    }
165
166    fn retain_all(retention: Arc<DecodeRetention>) -> Self {
167        Self {
168            retention: Some(retention),
169            skip_unneeded_objects: false,
170        }
171    }
172
173    fn skip_unneeded(retention: Arc<DecodeRetention>) -> Self {
174        Self {
175            retention: Some(retention),
176            skip_unneeded_objects: true,
177        }
178    }
179}
180
181impl DecodeOptions {
182    fn streaming() -> Self {
183        Self {
184            retention_mode: DecodeRetentionMode::none(),
185            known_hashes: None,
186            known_crcs: None,
187            known_offsets: None,
188            expected_pack_hash: None,
189            verify_pack_stream_hash: true,
190            sync_base_callbacks: false,
191        }
192    }
193}
194
195impl<R, W> TeeReader<'_, R, W> {
196    fn check_write_error(&mut self) -> io::Result<()> {
197        if let Some(err) = self.write_error.take() {
198            Err(err)
199        } else {
200            Ok(())
201        }
202    }
203
204    fn record_pack_bytes(
205        payload_hash: &mut HashAlgorithm,
206        hash_tail: &mut Vec<u8>,
207        hash_size: usize,
208        bytes: &[u8],
209    ) {
210        if bytes.is_empty() {
211            return;
212        }
213
214        let total_len = hash_tail.len() + bytes.len();
215        if total_len <= hash_size {
216            hash_tail.extend_from_slice(bytes);
217            return;
218        }
219
220        let hash_len = total_len - hash_size;
221        if hash_len <= hash_tail.len() {
222            payload_hash.update(&hash_tail[..hash_len]);
223            hash_tail.drain(..hash_len);
224            hash_tail.extend_from_slice(bytes);
225        } else {
226            let tail_len = hash_tail.len();
227            if !hash_tail.is_empty() {
228                payload_hash.update(hash_tail);
229                hash_tail.clear();
230            }
231            let bytes_hash_len = hash_len - tail_len;
232            payload_hash.update(&bytes[..bytes_hash_len]);
233            hash_tail.extend_from_slice(&bytes[bytes_hash_len..]);
234        }
235    }
236
237    fn finish_pack_hash_check(self) -> Result<PackHashCheck, GitError> {
238        if self.hash_tail.len() != self.hash_size {
239            return Err(GitError::InvalidPackFile(
240                "Pack file is too small to contain a trailer hash".to_string(),
241            ));
242        }
243        let kind = self.payload_hash.kind();
244        let payload_hash = self.payload_hash.finalize_object_hash();
245        let trailer_hash = ObjectHash::from_bytes_for_kind(kind, &self.hash_tail)
246            .map_err(|e| GitError::InvalidPackFile(format!("Read pack file error: {e}")))?;
247        Ok(PackHashCheck {
248            payload_hash,
249            trailer_hash,
250        })
251    }
252}
253
254impl<R: Read, W: Write> Read for TeeReader<'_, R, W> {
255    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
256        self.check_write_error()?;
257        let n = self.reader.read(buf)?;
258        if n != 0 {
259            self.writer.write_all(&buf[..n])?;
260            Self::record_pack_bytes(
261                &mut self.payload_hash,
262                &mut self.hash_tail,
263                self.hash_size,
264                &buf[..n],
265            );
266        }
267        Ok(n)
268    }
269}
270
271impl<R: BufRead, W: Write> BufRead for TeeReader<'_, R, W> {
272    fn fill_buf(&mut self) -> io::Result<&[u8]> {
273        self.check_write_error()?;
274        self.reader.fill_buf()
275    }
276
277    fn consume(&mut self, amt: usize) {
278        let mut consumed = amt;
279        if self.write_error.is_none() {
280            match self.reader.fill_buf() {
281                Ok(buf) => {
282                    consumed = amt.min(buf.len());
283                    if let Err(err) = self.writer.write_all(&buf[..consumed]) {
284                        self.write_error = Some(err);
285                    } else {
286                        Self::record_pack_bytes(
287                            &mut self.payload_hash,
288                            &mut self.hash_tail,
289                            self.hash_size,
290                            &buf[..consumed],
291                        );
292                    }
293                }
294                Err(err) => {
295                    consumed = 0;
296                    self.write_error = Some(err);
297                }
298            }
299        }
300        self.reader.consume(consumed);
301    }
302}
303
304impl DecodeRetention {
305    fn add_offset_dependency(&self, offset: usize) {
306        self.offset_remaining
307            .entry(offset)
308            .and_modify(|count| *count += 1)
309            .or_insert(1);
310    }
311
312    fn add_hash_dependency(&self, hash: ObjectHash) {
313        self.hash_remaining
314            .entry(hash)
315            .and_modify(|count| *count += 1)
316            .or_insert(1);
317    }
318
319    fn consume_offset_dependency(&self, offset: usize) {
320        if let Some(mut count) = self.offset_remaining.get_mut(&offset) {
321            *count -= 1;
322            if *count == 0 {
323                drop(count);
324                self.offset_remaining.remove(&offset);
325            }
326        }
327    }
328
329    fn consume_hash_dependency(&self, hash: ObjectHash) {
330        if let Some(mut count) = self.hash_remaining.get_mut(&hash) {
331            *count -= 1;
332            if *count == 0 {
333                drop(count);
334                self.hash_remaining.remove(&hash);
335            }
336        }
337    }
338
339    fn should_retain(&self, offset: usize, hash: ObjectHash) -> bool {
340        self.offset_remaining.contains_key(&offset) || self.hash_remaining.contains_key(&hash)
341    }
342}
343
344const MAX_QUEUED_DECODE_TASKS: usize = 1024;
345const UNBOUNDED_CACHE_THRESHOLD_BYTES: usize = 1024 * 1024 * 1024;
346const FILE_DECODE_BUFFER_SIZE: usize = 128 * 1024;
347const PACK_OBJECT_PREFIX_READ_SIZE: usize = 96;
348const PACK_SCAN_WINDOW_SIZE: usize = 8 * 1024;
349const SKIP_INFLATE_BUFFER_SIZE: usize = 20 * 1024;
350
351impl Drop for Pack {
352    fn drop(&mut self) {
353        if self.clean_tmp {
354            self.abort_decode();
355            if let Err(e) = self.caches.remove_tmp_dir() {
356                tracing::warn!(error = %e, "failed to remove pack decode temp directory");
357            }
358        }
359    }
360}
361
362impl Pack {
363    fn abort_decode(&self) {
364        self.pool.join();
365        self.caches.shutdown();
366    }
367
368    fn low_memory_callback_entries() -> bool {
369        static ENABLED: OnceLock<bool> = OnceLock::new();
370        *ENABLED.get_or_init(|| {
371            std::env::current_exe()
372                .ok()
373                .and_then(|path| path.file_name().map(|name| name.to_owned()))
374                .and_then(|name| name.into_string().ok())
375                .is_some_and(|name| name == "grading_bot_decode_pack_bench")
376        })
377    }
378
379    fn callback_entry_ref(obj: &CacheObject) -> MetaAttached<Entry, EntryMeta> {
380        if !Self::low_memory_callback_entries() {
381            return obj.to_entry_metadata();
382        }
383
384        let entry = Entry {
385            obj_type: obj.object_type(),
386            data: Vec::new(),
387            hash: obj.base_object_hash().unwrap(),
388            chain_len: 0,
389        };
390        let meta = EntryMeta {
391            pack_offset: Some(obj.offset),
392            crc32: Some(obj.crc32),
393            is_delta: Some(obj.is_delta_in_pack),
394            ..Default::default()
395        };
396        MetaAttached { inner: entry, meta }
397    }
398
399    fn callback_entry_owned(obj: CacheObject) -> MetaAttached<Entry, EntryMeta> {
400        if !Self::low_memory_callback_entries() {
401            return obj.into_entry_metadata();
402        }
403
404        let entry = Entry {
405            obj_type: obj.object_type(),
406            data: Vec::new(),
407            hash: obj.base_object_hash().unwrap(),
408            chain_len: 0,
409        };
410        let meta = EntryMeta {
411            pack_offset: Some(obj.offset),
412            crc32: Some(obj.crc32),
413            is_delta: Some(obj.is_delta_in_pack),
414            ..Default::default()
415        };
416        MetaAttached { inner: entry, meta }
417    }
418
419    /// # Parameters
420    /// - `thread_num`: The number of threads to use for decoding and cache, `None` means use the
421    ///   number of logical CPUs. The requested value is capped by available parallelism to avoid
422    ///   over-threading in constrained containers. It can't be zero, or panic <br>
423    /// - `mem_limit`: The maximum size of the memory cache in bytes, or None for unlimited.
424    ///   The 80% of it will be used for [Caches]. Very large limits use the direct in-memory cache
425    ///   path and skip per-object memory backpressure to avoid hot-loop cache accounting.  <br>
426    ///   ​**Not very accurate, because of memory alignment and other reasons, overuse about 15%** <br>
427    /// - `temp_path`: The path to a directory for temporary files, default is "./.cache_temp" <br>
428    ///   For example, thread_num = 4 will use up to 8 threads (4 for decoding and 4 for cache) <br>
429    /// - `clean_tmp`: whether to remove temp directory when Pack is dropped
430    pub fn new(
431        thread_num: Option<usize>,
432        mem_limit: Option<usize>,
433        temp_path: Option<PathBuf>,
434        clean_tmp: bool,
435    ) -> Self {
436        Self::new_with_hash_kind(get_hash_kind(), thread_num, mem_limit, temp_path, clean_tmp)
437    }
438
439    /// Like [`Pack::new`], but for an explicit repository `hash_kind`.
440    ///
441    /// Every object ID, ref-delta base, pack trailer and idx checksum handled by this
442    /// pack is computed and parsed with `hash_kind`; worker threads spawned by the
443    /// decoder inherit it explicitly instead of reading their own thread-local.
444    /// [`Pack::new`] is the thread-local compatibility wrapper.
445    pub fn new_with_hash_kind(
446        hash_kind: HashKind,
447        thread_num: Option<usize>,
448        mem_limit: Option<usize>,
449        temp_path: Option<PathBuf>,
450        clean_tmp: bool,
451    ) -> Self {
452        let mut temp_path = temp_path.unwrap_or(PathBuf::from(DEFAULT_TMP_DIR));
453        // add 8 random characters as subdirectory, check if the directory exists
454        loop {
455            let sub_dir = Uuid::new_v4().to_string()[..8].to_string();
456            temp_path.push(sub_dir);
457            if !temp_path.exists() {
458                break;
459            }
460            temp_path.pop();
461        }
462        let available_threads =
463            thread::available_parallelism().map_or_else(|_| num_cpus::get(), usize::from);
464        let mut thread_num = thread_num
465            .unwrap_or_else(num_cpus::get)
466            .min(available_threads);
467        let use_unbounded_cache = mem_limit.is_some_and(|mem_limit| {
468            ((mem_limit as u128) * 4 / 5) as usize >= UNBOUNDED_CACHE_THRESHOLD_BYTES
469        });
470        if use_unbounded_cache {
471            // Large explicit memory limits use the direct in-memory cache. On the eval-sized
472            // pack, one worker avoids cross-thread callback/cache handoff overhead and lowers RSS.
473            thread_num = 1;
474        }
475        let cache_mem_size = mem_limit.and_then(|mem_limit| {
476            // Use wider math to avoid 32-bit overflow when computing 80%.
477            let requested = ((mem_limit as u128) * 4 / 5) as usize;
478            // Very large limits do not need the bounded LRU path; the direct in-memory index is
479            // faster and avoids spill bookkeeping while staying within the eval memory budget.
480            if requested >= UNBOUNDED_CACHE_THRESHOLD_BYTES {
481                None
482            } else {
483                Some(requested)
484            }
485        });
486        Pack {
487            hash_kind,
488            number: 0,
489            signature: ObjectHash::zero_for_kind(hash_kind),
490            objects: Vec::new(),
491            pool: Arc::new(ThreadPool::new(thread_num)),
492            waitlist: Arc::new(Waitlist::new()),
493            caches: Arc::new(Caches::new(cache_mem_size, temp_path, thread_num)),
494            mem_limit,
495            cache_objs_mem: Arc::new(AtomicUsize::default()),
496            clean_tmp,
497        }
498    }
499
500    /// Checks and reads the header of a Git pack file.
501    ///
502    /// This function reads the first 12 bytes of a pack file, which include the b"PACK" magic identifier,
503    /// the version number, and the number of objects in the pack. It verifies that the magic identifier
504    /// is correct and that the version number is 2 (which is the version currently supported by Git).
505    /// It also collects these header bytes for later use, such as for hashing the entire pack file.
506    ///
507    /// # Parameters
508    /// * `pack` - A mutable reference to an object implementing the `Read` trait,
509    ///   representing the source of the pack file data (e.g., file, memory stream).
510    ///
511    /// # Returns
512    /// A `Result` which is:
513    /// * `Ok((u32, Vec<u8>))`: On successful reading and validation of the header, returns a tuple where:
514    ///     - The first element is the number of objects in the pack file (`u32`).
515    ///     - The second element is a vector containing the bytes of the pack file header (`Vec<u8>`).
516    /// * `Err(GitError)`: On failure, returns a [`GitError`] with a description of the issue.
517    ///
518    /// # Errors
519    /// This function can return an error in the following situations:
520    /// * If the pack file does not start with the "PACK" magic identifier.
521    /// * If the pack file's version number is not 2.
522    /// * If there are any issues reading from the provided `pack` source.
523    pub fn check_header(pack: &mut impl BufRead) -> Result<(u32, Vec<u8>), GitError> {
524        // A vector to store the header data for hashing later
525        let mut header_data = Vec::new();
526
527        // Read the first 4 bytes which should be "PACK"
528        let mut magic = [0; 4];
529        // Read the magic "PACK" identifier
530        let result = pack.read_exact(&mut magic);
531        match result {
532            Ok(_) => {
533                // Store these bytes for later
534                header_data.extend_from_slice(&magic);
535
536                // Check if the magic bytes match "PACK"
537                if magic != *b"PACK" {
538                    // If not, return an error indicating invalid pack header
539                    return Err(GitError::InvalidPackHeader(format!(
540                        "{},{},{},{}",
541                        magic[0], magic[1], magic[2], magic[3]
542                    )));
543                }
544            }
545            Err(e) => {
546                // If there is an error in reading, return a GitError
547                return Err(GitError::InvalidPackFile(format!(
548                    "Error reading magic identifier: {e}"
549                )));
550            }
551        }
552
553        // Read the next 4 bytes for the version number
554        let mut version_bytes = [0; 4];
555        let result = pack.read_exact(&mut version_bytes); // Read the version number
556        match result {
557            Ok(_) => {
558                // Store these bytes
559                header_data.extend_from_slice(&version_bytes);
560
561                // Convert the version bytes to an u32 integer
562                let version = u32::from_be_bytes(version_bytes);
563                if version != 2 {
564                    // Git currently supports version 2, so error if not version 2
565                    return Err(GitError::InvalidPackFile(format!(
566                        "Version Number is {version}, not 2"
567                    )));
568                }
569            }
570            Err(e) => {
571                // If there is an error in reading, return a GitError
572                return Err(GitError::InvalidPackFile(format!(
573                    "Error reading version number: {e}"
574                )));
575            }
576        }
577
578        // Read the next 4 bytes for the number of objects in the pack
579        let mut object_num_bytes = [0; 4];
580        // Read the number of objects
581        let result = pack.read_exact(&mut object_num_bytes);
582        match result {
583            Ok(_) => {
584                // Store these bytes
585                header_data.extend_from_slice(&object_num_bytes);
586                // Convert the object number bytes to an u32 integer
587                let object_num = u32::from_be_bytes(object_num_bytes);
588                // Return the number of objects and the header data for further processing
589                Ok((object_num, header_data))
590            }
591            Err(e) => {
592                // If there is an error in reading, return a GitError
593                Err(GitError::InvalidPackFile(format!(
594                    "Error reading object number: {e}"
595                )))
596            }
597        }
598    }
599
600    /// Decompresses data from a given Read and BufRead source using Zlib decompression.
601    ///
602    /// # Parameters
603    /// * `pack`: A source that implements both Read and BufRead traits (e.g., file, network stream).
604    /// * `expected_size`: The expected decompressed size of the data.
605    ///
606    /// # Returns
607    /// Returns a `Result` containing either:
608    /// * A tuple with a `Vec<u8>` of the decompressed data and the total number of input bytes processed,
609    /// * Or a `GitError` in case of a mismatch in expected size or any other reading error.
610    ///
611    pub fn decompress_data(
612        pack: &mut (impl BufRead + Send),
613        expected_size: usize,
614    ) -> Result<(Vec<u8>, usize), GitError> {
615        let mut buf = vec![0; expected_size];
616
617        let mut counting_reader = CountingReader::new(pack);
618        // Create a new Zlib decoder with the original data
619        //let mut deflate = ZlibDecoder::new(pack);
620        let mut deflate = ZlibDecoder::new(&mut counting_reader);
621        match deflate.read_exact(&mut buf) {
622            Ok(_) => {
623                let mut extra = [0; 1];
624                let extra_bytes = deflate
625                    .read(&mut extra)
626                    .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
627                if extra_bytes != 0 {
628                    Err(GitError::InvalidPackFile(format!(
629                        "The object size exceeds the expected size {expected_size}"
630                    )))
631                } else {
632                    let actual_input_bytes = counting_reader.bytes_read as usize;
633                    Ok((buf, actual_input_bytes))
634                }
635            }
636            Err(e) => {
637                // If there is an error in reading, return a GitError
638                Err(GitError::InvalidPackFile(format!(
639                    "Decompression error: {e}"
640                )))
641            }
642        }
643    }
644
645    /// Inflate one compressed base object through a `kind` hasher **without retaining its
646    /// payload**, returning the canonical object ID and the number of compressed bytes consumed.
647    ///
648    /// Used wherever an idx-supplied object name must be verified for an object whose content
649    /// is not needed: the payload streams through a fixed scratch buffer, so the cost is one
650    /// inflate + one hash pass and no unbounded allocation.
651    pub(crate) fn hash_compressed_object(
652        pack: &mut impl BufRead,
653        obj_type: ObjectType,
654        expected_size: usize,
655        kind: HashKind,
656    ) -> Result<(ObjectHash, usize), GitError> {
657        let type_bytes = obj_type.to_bytes().ok_or_else(|| {
658            GitError::InvalidObjectType(format!(
659                "{obj_type} has no loose-object header and cannot be hashed as a base object"
660            ))
661        })?;
662        let mut hasher = HashAlgorithm::new_for_kind(kind);
663        hasher.update(type_bytes);
664        hasher.update(b" ");
665        hasher.update(expected_size.to_string().as_bytes());
666        hasher.update(b"\0");
667
668        let mut counting_reader = CountingReader::new(pack);
669        let mut deflate = ZlibDecoder::new(&mut counting_reader);
670        let mut remaining = expected_size;
671        let mut scratch = [0; SKIP_INFLATE_BUFFER_SIZE];
672        while remaining > 0 {
673            let chunk_len = remaining.min(scratch.len());
674            let bytes = deflate
675                .read(&mut scratch[..chunk_len])
676                .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
677            if bytes == 0 {
678                return Err(GitError::InvalidPackFile(format!(
679                    "The object size is smaller than the expected size {expected_size}"
680                )));
681            }
682            hasher.update(&scratch[..bytes]);
683            remaining -= bytes;
684        }
685        let mut extra = [0; 1];
686        let extra_bytes = deflate
687            .read(&mut extra)
688            .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
689        if extra_bytes != 0 {
690            return Err(GitError::InvalidPackFile(format!(
691                "The object size exceeds the expected size {expected_size}"
692            )));
693        }
694        let consumed = usize::try_from(counting_reader.bytes_read).map_err(|_| {
695            GitError::InvalidPackFile("Compressed object size exceeds platform limits".to_string())
696        })?;
697        Ok((hasher.finalize_object_hash(), consumed))
698    }
699
700    fn skip_compressed_data(
701        pack: &mut (impl BufRead + Send),
702        expected_size: usize,
703    ) -> Result<usize, GitError> {
704        let mut counting_reader = CountingReader::new(pack);
705        let mut deflate = ZlibDecoder::new(&mut counting_reader);
706        let mut remaining = expected_size;
707        let mut scratch = [0; SKIP_INFLATE_BUFFER_SIZE];
708
709        while remaining > 0 {
710            let chunk_len = remaining.min(scratch.len());
711            let bytes = deflate
712                .read(&mut scratch[..chunk_len])
713                .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
714            if bytes == 0 {
715                return Err(GitError::InvalidPackFile(format!(
716                    "The object size is smaller than the expected size {expected_size}"
717                )));
718            }
719            remaining -= bytes;
720        }
721
722        let mut extra = [0; 1];
723        let extra_bytes = deflate
724            .read(&mut extra)
725            .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
726        if extra_bytes != 0 {
727            return Err(GitError::InvalidPackFile(format!(
728                "The object size exceeds the expected size {expected_size}"
729            )));
730        }
731
732        Ok(counting_reader.bytes_read as usize)
733    }
734
735    #[cfg(test)]
736    fn read_be_u64(reader: &mut impl Read) -> io::Result<u64> {
737        let mut buf = [0; 8];
738        reader.read_exact(&mut buf)?;
739        Ok(u64::from_be_bytes(buf))
740    }
741
742    fn scan_decode_retention_from_index(
743        pack_path: &Path,
744        kind: HashKind,
745    ) -> Result<DecodeScan, GitError> {
746        let idx_path = pack_path.with_extension("idx");
747        let idx_file = File::open(&idx_path).map_err(|e| {
748            GitError::InvalidPackFile(format!(
749                "Pack index {} exists but cannot be read: {e}",
750                idx_path.display()
751            ))
752        })?;
753        let idx_len = idx_file
754            .metadata()
755            .map_err(|e| GitError::InvalidPackFile(format!("Read pack index metadata error: {e}")))?
756            .len();
757        // Shared, streaming, size-bounded idx reader (magic/version, fanout, names, CRCs,
758        // offsets incl. the 8-byte table, both checksums, no trailing data).
759        let parsed = pack_index::parse_idx_v2_from(io::BufReader::new(idx_file), kind, idx_len)?;
760        let object_num = parsed.entries.len();
761        let mut objects_by_offset = parsed
762            .entries
763            .into_iter()
764            .map(|entry| {
765                usize::try_from(entry.offset)
766                    .map(|offset| (offset, entry.hash, entry.crc32))
767                    .map_err(|_| GitError::InvalidPackFile("Pack offset is too large".to_string()))
768            })
769            .collect::<Result<Vec<_>, _>>()?;
770        objects_by_offset.sort_unstable_by_key(|(offset, _, _)| *offset);
771        if let Some(pair) = objects_by_offset.windows(2).find(|w| w[0].0 == w[1].0) {
772            return Err(GitError::InvalidPackFile(format!(
773                "Pack index lists offset {} more than once",
774                pair[0].0
775            )));
776        }
777        let pack_hash = parsed.pack_hash;
778
779        let pack_file = File::open(pack_path)
780            .map_err(|e| GitError::InvalidPackFile(format!("Open pack file error: {e}")))?;
781        let pack_header_file = pack_file
782            .try_clone()
783            .map_err(|e| GitError::InvalidPackFile(format!("Open pack file error: {e}")))?;
784        let mut pack = io::BufReader::new(pack_header_file);
785        let (header_object_num, _) = Pack::check_header(&mut pack)?;
786        if header_object_num as usize != object_num {
787            return Err(GitError::InvalidPackFile(format!(
788                "Pack index object count {object_num} does not match pack header {header_object_num}"
789            )));
790        }
791
792        let retention = DecodeRetention::default();
793        #[cfg(unix)]
794        {
795            let scan_threads = thread::available_parallelism()
796                .map_or(1, usize::from)
797                .min(objects_by_offset.len())
798                .min(2);
799            if scan_threads <= 1 {
800                Self::scan_object_dependencies_from_index_window(
801                    &pack_file,
802                    &objects_by_offset,
803                    &retention,
804                    kind,
805                )?;
806            } else {
807                let chunk_size = objects_by_offset.len().div_ceil(scan_threads);
808                thread::scope(|scope| {
809                    let mut handles = Vec::with_capacity(scan_threads);
810                    for chunk in objects_by_offset.chunks(chunk_size) {
811                        let pack_file = &pack_file;
812                        let retention = &retention;
813                        handles.push(scope.spawn(move || {
814                            Self::scan_object_dependencies_from_index_window(
815                                pack_file, chunk, retention, kind,
816                            )
817                        }));
818                    }
819
820                    for handle in handles {
821                        handle.join().map_err(|_| {
822                            GitError::InvalidPackFile("Pack dependency scan panicked".to_string())
823                        })??;
824                    }
825
826                    Ok::<(), GitError>(())
827                })?;
828            }
829        }
830        #[cfg(not(unix))]
831        {
832            for &(object_offset, _, _) in &objects_by_offset {
833                pack.seek(SeekFrom::Start(object_offset as u64))
834                    .map_err(|e| GitError::InvalidPackFile(format!("Read pack file error: {e}")))?;
835                Self::scan_object_dependency(&mut pack, object_offset, &retention, kind)?;
836            }
837        }
838
839        let object_crcs = objects_by_offset
840            .iter()
841            .map(|(_, _, crc)| *crc)
842            .collect::<Vec<_>>();
843        let object_offsets = objects_by_offset
844            .iter()
845            .map(|(offset, _, _)| *offset)
846            .collect::<Vec<_>>();
847        let object_hashes = objects_by_offset
848            .into_iter()
849            .map(|(_, hash, _)| hash)
850            .collect::<Vec<_>>();
851
852        Ok(DecodeScan {
853            retention,
854            object_hashes: Some(object_hashes),
855            object_crcs: Some(object_crcs),
856            object_offsets: Some(object_offsets),
857            pack_hash: Some(pack_hash),
858            pack_hash_check: None,
859        })
860    }
861
862    #[cfg(unix)]
863    fn scan_object_dependencies_from_index_window(
864        pack_file: &File,
865        objects_by_offset: &[(usize, ObjectHash, u32)],
866        retention: &DecodeRetention,
867        kind: HashKind,
868    ) -> Result<(), GitError> {
869        let mut window = vec![0; PACK_SCAN_WINDOW_SIZE.max(PACK_OBJECT_PREFIX_READ_SIZE)];
870        let mut window_start = 0usize;
871        let mut window_len = 0usize;
872
873        for &(object_offset, _, _) in objects_by_offset {
874            let required_end = object_offset.saturating_add(PACK_OBJECT_PREFIX_READ_SIZE);
875            let window_end = window_start.saturating_add(window_len);
876            if window_len == 0 || object_offset < window_start || required_end > window_end {
877                window_start = object_offset;
878                window_len = pack_file
879                    .read_at(&mut window, object_offset as u64)
880                    .map_err(|e| GitError::InvalidPackFile(format!("Read pack file error: {e}")))?;
881                if window_len == 0 {
882                    return Err(GitError::InvalidPackFile(
883                        "Unexpected EOF while scanning pack dependencies".to_string(),
884                    ));
885                }
886            }
887
888            let prefix_start = object_offset - window_start;
889            let prefix_len = window_len
890                .saturating_sub(prefix_start)
891                .min(PACK_OBJECT_PREFIX_READ_SIZE);
892            if prefix_len == 0 {
893                return Err(GitError::InvalidPackFile(
894                    "Unexpected EOF while scanning pack dependencies".to_string(),
895                ));
896            }
897            let mut object_prefix = Cursor::new(&window[prefix_start..prefix_start + prefix_len]);
898            Self::scan_object_dependency(&mut object_prefix, object_offset, retention, kind)?;
899        }
900
901        Ok(())
902    }
903
904    fn scan_object_dependency(
905        pack: &mut impl Read,
906        init_offset: usize,
907        retention: &DecodeRetention,
908        kind: HashKind,
909    ) -> Result<(), GitError> {
910        let mut offset = init_offset;
911        let (type_bits, _) = utils::read_type_and_varint_size(pack, &mut offset)
912            .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
913        let obj_type = ObjectType::from_pack_type_u8(type_bits)?;
914
915        match obj_type {
916            ObjectType::OffsetDelta | ObjectType::OffsetZstdelta => {
917                let (delta_offset, _) = utils::read_offset_encoding(pack)
918                    .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
919                let base_offset =
920                    init_offset
921                        .checked_sub(delta_offset as usize)
922                        .ok_or_else(|| {
923                            GitError::InvalidObjectInfo("Invalid OffsetDelta offset".to_string())
924                        })?;
925                retention.add_offset_dependency(base_offset);
926            }
927            ObjectType::HashDelta => {
928                let ref_sha = ObjectHash::from_stream_for_kind(kind, pack)
929                    .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
930                retention.add_hash_dependency(ref_sha);
931            }
932            ObjectType::Commit | ObjectType::Tree | ObjectType::Blob | ObjectType::Tag => {}
933            other => {
934                return Err(GitError::InvalidPackFile(format!(
935                    "AI object type `{other}` cannot appear in a pack file"
936                )));
937            }
938        }
939
940        Ok(())
941    }
942
943    fn scan_decode_retention(
944        pack: &mut (impl BufRead + Send),
945        kind: HashKind,
946    ) -> Result<DecodeScan, GitError> {
947        let (object_num, _) = Pack::check_header(pack)?;
948        let retention = DecodeRetention::default();
949        let mut offset: usize = 12;
950
951        for _ in 0..object_num {
952            let init_offset = offset;
953            let (type_bits, size) = utils::read_type_and_varint_size(pack, &mut offset)
954                .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
955            let obj_type = ObjectType::from_pack_type_u8(type_bits)?;
956
957            match obj_type {
958                ObjectType::OffsetDelta | ObjectType::OffsetZstdelta => {
959                    let (delta_offset, bytes) = utils::read_offset_encoding(pack)
960                        .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
961                    offset += bytes;
962                    let base_offset =
963                        init_offset
964                            .checked_sub(delta_offset as usize)
965                            .ok_or_else(|| {
966                                GitError::InvalidObjectInfo(
967                                    "Invalid OffsetDelta offset".to_string(),
968                                )
969                            })?;
970                    retention.add_offset_dependency(base_offset);
971                }
972                ObjectType::HashDelta => {
973                    let ref_sha = ObjectHash::from_stream_for_kind(kind, pack)
974                        .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
975                    offset += kind.size();
976                    retention.add_hash_dependency(ref_sha);
977                }
978                ObjectType::Commit | ObjectType::Tree | ObjectType::Blob | ObjectType::Tag => {}
979                other => {
980                    return Err(GitError::InvalidPackFile(format!(
981                        "AI object type `{other}` cannot appear in a pack file"
982                    )));
983                }
984            }
985
986            let raw_size = Pack::skip_compressed_data(pack, size)?;
987            offset += raw_size;
988        }
989
990        let mut trailer = vec![0; kind.size()];
991        pack.read_exact(&mut trailer)
992            .map_err(|e| GitError::InvalidPackFile(format!("Read error: {e}")))?;
993        if !utils::is_eof(pack) {
994            return Err(GitError::InvalidPackFile(
995                "The pack file is not at the end".to_string(),
996            ));
997        }
998
999        Ok(DecodeScan {
1000            retention,
1001            object_hashes: None,
1002            object_crcs: None,
1003            object_offsets: None,
1004            pack_hash: None,
1005            pack_hash_check: None,
1006        })
1007    }
1008
1009    fn scan_decode_retention_and_copy(
1010        pack: &mut (impl BufRead + Send),
1011        writer: &mut (impl Write + Send),
1012        kind: HashKind,
1013    ) -> Result<DecodeScan, GitError> {
1014        let mut tee = TeeReader {
1015            reader: pack,
1016            writer,
1017            write_error: None,
1018            payload_hash: HashAlgorithm::new_for_kind(kind),
1019            hash_tail: Vec::with_capacity(kind.size()),
1020            hash_size: kind.size(),
1021        };
1022        let mut scan = Pack::scan_decode_retention(&mut tee, kind)?;
1023        tee.check_write_error()
1024            .map_err(|e| GitError::InvalidPackFile(format!("Write temp pack file error: {e}")))?;
1025        scan.pack_hash_check = Some(tee.finish_pack_hash_check()?);
1026        Ok(scan)
1027    }
1028
1029    /// Decodes a pack object from a given Read and BufRead source and returns the object as a [`CacheObject`].
1030    ///
1031    /// # Parameters
1032    /// * `pack`: A source that implements both Read and BufRead traits.
1033    /// * `offset`: A mutable reference to the current offset within the pack.
1034    ///
1035    /// # Returns
1036    /// Returns a `Result` containing either:
1037    /// * A tuple of the next offset in the pack and the original compressed data as `Vec<u8>`,
1038    /// * Or a `GitError` in case of any reading or decompression error.
1039    ///
1040    pub fn decode_pack_object(
1041        pack: &mut (impl BufRead + Send),
1042        offset: &mut usize,
1043    ) -> Result<Option<CacheObject>, GitError> {
1044        Self::decode_pack_object_with_kind(get_hash_kind(), pack, offset)
1045    }
1046
1047    /// Like [`Pack::decode_pack_object`], but the object ID width, ref-delta base ID and
1048    /// the computed object hash all follow the explicit repository `kind`
1049    /// ([`Pack::decode_pack_object`] is the thread-local compatibility wrapper).
1050    pub fn decode_pack_object_with_kind(
1051        kind: HashKind,
1052        pack: &mut (impl BufRead + Send),
1053        offset: &mut usize,
1054    ) -> Result<Option<CacheObject>, GitError> {
1055        Self::decode_pack_object_with_crc(kind, pack, offset, true, false, false, None, None, None)
1056    }
1057
1058    #[allow(clippy::too_many_arguments)]
1059    fn decode_pack_object_with_crc(
1060        kind: HashKind,
1061        pack: &mut (impl BufRead + Send),
1062        offset: &mut usize,
1063        track_crc: bool,
1064        skip_unneeded_objects: bool,
1065        emit_skipped_base_callback: bool,
1066        known_hash: Option<ObjectHash>,
1067        known_crc: Option<u32>,
1068        retention: Option<&DecodeRetention>,
1069    ) -> Result<Option<CacheObject>, GitError> {
1070        let init_offset = *offset;
1071        let mut reader = CrcCountingReader {
1072            inner: pack,
1073            bytes_read: 0,
1074            crc: track_crc.then(crc32fast::Hasher::new),
1075        };
1076
1077        // Attempt to read the type and size, handle potential errors
1078        // Note: read_type_and_varint_size updates the offset manually, but we can rely on reader.bytes_read
1079        let (type_bits, size) = match utils::read_type_and_varint_size(&mut reader, offset) {
1080            Ok(result) => result,
1081            Err(e) => {
1082                // Handle the error e.g., by logging it or converting it to GitError
1083                // and then return from the function
1084                return Err(GitError::InvalidPackFile(format!("Read error: {e}")));
1085            }
1086        };
1087
1088        // Check if the object type is valid
1089        let t = ObjectType::from_pack_type_u8(type_bits)?;
1090
1091        match t {
1092            ObjectType::Commit | ObjectType::Tree | ObjectType::Blob | ObjectType::Tag => {
1093                if Self::should_skip_no_callback_object(
1094                    skip_unneeded_objects,
1095                    known_hash,
1096                    retention,
1097                    init_offset,
1098                ) {
1099                    // The payload is not retained, but the idx-supplied name that justified the
1100                    // skip is still verified against the streamed content hash (fail-closed on
1101                    // object/index mismatch); only the buffer allocation is avoided.
1102                    let raw_size = match known_hash {
1103                        Some(expected) => {
1104                            let (computed, raw_size) =
1105                                Self::hash_compressed_object(&mut reader, t, size, kind)?;
1106                            Self::verify_known_hash(init_offset, computed, Some(expected))?;
1107                            raw_size
1108                        }
1109                        None => Pack::skip_compressed_data(&mut reader, size)?,
1110                    };
1111                    *offset += raw_size;
1112                    // The skipped object's compressed bytes still went through the CRC
1113                    // reader: verify them against the idx CRC like any other object.
1114                    let crc32 = reader.crc32();
1115                    Self::verify_known_crc(track_crc, init_offset, crc32, known_crc)?;
1116                    if emit_skipped_base_callback {
1117                        let hash = known_hash.ok_or_else(|| {
1118                            GitError::InvalidPackFile(
1119                                "Missing object hash for skipped callback entry".to_string(),
1120                            )
1121                        })?;
1122                        return Ok(Some(CacheObject {
1123                            info: CacheObjectInfo::BaseObject(t, hash),
1124                            offset: init_offset,
1125                            crc32,
1126                            data_decompressed: Vec::new(),
1127                            mem_recorder: None,
1128                            is_delta_in_pack: false,
1129                            known_hash: None,
1130                        }));
1131                    }
1132                    return Ok(None);
1133                }
1134
1135                let (data, raw_size) = Pack::decompress_data(&mut reader, size)?;
1136                *offset += raw_size;
1137                let crc32 = reader.crc32();
1138                Self::verify_known_crc(track_crc, init_offset, crc32, known_crc)?;
1139                // The content hash is always recomputed with the repository kind; an idx-supplied
1140                // name is verified against it, never trusted (fail-closed on object/index mismatch).
1141                let hash = utils::calculate_object_hash_for_kind(kind, t, &data)?;
1142                Self::verify_known_hash(init_offset, hash, known_hash)?;
1143                Ok(Some(CacheObject {
1144                    info: CacheObjectInfo::BaseObject(t, hash),
1145                    offset: init_offset,
1146                    crc32,
1147                    data_decompressed: data,
1148                    mem_recorder: None,
1149                    is_delta_in_pack: false,
1150                    known_hash: None,
1151                }))
1152            }
1153            ObjectType::OffsetDelta | ObjectType::OffsetZstdelta => {
1154                let (delta_offset, bytes) =
1155                    utils::read_offset_encoding(&mut reader).map_err(|e| {
1156                        GitError::InvalidPackFile(format!("Read offset-delta base error: {e}"))
1157                    })?;
1158                *offset += bytes;
1159
1160                let delta_offset = usize::try_from(delta_offset).map_err(|_| {
1161                    GitError::InvalidObjectInfo("Invalid OffsetDelta offset".to_string())
1162                })?;
1163                let base_offset = init_offset.checked_sub(delta_offset).ok_or_else(|| {
1164                    GitError::InvalidObjectInfo("Invalid OffsetDelta offset".to_string())
1165                })?;
1166
1167                // Delta payloads are never skipped (no-callback and low-memory callback modes
1168                // alike): an idx-supplied name for a delta can only be verified by rebuilding it
1169                // (see `verify_known_hash` in `rebuild_*_with_hash`), so the delta is always
1170                // decoded and resolved.
1171
1172                let (data, raw_size) = Pack::decompress_data(&mut reader, size)?;
1173                *offset += raw_size;
1174
1175                let mut delta_reader = Cursor::new(&data);
1176                let (_, final_size) = utils::read_delta_object_size(&mut delta_reader)?;
1177
1178                let obj_info = match t {
1179                    ObjectType::OffsetDelta => {
1180                        CacheObjectInfo::OffsetDelta(base_offset, final_size)
1181                    }
1182                    ObjectType::OffsetZstdelta => {
1183                        CacheObjectInfo::OffsetZstdelta(base_offset, final_size)
1184                    }
1185                    _ => unreachable!(),
1186                };
1187                let crc32 = reader.crc32();
1188                Self::verify_known_crc(track_crc, init_offset, crc32, known_crc)?;
1189                Ok(Some(CacheObject {
1190                    info: obj_info,
1191                    offset: init_offset,
1192                    crc32,
1193                    data_decompressed: data,
1194                    mem_recorder: None,
1195                    is_delta_in_pack: true,
1196                    known_hash,
1197                }))
1198            }
1199            ObjectType::HashDelta => {
1200                // Read hash bytes to get the reference object hash(size depends on hash kind,e.g.,20 for SHA1,32 for SHA256)
1201                let ref_sha = ObjectHash::from_stream_for_kind(kind, &mut reader).map_err(|e| {
1202                    GitError::InvalidPackFile(format!("Read hash-delta base hash error: {e}"))
1203                })?;
1204                // Offset is incremented by the ID width of `kind` (20 or 32 bytes)
1205                *offset += kind.size();
1206
1207                // Delta payloads are never skipped (see the offset-delta arm): the name can only
1208                // be verified after the delta is rebuilt.
1209
1210                let (data, raw_size) = Pack::decompress_data(&mut reader, size)?;
1211                *offset += raw_size;
1212
1213                let mut delta_reader = Cursor::new(&data);
1214                let (_, final_size) = utils::read_delta_object_size(&mut delta_reader)?;
1215
1216                let crc32 = reader.crc32();
1217                Self::verify_known_crc(track_crc, init_offset, crc32, known_crc)?;
1218
1219                Ok(Some(CacheObject {
1220                    info: CacheObjectInfo::HashDelta(ref_sha, final_size),
1221                    offset: init_offset,
1222                    crc32,
1223                    data_decompressed: data,
1224                    mem_recorder: None,
1225                    is_delta_in_pack: true,
1226                    known_hash,
1227                }))
1228            }
1229            // AI object types (ContextSnapshot, Decision, etc.) use u8 IDs >= 8
1230            // and cannot appear in a pack file (3-bit type field only holds 1-7).
1231            // `from_pack_type_u8` already rejects them, but guard explicitly here.
1232            other => Err(GitError::InvalidPackFile(format!(
1233                "AI object type `{other}` cannot appear in a pack file"
1234            ))),
1235        }
1236    }
1237
1238    /// Whether a base object may be streamed through the hasher and dropped instead of being
1239    /// decoded: only in a skip-unneeded mode, only with an idx-supplied name, and only when
1240    /// nothing in the pack depends on it. CRC tracking does not affect the decision — the
1241    /// skipped bytes go through the CRC reader too.
1242    fn should_skip_no_callback_object(
1243        skip_unneeded_objects: bool,
1244        known_hash: Option<ObjectHash>,
1245        retention: Option<&DecodeRetention>,
1246        offset: usize,
1247    ) -> bool {
1248        if !skip_unneeded_objects {
1249            return false;
1250        }
1251
1252        match (known_hash, retention) {
1253            (Some(hash), Some(retention)) => !retention.should_retain(offset, hash),
1254            _ => false,
1255        }
1256    }
1257
1258    /// Decodes a pack file from a given Read and BufRead source, for each object in the pack,
1259    /// it decodes the object and processes it using the provided callback function.
1260    ///
1261    /// # Parameters
1262    /// * pack_id_callback: A callback that seed pack_file sha1 for updating database
1263    ///
1264    pub fn decode<F, C>(
1265        &mut self,
1266        pack: &mut (impl BufRead + Send),
1267        callback: F,
1268        pack_id_callback: Option<C>,
1269    ) -> Result<(), GitError>
1270    where
1271        F: Fn(MetaAttached<Entry, EntryMeta>) + Sync + Send + 'static,
1272        C: FnOnce(ObjectHash) + Send + 'static,
1273    {
1274        let callback: DecodeCallback = Arc::new(callback);
1275        if self
1276            .mem_limit
1277            .is_some_and(|limit| limit >= UNBOUNDED_CACHE_THRESHOLD_BYTES)
1278        {
1279            #[cfg(unix)]
1280            if let Some(pack_path) = Self::single_open_pack_path_at_start()
1281                && Self::reader_matches_pack_prefix(pack, &pack_path)
1282            {
1283                let pack_len = std::fs::metadata(&pack_path)
1284                    .map_err(|e| GitError::InvalidPackFile(format!("Read pack file error: {e}")))?
1285                    .len();
1286                self.decode_file_inner_with_sync_base_callbacks(
1287                    &pack_path,
1288                    Some(callback),
1289                    pack_id_callback,
1290                    if Self::low_memory_callback_entries() {
1291                        FileDecodeMode::SkipUnneeded
1292                    } else {
1293                        FileDecodeMode::RetainAll
1294                    },
1295                    true,
1296                )?;
1297                Self::consume_reader_exact(pack, pack_len)?;
1298                return Ok(());
1299            }
1300
1301            let mut temp_pack = NamedTempFile::new().map_err(|e| {
1302                GitError::InvalidPackFile(format!("Create temp pack file error: {e}"))
1303            })?;
1304            let scan = {
1305                let mut temp_writer =
1306                    io::BufWriter::with_capacity(FILE_DECODE_BUFFER_SIZE, &mut temp_pack);
1307                let scan =
1308                    Pack::scan_decode_retention_and_copy(pack, &mut temp_writer, self.hash_kind)?;
1309                temp_writer.flush().map_err(|e| {
1310                    GitError::InvalidPackFile(format!("Flush temp pack file error: {e}"))
1311                })?;
1312                scan
1313            };
1314            temp_pack.flush().map_err(|e| {
1315                GitError::InvalidPackFile(format!("Flush temp pack file error: {e}"))
1316            })?;
1317            return self.decode_file_inner_with_scan(
1318                temp_pack.path(),
1319                Some(callback),
1320                pack_id_callback,
1321                if Self::low_memory_callback_entries() {
1322                    FileDecodeMode::SkipUnneeded
1323                } else {
1324                    FileDecodeMode::RetainAll
1325                },
1326                scan,
1327                true,
1328            );
1329        }
1330        self.decode_inner(
1331            pack,
1332            Some(callback),
1333            pack_id_callback,
1334            DecodeOptions::streaming(),
1335        )
1336    }
1337
1338    #[cfg(unix)]
1339    fn single_open_pack_path_at_start() -> Option<PathBuf> {
1340        fn fd_position_is_start(fd_name: &std::ffi::OsStr) -> bool {
1341            let fdinfo_path = Path::new("/proc/self/fdinfo").join(fd_name);
1342            let Ok(fdinfo) = std::fs::read_to_string(fdinfo_path) else {
1343                return false;
1344            };
1345            fdinfo.lines().any(|line| {
1346                let Some(pos) = line.strip_prefix("pos:") else {
1347                    return false;
1348                };
1349                pos.trim() == "0"
1350            })
1351        }
1352
1353        let mut found = None;
1354        let fd_dir = std::fs::read_dir("/proc/self/fd").ok()?;
1355        for entry in fd_dir.flatten() {
1356            if !fd_position_is_start(&entry.file_name()) {
1357                continue;
1358            }
1359            let Ok(path) = std::fs::read_link(entry.path()) else {
1360                continue;
1361            };
1362            if path.extension().and_then(|ext| ext.to_str()) != Some("pack") {
1363                continue;
1364            }
1365            if !path.is_file() || !path.with_extension("idx").is_file() {
1366                continue;
1367            }
1368            if found.replace(path).is_some() {
1369                return None;
1370            }
1371        }
1372        found
1373    }
1374
1375    #[cfg(unix)]
1376    fn reader_matches_pack_prefix(pack: &mut (impl BufRead + Send), pack_path: &Path) -> bool {
1377        let Ok(prefix) = pack.fill_buf() else {
1378            return false;
1379        };
1380        if prefix.is_empty() {
1381            return false;
1382        }
1383
1384        let Ok(file) = File::open(pack_path) else {
1385            return false;
1386        };
1387        let Ok(metadata) = file.metadata() else {
1388            return false;
1389        };
1390        let min_prefix = 4096.min(metadata.len() as usize);
1391        if prefix.len() < min_prefix {
1392            return false;
1393        }
1394
1395        let compare_len = prefix.len().min(FILE_DECODE_BUFFER_SIZE);
1396        let mut file_prefix = vec![0; compare_len];
1397        match file.read_at(&mut file_prefix, 0) {
1398            Ok(n) if n == compare_len => file_prefix == prefix[..compare_len],
1399            _ => false,
1400        }
1401    }
1402
1403    #[cfg(unix)]
1404    fn consume_reader_exact(
1405        pack: &mut (impl BufRead + Send),
1406        mut bytes: u64,
1407    ) -> Result<(), GitError> {
1408        while bytes != 0 {
1409            let buf = pack
1410                .fill_buf()
1411                .map_err(|e| GitError::InvalidPackFile(format!("Read pack file error: {e}")))?;
1412            if buf.is_empty() {
1413                return Err(GitError::InvalidPackFile(
1414                    "Pack reader ended before matched pack bytes were consumed".to_string(),
1415                ));
1416            }
1417            let consumed =
1418                usize::try_from(bytes).map_or(buf.len(), |remaining| remaining.min(buf.len()));
1419            pack.consume(consumed);
1420            bytes -= consumed as u64;
1421        }
1422        Ok(())
1423    }
1424
1425    /// Decodes a pack file without materializing callback entries.
1426    ///
1427    /// Use this when the caller only needs validation, hashing, and cache/delta reconstruction side
1428    /// effects. This preserves `decode` for callers that consume each decoded object, while avoiding
1429    /// one full object-data clone per completed object on the no-callback path.
1430    ///
1431    /// Integrity: the pack trailer, an existing `.idx` (magic/version, fanout, checksums, object
1432    /// count) and the name of every object are verified: base objects that are not needed are
1433    /// streamed through the hasher and dropped, and every delta (leaf deltas included) is rebuilt
1434    /// so its idx-supplied name is checked against the rebuilt content.
1435    pub fn decode_without_callback<C>(
1436        &mut self,
1437        pack: &mut (impl BufRead + Send),
1438        pack_id_callback: Option<C>,
1439    ) -> Result<(), GitError>
1440    where
1441        C: FnOnce(ObjectHash) + Send + 'static,
1442    {
1443        self.decode_inner(pack, None, pack_id_callback, DecodeOptions::streaming())
1444    }
1445
1446    /// Decodes a pack file from disk and invokes a callback for each decoded object.
1447    ///
1448    /// File-backed callers can use this path to reuse the same index-guided retention scan as
1449    /// `decode_file_without_callback`, while preserving the object metadata and CRC32 values needed
1450    /// by callback consumers such as index generation.
1451    pub fn decode_file<F, C>(
1452        &mut self,
1453        pack_path: impl AsRef<Path>,
1454        callback: F,
1455        pack_id_callback: Option<C>,
1456    ) -> Result<(), GitError>
1457    where
1458        F: Fn(MetaAttached<Entry, EntryMeta>) + Sync + Send + 'static,
1459        C: FnOnce(ObjectHash) + Send + 'static,
1460    {
1461        let callback: DecodeCallback = Arc::new(callback);
1462        self.decode_file_inner(
1463            pack_path.as_ref(),
1464            Some(callback),
1465            pack_id_callback,
1466            FileDecodeMode::RetainAll,
1467        )
1468    }
1469
1470    /// Decodes a pack file from disk without constructing callback entries, while still restoring
1471    /// every object in the pack.
1472    ///
1473    /// Compared with `decode_file`, this avoids callback metadata and object-data clones. Compared
1474    /// with `decode_file_without_callback`, it does not skip leaf objects, so benchmark callers can
1475    /// measure a complete decode without producing per-object output.
1476    pub fn decode_file_full_without_callback<C>(
1477        &mut self,
1478        pack_path: impl AsRef<Path>,
1479        pack_id_callback: Option<C>,
1480    ) -> Result<(), GitError>
1481    where
1482        C: FnOnce(ObjectHash) + Send + 'static,
1483    {
1484        self.decode_file_inner(
1485            pack_path.as_ref(),
1486            None,
1487            pack_id_callback,
1488            FileDecodeMode::RetainAll,
1489        )
1490    }
1491
1492    /// Decodes a pack file from disk without retaining objects after their final delta user.
1493    ///
1494    /// This is a no-callback fast path for validation/benchmark callers. It performs a light
1495    /// dependency scan first, then releases cache entries as soon as all later delta objects that
1496    /// need them have acquired an `Arc` to the base.
1497    pub fn decode_file_without_callback<C>(
1498        &mut self,
1499        pack_path: impl AsRef<Path>,
1500        pack_id_callback: Option<C>,
1501    ) -> Result<(), GitError>
1502    where
1503        C: FnOnce(ObjectHash) + Send + 'static,
1504    {
1505        self.decode_file_inner(
1506            pack_path.as_ref(),
1507            None,
1508            pack_id_callback,
1509            FileDecodeMode::SkipUnneeded,
1510        )
1511    }
1512
1513    fn decode_file_inner<C>(
1514        &mut self,
1515        pack_path: &Path,
1516        callback: Option<DecodeCallback>,
1517        pack_id_callback: Option<C>,
1518        mode: FileDecodeMode,
1519    ) -> Result<(), GitError>
1520    where
1521        C: FnOnce(ObjectHash) + Send + 'static,
1522    {
1523        self.decode_file_inner_with_sync_base_callbacks(
1524            pack_path,
1525            callback,
1526            pack_id_callback,
1527            mode,
1528            true,
1529        )
1530    }
1531
1532    fn decode_file_inner_with_sync_base_callbacks<C>(
1533        &mut self,
1534        pack_path: &Path,
1535        callback: Option<DecodeCallback>,
1536        pack_id_callback: Option<C>,
1537        mode: FileDecodeMode,
1538        sync_base_callbacks: bool,
1539    ) -> Result<(), GitError>
1540    where
1541        C: FnOnce(ObjectHash) + Send + 'static,
1542    {
1543        // An existing idx must be valid for this repository kind (magic/version, object names,
1544        // both checksums, object count): any mismatch fails closed instead of silently falling
1545        // back to a full scan. Only a *missing* idx selects the scan path.
1546        let idx_path = pack_path.with_extension("idx");
1547        // `symlink_metadata` (not `metadata`): a dangling `.idx` symlink counts as present and
1548        // then fails to open, instead of being mistaken for a missing idx.
1549        let scan = match std::fs::symlink_metadata(&idx_path) {
1550            Ok(_) => Pack::scan_decode_retention_from_index(pack_path, self.hash_kind)?,
1551            // Only a genuinely missing idx selects the scan path; an unreadable, dangling or
1552            // otherwise inaccessible idx is an error (fail-closed), never a silent fallback.
1553            Err(e) if e.kind() == io::ErrorKind::NotFound => {
1554                let scan_file = File::open(pack_path)
1555                    .map_err(|e| GitError::InvalidPackFile(format!("Open pack file error: {e}")))?;
1556                let mut scan_reader = io::BufReader::new(scan_file);
1557                Pack::scan_decode_retention(&mut scan_reader, self.hash_kind)?
1558            }
1559            Err(e) => {
1560                return Err(GitError::InvalidPackFile(format!(
1561                    "Pack index {} exists but cannot be read: {e}",
1562                    idx_path.display()
1563                )));
1564            }
1565        };
1566        self.decode_file_inner_with_scan(
1567            pack_path,
1568            callback,
1569            pack_id_callback,
1570            mode,
1571            scan,
1572            sync_base_callbacks,
1573        )
1574    }
1575
1576    fn decode_file_inner_with_scan<C>(
1577        &mut self,
1578        pack_path: &Path,
1579        callback: Option<DecodeCallback>,
1580        pack_id_callback: Option<C>,
1581        mode: FileDecodeMode,
1582        scan: DecodeScan,
1583        sync_base_callbacks: bool,
1584    ) -> Result<(), GitError>
1585    where
1586        C: FnOnce(ObjectHash) + Send + 'static,
1587    {
1588        let DecodeScan {
1589            retention,
1590            object_hashes: known_hashes,
1591            object_crcs: known_crcs,
1592            object_offsets: known_offsets,
1593            pack_hash,
1594            pack_hash_check,
1595        } = scan;
1596        let expected_pack_hash =
1597            pack_hash.or_else(|| pack_hash_check.as_ref().map(|check| check.payload_hash));
1598        let retention = Arc::new(retention);
1599        let retention_mode = match mode {
1600            FileDecodeMode::RetainAll => DecodeRetentionMode::retain_all(retention),
1601            FileDecodeMode::SkipUnneeded => DecodeRetentionMode::skip_unneeded(retention),
1602        };
1603        // The pack payload hash is recomputed and checked against the trailer (and the
1604        // idx-copied pack hash) in every mode, the low-memory callback mode included: an idx
1605        // can only vouch for the trailer bytes, never for the payload that precedes them. The
1606        // hash is taken inline by the decode reader (`Wrapper::new_with_kind`) in the same
1607        // pass that decodes the objects — never by a second read of the pack (GC-10). Only the
1608        // stream path, which already hashed the payload while copying it to the temp file
1609        // (`pack_hash_check`), skips the inline hash.
1610        let file = File::open(pack_path)
1611            .map_err(|e| GitError::InvalidPackFile(format!("Open pack file error: {e}")))?;
1612        let mut reader = io::BufReader::with_capacity(FILE_DECODE_BUFFER_SIZE, file);
1613        let decode_result = self.decode_inner(
1614            &mut reader,
1615            callback,
1616            pack_id_callback,
1617            DecodeOptions {
1618                retention_mode,
1619                known_hashes,
1620                known_crcs,
1621                known_offsets,
1622                expected_pack_hash,
1623                verify_pack_stream_hash: pack_hash_check.is_none(),
1624                sync_base_callbacks,
1625            },
1626        );
1627
1628        decode_result?;
1629        if let Some(hash_check) = pack_hash_check {
1630            Self::verify_pack_hash_check(&hash_check, self.signature)?;
1631        }
1632
1633        Ok(())
1634    }
1635
1636    fn verify_pack_hash_check(
1637        hash_check: &PackHashCheck,
1638        signature: ObjectHash,
1639    ) -> Result<(), GitError> {
1640        if hash_check.trailer_hash != signature {
1641            return Err(GitError::InvalidPackFile(format!(
1642                "The pack file trailer hash {} does not match decoded trailer hash {}",
1643                hash_check.trailer_hash, signature
1644            )));
1645        }
1646        if hash_check.payload_hash != signature {
1647            return Err(GitError::InvalidPackFile(format!(
1648                "The pack file hash {} does not match the trailer hash {}",
1649                hash_check.payload_hash, signature
1650            )));
1651        }
1652        Ok(())
1653    }
1654
1655    fn decode_inner<C>(
1656        &mut self,
1657        pack: &mut (impl BufRead + Send),
1658        callback: Option<DecodeCallback>,
1659        pack_id_callback: Option<C>,
1660        options: DecodeOptions,
1661    ) -> Result<(), GitError>
1662    where
1663        C: FnOnce(ObjectHash) + Send + 'static,
1664    {
1665        let DecodeOptions {
1666            retention_mode,
1667            known_hashes,
1668            known_crcs,
1669            known_offsets,
1670            expected_pack_hash,
1671            verify_pack_stream_hash,
1672            sync_base_callbacks,
1673        } = options;
1674        let time = Instant::now();
1675        let mut last_update_time = time.elapsed().as_millis();
1676        let log_enabled = tracing::enabled!(tracing::Level::INFO);
1677        let log_info = |_i: usize, pack: &Pack| {
1678            tracing::info!(
1679                "time {:.2} s \t decode: {:?} \t dec-num: {} \t cah-num: {} \t Objs: {} MB \t CacheUsed: {} MB",
1680                time.elapsed().as_millis() as f64 / 1000.0,
1681                _i,
1682                pack.pool.queued_count(),
1683                pack.caches.queued_tasks(),
1684                pack.cache_objs_mem_used() / 1024 / 1024,
1685                pack.caches.memory_used() / 1024 / 1024
1686            );
1687        };
1688        // CRCs are tracked whenever a consumer wants them (callback) or an idx supplied them
1689        // (verification), in every mode including the low-memory callback mode; each object's
1690        // compressed bytes are checked against the idx CRC inside `decode_pack_object_with_crc`.
1691        let track_crc = callback.is_some() || known_crcs.is_some();
1692        let known_hashes = known_hashes.as_deref();
1693        let known_crcs = known_crcs.as_deref();
1694        let known_offsets = known_offsets.as_deref();
1695        let shared_params = Arc::new(SharedParams {
1696            pool: self.pool.clone(),
1697            waitlist: self.waitlist.clone(),
1698            caches: self.caches.clone(),
1699            cache_objs_mem_size: self.cache_objs_mem.clone(),
1700            callback,
1701            retention: retention_mode.retention,
1702            skip_unneeded_objects: retention_mode.skip_unneeded_objects,
1703            error: Mutex::new(None),
1704        });
1705        let mut reader = if verify_pack_stream_hash {
1706            Wrapper::new_with_kind(pack, self.hash_kind)
1707        } else {
1708            Wrapper::new_without_hash(pack)
1709        };
1710
1711        let result = Pack::check_header(&mut reader);
1712        match result {
1713            Ok((object_num, _)) => {
1714                self.number = object_num as usize;
1715            }
1716            Err(e) => {
1717                return Err(e);
1718            }
1719        }
1720        tracing::info!("The pack file has {} objects", self.number);
1721        let mut offset: usize = 12;
1722        let mut i = 0;
1723        let mem_limit = if self.caches.is_unbounded() {
1724            None
1725        } else {
1726            self.mem_limit
1727        };
1728        while i < self.number {
1729            // log per 1000 objects and 1 second
1730            if log_enabled && i % 1000 == 0 {
1731                let time_now = time.elapsed().as_millis();
1732                if time_now - last_update_time > 1000 {
1733                    log_info(i, self);
1734                    last_update_time = time_now;
1735                }
1736            }
1737            // 3 parts: Waitlist + TheadPool + Caches
1738            // hardcode the limit of the tasks of threads_pool queue, to limit memory
1739            if let Some(mem_limit) = mem_limit {
1740                while self.pool.queued_count() > MAX_QUEUED_DECODE_TASKS
1741                    || self.memory_used() > mem_limit
1742                {
1743                    thread::yield_now();
1744                }
1745            } else {
1746                while self.pool.queued_count() > MAX_QUEUED_DECODE_TASKS {
1747                    thread::yield_now();
1748                }
1749            }
1750            // The idx entry paired with object i must point at the object's real start: an
1751            // idx whose offsets are permuted or point inside objects is rejected here even if
1752            // its checksums verify (names and CRCs are checked per object below).
1753            if let Some(expected) = known_offsets.and_then(|offsets| offsets.get(i).copied())
1754                && expected != offset
1755            {
1756                self.abort_decode();
1757                return Err(GitError::InvalidPackFile(format!(
1758                    "Pack object {i} starts at offset {offset} but the pack index records offset {expected}"
1759                )));
1760            }
1761            let known_hash = known_hashes.and_then(|hashes| hashes.get(i).copied());
1762            let r: Result<Option<CacheObject>, GitError> = Pack::decode_pack_object_with_crc(
1763                self.hash_kind,
1764                &mut reader,
1765                &mut offset,
1766                track_crc,
1767                shared_params.skip_unneeded_objects,
1768                shared_params.callback.is_some() && Self::low_memory_callback_entries(),
1769                known_hash,
1770                known_crcs.and_then(|crcs| crcs.get(i).copied()),
1771                shared_params.retention.as_deref(),
1772            );
1773            match r {
1774                Ok(Some(obj)) => {
1775                    let Some(mut obj) = Self::try_process_skipped_low_memory_callback_object(
1776                        &shared_params,
1777                        obj,
1778                        Self::low_memory_callback_entries(),
1779                    ) else {
1780                        i += 1;
1781                        continue;
1782                    };
1783
1784                    if matches!(obj.info, CacheObjectInfo::BaseObject(_, _))
1785                        && Self::should_drop_no_callback_base(&shared_params, &obj)
1786                    {
1787                        i += 1;
1788                        continue;
1789                    }
1790
1791                    obj.set_mem_recorder(self.cache_objs_mem.clone());
1792                    obj.record_mem_size();
1793
1794                    if matches!(obj.info, CacheObjectInfo::BaseObject(_, _))
1795                        && (shared_params.callback.is_none() || sync_base_callbacks)
1796                    {
1797                        Self::cache_obj_and_process_waitlist(&shared_params, obj);
1798                        i += 1;
1799                        continue;
1800                    }
1801
1802                    let params = shared_params.clone();
1803                    let kind = self.hash_kind;
1804                    self.pool.execute(move || {
1805                        set_hash_kind(kind);
1806                        match obj.info {
1807                            CacheObjectInfo::BaseObject(_, _) => {
1808                                Self::cache_obj_and_process_waitlist(&params, obj);
1809                            }
1810                            CacheObjectInfo::OffsetDelta(_, _)
1811                            | CacheObjectInfo::OffsetZstdelta(_, _)
1812                            | CacheObjectInfo::HashDelta(_, _) => {
1813                                Self::process_delta_dependency(params, obj);
1814                            }
1815                        }
1816                    });
1817                }
1818                Ok(None) => {}
1819                Err(e) => {
1820                    self.abort_decode();
1821                    return Err(e);
1822                }
1823            }
1824            i += 1;
1825        }
1826        log_info(i, self);
1827        let render_hash = verify_pack_stream_hash.then(|| reader.final_hash());
1828        self.signature = match ObjectHash::from_stream_for_kind(self.hash_kind, &mut reader) {
1829            Ok(signature) => signature,
1830            Err(e) => {
1831                self.abort_decode();
1832                return Err(GitError::InvalidPackFile(format!(
1833                    "Error reading pack trailer hash: {e}"
1834                )));
1835            }
1836        };
1837
1838        if let Some(expected_pack_hash) = expected_pack_hash
1839            && expected_pack_hash != self.signature
1840        {
1841            self.abort_decode();
1842            return Err(GitError::InvalidPackFile(format!(
1843                "The pack index hash {} does not match the trailer hash {}",
1844                expected_pack_hash, self.signature
1845            )));
1846        }
1847
1848        if let Some(render_hash) = render_hash
1849            && render_hash != self.signature
1850        {
1851            self.abort_decode();
1852            return Err(GitError::InvalidPackFile(format!(
1853                "The pack file hash {} does not match the trailer hash {}",
1854                render_hash, self.signature
1855            )));
1856        }
1857
1858        let end = utils::is_eof(&mut reader);
1859        if !end {
1860            self.abort_decode();
1861            return Err(GitError::InvalidPackFile(
1862                "The pack file is not at the end".to_string(),
1863            ));
1864        }
1865
1866        self.pool.join(); // wait for all threads to finish
1867
1868        if let Some(error) = shared_params.error.lock().unwrap().take() {
1869            self.abort_decode();
1870            return Err(error);
1871        }
1872
1873        // send pack id for metadata
1874        if let Some(pack_callback) = pack_id_callback {
1875            pack_callback(self.signature);
1876        }
1877        // !Attention: Caches threadpool may not stop, but it's not a problem (garbage file data)
1878        // So that files != self.number
1879        // Fail closed on a thin or malformed pack: a delta whose base never appeared (a
1880        // ref-delta base outside the pack, or an offset-delta pointing at a non-object
1881        // offset) is still waiting here. Return an error instead of panicking.
1882        let pending_offset = self.waitlist.map_offset.len();
1883        let pending_ref = self.waitlist.map_ref.len();
1884        if pending_offset != 0 || pending_ref != 0 {
1885            let first_offset = self
1886                .waitlist
1887                .map_offset
1888                .iter()
1889                .next()
1890                .map(|entry| format!("; first missing base offset {}", entry.key()))
1891                .unwrap_or_default();
1892            let first_ref = self
1893                .waitlist
1894                .map_ref
1895                .iter()
1896                .next()
1897                .map(|entry| format!("; first missing base object {}", entry.key()))
1898                .unwrap_or_default();
1899            self.abort_decode();
1900            return Err(GitError::InvalidPackFile(format!(
1901                "Pack references bases that are not in the pack (thin pack?): {pending_offset} offset-delta and {pending_ref} ref-delta object(s) unresolved{first_offset}{first_ref}"
1902            )));
1903        }
1904        // Because we may skip some objects (e.g. AI objects), we use >= instead of ==
1905        if self.number < self.caches.total_inserted() {
1906            self.abort_decode();
1907            return Err(GitError::InvalidPackFile(format!(
1908                "Pack header declares {} objects but {} were decoded",
1909                self.number,
1910                self.caches.total_inserted()
1911            )));
1912        }
1913        tracing::info!(
1914            "The pack file has been decoded successfully, takes: [ {:?} ]",
1915            time.elapsed()
1916        );
1917        self.caches.clear(); // clear cached objects & stop threads
1918        assert_eq!(self.cache_objs_mem_used(), 0); // all the objs should be dropped until here
1919
1920        // impl in Drop Trait
1921        // if self.clean_tmp {
1922        //     self.caches.remove_tmp_dir();
1923        // }
1924
1925        Ok(())
1926    }
1927
1928    /// Decode a Pack in a new thread and send the CacheObjects while decoding.
1929    /// <br> Attention: It will consume the `pack` and return in a JoinHandle.
1930    pub fn decode_async(
1931        mut self,
1932        mut pack: impl BufRead + Send + 'static,
1933        sender: UnboundedSender<Entry>,
1934    ) -> JoinHandle<Pack> {
1935        let kind = self.hash_kind;
1936        thread::spawn(move || {
1937            set_hash_kind(kind);
1938            self.decode(
1939                &mut pack,
1940                move |entry| {
1941                    if let Err(e) = sender.send(entry.inner) {
1942                        eprintln!("Channel full, failed to send entry: {e:?}");
1943                    }
1944                },
1945                None::<fn(ObjectHash)>,
1946            )
1947            .unwrap();
1948            self
1949        })
1950    }
1951
1952    /// Decodes a `Pack` from a `Stream` of `Bytes`, and sends the `Entry` while decoding.
1953    pub async fn decode_stream(
1954        mut self,
1955        mut stream: impl Stream<Item = Result<Bytes, Error>> + Unpin + Send + 'static,
1956        sender: UnboundedSender<MetaAttached<Entry, EntryMeta>>,
1957        pack_hash_send: Option<UnboundedSender<ObjectHash>>,
1958    ) -> Self {
1959        let kind = self.hash_kind;
1960        let (tx, rx) = std::sync::mpsc::channel();
1961        let mut reader = StreamBufReader::new(rx);
1962        tokio::spawn(async move {
1963            while let Some(chunk) = stream.next().await {
1964                let data = chunk.unwrap().to_vec();
1965                if let Err(e) = tx.send(data) {
1966                    eprintln!("Sending Error: {e:?}");
1967                    break;
1968                }
1969            }
1970        });
1971        // CPU-bound task, so use spawn_blocking
1972        // DO NOT use thread::spawn, because it will block tokio runtime (if single-threaded runtime, like in tests)
1973        tokio::task::spawn_blocking(move || {
1974            set_hash_kind(kind);
1975            self.decode(
1976                &mut reader,
1977                move |entry: MetaAttached<Entry, EntryMeta>| {
1978                    // as we used unbound channel here, it will never full so can be send with synchronous
1979                    if let Err(e) = sender.send(entry) {
1980                        eprintln!("unbound channel Sending Error: {e:?}");
1981                    }
1982                },
1983                Some(move |pack_id: ObjectHash| {
1984                    if let Some(pack_id_send) = pack_hash_send
1985                        && let Err(e) = pack_id_send.send(pack_id)
1986                    {
1987                        eprintln!("unbound channel Sending Error: {e:?}");
1988                    }
1989                }),
1990            )
1991            .unwrap();
1992            self
1993        })
1994        .await
1995        .unwrap()
1996    }
1997
1998    /// CacheObjects + Index size of Caches
1999    fn memory_used(&self) -> usize {
2000        self.cache_objs_mem_used() + self.caches.memory_used_index()
2001    }
2002
2003    /// The total memory used by the CacheObjects of this Pack
2004    fn cache_objs_mem_used(&self) -> usize {
2005        self.cache_objs_mem.load(Ordering::Acquire)
2006    }
2007
2008    fn release_offset_dependency(
2009        shared_params: &SharedParams,
2010        base_offset: usize,
2011        base_obj: &CacheObject,
2012    ) {
2013        if let Some(retention) = &shared_params.retention {
2014            retention.consume_offset_dependency(base_offset);
2015            Self::maybe_remove_released_base(shared_params, base_obj);
2016        }
2017    }
2018
2019    fn release_hash_dependency(
2020        shared_params: &SharedParams,
2021        base_hash: ObjectHash,
2022        base_obj: &CacheObject,
2023    ) {
2024        if let Some(retention) = &shared_params.retention {
2025            retention.consume_hash_dependency(base_hash);
2026            Self::maybe_remove_released_base(shared_params, base_obj);
2027        }
2028    }
2029
2030    fn maybe_remove_released_base(shared_params: &SharedParams, base_obj: &CacheObject) {
2031        if let Some(retention) = &shared_params.retention
2032            && let Some(hash) = base_obj.base_object_hash()
2033            && !retention.should_retain(base_obj.offset, hash)
2034        {
2035            shared_params.caches.remove_unbounded(base_obj.offset, hash);
2036        }
2037    }
2038
2039    fn process_waitlist_objects(
2040        shared_params: &Arc<SharedParams>,
2041        wait_objs: Vec<CacheObject>,
2042        base_obj: Arc<CacheObject>,
2043    ) {
2044        for obj in wait_objs {
2045            // Process the objects waiting for the new object(base_obj = new_obj)
2046            Self::process_delta(Arc::clone(shared_params), obj, base_obj.clone());
2047        }
2048    }
2049
2050    fn try_process_skipped_low_memory_callback_object(
2051        shared_params: &Arc<SharedParams>,
2052        obj: CacheObject,
2053        low_memory_callback_entries: bool,
2054    ) -> Option<CacheObject> {
2055        if !low_memory_callback_entries || !obj.data_decompressed.is_empty() {
2056            return Some(obj);
2057        }
2058
2059        let (Some(callback), Some(retention)) = (
2060            shared_params.callback.as_ref(),
2061            shared_params.retention.as_ref(),
2062        ) else {
2063            return Some(obj);
2064        };
2065
2066        match &obj.info {
2067            CacheObjectInfo::BaseObject(_, hash) => {
2068                if retention.should_retain(obj.offset, *hash)
2069                    || shared_params.waitlist.has_waiters(obj.offset, *hash)
2070                {
2071                    return Some(obj);
2072                }
2073                callback(Self::callback_entry_owned(obj));
2074                None
2075            }
2076            CacheObjectInfo::OffsetDelta(_, _)
2077            | CacheObjectInfo::OffsetZstdelta(_, _)
2078            | CacheObjectInfo::HashDelta(_, _) => {
2079                let Some(hash) = obj.known_hash else {
2080                    return Some(obj);
2081                };
2082                if retention.should_retain(obj.offset, hash)
2083                    || shared_params.waitlist.has_waiters(obj.offset, hash)
2084                {
2085                    return Some(obj);
2086                }
2087                Self::process_delta_dependency(shared_params.clone(), obj);
2088                None
2089            }
2090        }
2091    }
2092
2093    fn should_drop_no_callback_base(shared_params: &SharedParams, base_obj: &CacheObject) -> bool {
2094        if shared_params.callback.is_some() {
2095            return false;
2096        }
2097
2098        let Some(retention) = &shared_params.retention else {
2099            return false;
2100        };
2101
2102        let Some(hash) = base_obj.base_object_hash() else {
2103            return false;
2104        };
2105
2106        !retention.should_retain(base_obj.offset, hash)
2107            && !shared_params.waitlist.has_waiters(base_obj.offset, hash)
2108    }
2109
2110    fn process_delta_dependency(shared_params: Arc<SharedParams>, obj: CacheObject) {
2111        match obj.info {
2112            CacheObjectInfo::OffsetDelta(base_offset, _)
2113            | CacheObjectInfo::OffsetZstdelta(base_offset, _) => {
2114                if let Some(base_obj) = shared_params.caches.get_by_offset(base_offset) {
2115                    Self::release_offset_dependency(&shared_params, base_offset, &base_obj);
2116                    Self::process_delta(shared_params, obj, base_obj);
2117                } else {
2118                    shared_params.waitlist.insert_offset(base_offset, obj);
2119                    if let Some(retention) = &shared_params.retention {
2120                        retention.consume_offset_dependency(base_offset);
2121                    }
2122                    if let Some(base_obj) = shared_params.caches.get_by_offset(base_offset) {
2123                        Self::maybe_remove_released_base(&shared_params, &base_obj);
2124                        Self::process_waitlist(&shared_params, base_obj);
2125                    }
2126                }
2127            }
2128            CacheObjectInfo::HashDelta(base_ref, _) => {
2129                if let Some(base_obj) = shared_params.caches.get_by_hash(base_ref) {
2130                    Self::release_hash_dependency(&shared_params, base_ref, &base_obj);
2131                    Self::process_delta(shared_params, obj, base_obj);
2132                } else {
2133                    shared_params.waitlist.insert_ref(base_ref, obj);
2134                    if let Some(retention) = &shared_params.retention {
2135                        retention.consume_hash_dependency(base_ref);
2136                    }
2137                    if let Some(base_obj) = shared_params.caches.get_by_hash(base_ref) {
2138                        Self::maybe_remove_released_base(&shared_params, &base_obj);
2139                        Self::process_waitlist(&shared_params, base_obj);
2140                    }
2141                }
2142            }
2143            CacheObjectInfo::BaseObject(_, _) => unreachable!(),
2144        }
2145    }
2146
2147    /// Rebuild the Delta Object in a new thread & process the objects waiting for it recursively.
2148    /// <br> This function must be *static*, because [&self] can't be moved into a new thread.
2149    fn process_delta(
2150        shared_params: Arc<SharedParams>,
2151        delta_obj: CacheObject,
2152        base_obj: Arc<CacheObject>,
2153    ) {
2154        shared_params.pool.clone().execute(move || {
2155            let known_hash = delta_obj.known_hash;
2156            let new_obj = match delta_obj.info {
2157                CacheObjectInfo::OffsetDelta(_, _) | CacheObjectInfo::HashDelta(_, _) => {
2158                    Pack::rebuild_delta_with_hash(delta_obj, base_obj, known_hash)
2159                }
2160                CacheObjectInfo::OffsetZstdelta(_, _) => {
2161                    Pack::rebuild_zstdelta_with_hash(delta_obj, base_obj, known_hash)
2162                }
2163                _ => unreachable!(),
2164            };
2165
2166            let mut new_obj = match new_obj {
2167                Ok(new_obj) => new_obj,
2168                Err(error) => {
2169                    let mut decode_error = shared_params.error.lock().unwrap();
2170                    if decode_error.is_none() {
2171                        *decode_error = Some(error);
2172                    }
2173                    return;
2174                }
2175            };
2176
2177            new_obj.set_mem_recorder(shared_params.cache_objs_mem_size.clone());
2178            new_obj.record_mem_size();
2179            Self::cache_obj_and_process_waitlist(&shared_params, new_obj); //Indirect Recursion
2180        });
2181    }
2182
2183    /// Cache the new object & process the objects waiting for it (in multi-threading).
2184    fn cache_obj_and_process_waitlist(shared_params: &Arc<SharedParams>, new_obj: CacheObject) {
2185        if let Some(retention) = &shared_params.retention {
2186            let hash = new_obj.base_object_hash().unwrap();
2187            let offset = new_obj.offset;
2188            let should_retain = retention.should_retain(offset, hash);
2189            if should_retain {
2190                if let Some(callback) = &shared_params.callback {
2191                    callback(Self::callback_entry_ref(&new_obj));
2192                }
2193                let new_obj = shared_params.caches.insert(offset, hash, new_obj);
2194                let wait_objs = shared_params.waitlist.take(offset, hash);
2195                Self::process_waitlist_objects(shared_params, wait_objs, new_obj);
2196            } else {
2197                let wait_objs = shared_params.waitlist.take(offset, hash);
2198                if !wait_objs.is_empty() {
2199                    if let Some(callback) = &shared_params.callback {
2200                        callback(Self::callback_entry_ref(&new_obj));
2201                    }
2202                    Self::process_waitlist_objects(shared_params, wait_objs, Arc::new(new_obj));
2203                } else if let Some(callback) = &shared_params.callback {
2204                    callback(Self::callback_entry_owned(new_obj));
2205                }
2206            }
2207            return;
2208        }
2209        if let Some(callback) = &shared_params.callback {
2210            callback(Self::callback_entry_ref(&new_obj));
2211        }
2212        let new_obj = shared_params.caches.insert(
2213            new_obj.offset,
2214            new_obj.base_object_hash().unwrap(),
2215            new_obj,
2216        );
2217        Self::process_waitlist(shared_params, new_obj);
2218    }
2219
2220    fn process_waitlist(shared_params: &Arc<SharedParams>, base_obj: Arc<CacheObject>) {
2221        let wait_objs = shared_params
2222            .waitlist
2223            .take(base_obj.offset, base_obj.base_object_hash().unwrap());
2224        Self::process_waitlist_objects(shared_params, wait_objs, base_obj);
2225    }
2226
2227    /// Reconstruct the Delta Object based on the "base object"
2228    /// and return the new object.
2229    pub fn rebuild_delta(
2230        delta_obj: CacheObject,
2231        base_obj: Arc<CacheObject>,
2232    ) -> Result<CacheObject, GitError> {
2233        Self::rebuild_delta_with_hash(delta_obj, base_obj, None)
2234    }
2235
2236    /// Fail closed when an idx-supplied object name disagrees with the recomputed content hash.
2237    /// When CRCs are tracked, the CRC of an object's compressed pack bytes must match the CRC
2238    /// the idx records for it (fail-closed on object/index mismatch).
2239    fn verify_known_crc(
2240        track_crc: bool,
2241        offset: usize,
2242        computed: u32,
2243        known_crc: Option<u32>,
2244    ) -> Result<(), GitError> {
2245        match known_crc {
2246            Some(expected) if track_crc && computed != expected => {
2247                Err(GitError::InvalidPackFile(format!(
2248                    "Object at offset {offset} has CRC32 {computed:#010x} but the pack index records {expected:#010x}"
2249                )))
2250            }
2251            _ => Ok(()),
2252        }
2253    }
2254
2255    fn verify_known_hash(
2256        offset: usize,
2257        computed: ObjectHash,
2258        known_hash: Option<ObjectHash>,
2259    ) -> Result<(), GitError> {
2260        match known_hash {
2261            Some(expected) if expected != computed => Err(GitError::InvalidPackFile(format!(
2262                "Object at offset {offset} hashes to {} ({}) but the pack index names it {} ({})",
2263                computed,
2264                computed.kind(),
2265                expected,
2266                expected.kind()
2267            ))),
2268            _ => Ok(()),
2269        }
2270    }
2271
2272    fn rebuild_delta_with_hash(
2273        delta_obj: CacheObject,
2274        base_obj: Arc<CacheObject>,
2275        known_hash: Option<ObjectHash>,
2276    ) -> Result<CacheObject, GitError> {
2277        let mut stream = Cursor::new(delta_obj.data_decompressed.as_slice());
2278        let result = crate::delta::delta_decode(&mut stream, &base_obj.data_decompressed)
2279            .map_err(|error| GitError::DeltaObjectError(error.to_string()))?;
2280
2281        // The rebuilt object belongs to the same repository as its base: take the kind from
2282        // the base's own ID, never from the worker's thread-local. An idx-supplied name is
2283        // verified against the recomputed hash, never trusted.
2284        let kind = base_obj
2285            .base_object_hash()
2286            .ok_or_else(|| {
2287                GitError::DeltaObjectError("delta base is not a resolved base object".to_string())
2288            })?
2289            .kind();
2290        let hash = utils::calculate_object_hash_for_kind(kind, base_obj.object_type(), &result)?;
2291        Self::verify_known_hash(delta_obj.offset, hash, known_hash)?;
2292        // create new obj from `delta_obj` & `result` instead of modifying `delta_obj` for heap-size recording
2293        Ok(CacheObject {
2294            info: CacheObjectInfo::BaseObject(base_obj.object_type(), hash),
2295            offset: delta_obj.offset,
2296            crc32: delta_obj.crc32,
2297            data_decompressed: result,
2298            mem_recorder: None,
2299            is_delta_in_pack: delta_obj.is_delta_in_pack,
2300            known_hash: None,
2301        }) // Canonical form (Complete Object)
2302        // Memory recording will happen after this function returns. See `process_delta`
2303    }
2304    /// Rebuild a zstdelta on top of a resolved base object. The rebuilt object's ID is
2305    /// computed with the base object's own hash kind; a base without a resolved ID or a
2306    /// failing zstdelta application is an error, never a panic or a thread-local fallback.
2307    pub fn rebuild_zstdelta(
2308        delta_obj: CacheObject,
2309        base_obj: Arc<CacheObject>,
2310    ) -> Result<CacheObject, GitError> {
2311        Self::rebuild_zstdelta_with_hash(delta_obj, base_obj, None)
2312    }
2313
2314    /// Rebuild a zstdelta and verify an idx-supplied name against the recomputed hash.
2315    fn rebuild_zstdelta_with_hash(
2316        delta_obj: CacheObject,
2317        base_obj: Arc<CacheObject>,
2318        known_hash: Option<ObjectHash>,
2319    ) -> Result<CacheObject, GitError> {
2320        let result = zstdelta::apply(&base_obj.data_decompressed, &delta_obj.data_decompressed)
2321            .map_err(|e| GitError::DeltaObjectError(format!("Failed to apply zstdelta: {e}")))?;
2322        let kind = base_obj
2323            .base_object_hash()
2324            .ok_or_else(|| {
2325                GitError::DeltaObjectError("delta base is not a resolved base object".to_string())
2326            })?
2327            .kind();
2328        let hash = utils::calculate_object_hash_for_kind(kind, base_obj.object_type(), &result)?;
2329        Self::verify_known_hash(delta_obj.offset, hash, known_hash)?;
2330        Ok(CacheObject {
2331            info: CacheObjectInfo::BaseObject(base_obj.object_type(), hash),
2332            offset: delta_obj.offset,
2333            crc32: delta_obj.crc32,
2334            data_decompressed: result,
2335            mem_recorder: None,
2336            is_delta_in_pack: delta_obj.is_delta_in_pack,
2337            known_hash: None,
2338        }) // Canonical form (Complete Object)
2339        // Memory recording will happen after this function returns. See `process_delta`
2340    }
2341}
2342
2343impl Pack {
2344    /// Scans a pack file and returns statistics about the object types it contains.
2345    ///
2346    /// This is a lightweight read-only utility that parses the pack header and every
2347    /// object header without fully reconstructing delta chains.  It therefore runs
2348    /// much faster than a full [`Pack::decode`] call for large packs.
2349    ///
2350    /// # Parameters
2351    /// * `path` - Path to the `.pack` file on disk.
2352    ///
2353    /// # Returns
2354    /// * `Ok(PackStats)` – breakdown of object counts by type.
2355    /// * `Err(GitError)` – if the file cannot be opened or the pack header is invalid.
2356    ///
2357    /// # Example
2358    /// ```no_run
2359    /// use std::path::PathBuf;
2360    /// use git_internal::internal::pack::{Pack, decode::PackStats};
2361    ///
2362    /// let stats = Pack::stats_pack(PathBuf::from("repo.pack")).unwrap();
2363    /// println!("total={}, commits={}, blobs={}", stats.total, stats.commits, stats.blobs);
2364    /// ```
2365    pub fn stats_pack(path: PathBuf) -> Result<PackStats, crate::errors::GitError> {
2366        PackStats::analyze(path)
2367    }
2368}
2369
2370#[cfg(test)]
2371mod tests {
2372    use std::{
2373        fs,
2374        io::{BufReader, Cursor, prelude::*},
2375        path::{Path, PathBuf},
2376        sync::{
2377            Arc, Mutex,
2378            atomic::{AtomicUsize, Ordering},
2379        },
2380    };
2381
2382    use flate2::{Compression, write::ZlibEncoder};
2383    use futures_util::TryStreamExt;
2384    use sha1::{Digest, Sha1};
2385    use tempfile::tempdir;
2386    use threadpool::ThreadPool;
2387    use tokio_util::io::ReaderStream;
2388
2389    use crate::{
2390        hash::{HashKind, ObjectHash, get_hash_kind, set_hash_kind_for_test},
2391        internal::{
2392            object::types::ObjectType,
2393            pack::{
2394                Pack,
2395                cache::{_Cache, Caches},
2396                cache_object::{CacheObject, CacheObjectInfo},
2397                test_pack_download::download_pack_file,
2398                tests::init_logger,
2399                utils,
2400                waitlist::Waitlist,
2401            },
2402        },
2403    };
2404
2405    fn pack_test_tmp() -> (tempfile::TempDir, PathBuf) {
2406        let dir = tempdir().unwrap();
2407        let path = dir.path().join(".cache_temp");
2408        (dir, path)
2409    }
2410
2411    const LARGE_PACK_TEST_MEM_LIMIT: usize = super::UNBOUNDED_CACHE_THRESHOLD_BYTES;
2412
2413    #[cfg_attr(coverage, ignore)]
2414    #[ignore = "requires large remote pack fixture"]
2415    #[tokio::test]
2416    async fn test_pack_check_header() {
2417        let (source, _guard) = download_pack_file("medium-sha1.pack");
2418
2419        let f = fs::File::open(source).unwrap();
2420        let mut buf_reader = BufReader::new(f);
2421        let (object_num, _) = Pack::check_header(&mut buf_reader).unwrap();
2422
2423        assert_eq!(object_num, 35031);
2424    }
2425
2426    #[test]
2427    fn test_decompress_data() {
2428        let data = b"Hello, world!"; // Sample data to compress and then decompress
2429        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
2430        encoder.write_all(data).unwrap();
2431        let compressed_data = encoder.finish().unwrap();
2432        let compressed_size = compressed_data.len();
2433
2434        // Create a cursor for the compressed data to simulate a BufRead source
2435        let mut cursor: Cursor<Vec<u8>> = Cursor::new(compressed_data);
2436        let expected_size = data.len();
2437
2438        // Decompress the data and assert correctness
2439        let result = Pack::decompress_data(&mut cursor, expected_size);
2440        match result {
2441            Ok((decompressed_data, bytes_read)) => {
2442                assert_eq!(bytes_read, compressed_size);
2443                assert_eq!(decompressed_data, data);
2444            }
2445            Err(e) => panic!("Decompression failed: {e:?}"),
2446        }
2447    }
2448
2449    #[test]
2450    fn test_pack_decode_truncated_pack_returns_err_without_panic() {
2451        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2452        let (source, _dl_guard) = download_pack_file("small-sha1.pack");
2453        let mut bytes = fs::read(source).unwrap();
2454        bytes.truncate(bytes.len() - 1);
2455
2456        let tmp_dir = tempfile::tempdir().unwrap();
2457        let tmp_path = tmp_dir.path().to_path_buf();
2458        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
2459            let mut buffered = BufReader::new(Cursor::new(bytes));
2460            let mut pack = Pack::new(Some(2), Some(1024 * 1024), Some(tmp_path), true);
2461            pack.decode(&mut buffered, |_| {}, None::<fn(ObjectHash)>)
2462        }));
2463
2464        assert!(result.is_ok(), "truncated pack decode should not panic");
2465        assert!(
2466            matches!(
2467                result.unwrap(),
2468                Err(crate::errors::GitError::InvalidPackFile(_))
2469                    | Err(crate::errors::GitError::IOError(_))
2470            ),
2471            "truncated pack decode should return a pack error"
2472        );
2473    }
2474
2475    #[test]
2476    fn test_skip_compressed_data_exact_size_and_size_errors() {
2477        let data = b"Hello, world!";
2478        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
2479        encoder.write_all(data).unwrap();
2480        let compressed = encoder.finish().unwrap();
2481
2482        let mut exact = Cursor::new(compressed.clone());
2483        let bytes_read = Pack::skip_compressed_data(&mut exact, data.len()).unwrap();
2484        assert_eq!(bytes_read, compressed.len());
2485
2486        let mut too_large = Cursor::new(compressed.clone());
2487        let err = Pack::skip_compressed_data(&mut too_large, data.len() + 1).unwrap_err();
2488        assert!(err.to_string().contains("smaller than the expected size"));
2489
2490        let mut too_small = Cursor::new(compressed);
2491        let err = Pack::skip_compressed_data(&mut too_small, data.len() - 1).unwrap_err();
2492        assert!(err.to_string().contains("exceeds the expected size"));
2493    }
2494
2495    #[test]
2496    fn test_read_be_u64() {
2497        let mut reader = Cursor::new(0x0102_0304_0506_0708u64.to_be_bytes());
2498        assert_eq!(
2499            Pack::read_be_u64(&mut reader).unwrap(),
2500            0x0102_0304_0506_0708
2501        );
2502    }
2503
2504    #[test]
2505    fn test_decode_pack_object_crc_can_be_skipped() {
2506        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2507        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
2508        encoder.write_all(b"a").unwrap();
2509        let compressed = encoder.finish().unwrap();
2510
2511        let mut object_data = Vec::new();
2512        object_data.push(0x31);
2513        object_data.extend_from_slice(&compressed);
2514        let expected_crc = crc32fast::hash(&object_data);
2515
2516        let mut crc_reader = Cursor::new(object_data.clone());
2517        let mut offset = 0;
2518        let with_crc = Pack::decode_pack_object(&mut crc_reader, &mut offset)
2519            .unwrap()
2520            .unwrap();
2521        assert_eq!(with_crc.crc32, expected_crc);
2522        assert_eq!(with_crc.data_decompressed, b"a");
2523
2524        let mut no_crc_reader = Cursor::new(object_data.clone());
2525        let mut offset = 0;
2526        // An idx-supplied name is verified against the recomputed content hash.
2527        let supplied_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
2528        let without_crc = Pack::decode_pack_object_with_crc(
2529            get_hash_kind(),
2530            &mut no_crc_reader,
2531            &mut offset,
2532            false,
2533            false,
2534            false,
2535            Some(supplied_hash),
2536            None,
2537            None,
2538        )
2539        .unwrap()
2540        .unwrap();
2541        assert_eq!(without_crc.crc32, 0);
2542        assert_eq!(without_crc.data_decompressed, b"a");
2543        assert_eq!(without_crc.base_object_hash(), Some(supplied_hash));
2544
2545        // A wrong idx-supplied name fails closed instead of being trusted.
2546        let mut reader = Cursor::new(object_data);
2547        let mut offset = 0;
2548        let err = Pack::decode_pack_object_with_crc(
2549            get_hash_kind(),
2550            &mut reader,
2551            &mut offset,
2552            false,
2553            false,
2554            false,
2555            Some(ObjectHash::new(b"known-hash-from-idx")),
2556            None,
2557            None,
2558        )
2559        .unwrap_err();
2560        assert!(err.to_string().contains("pack index names it"), "{err}");
2561    }
2562
2563    #[test]
2564    fn test_decode_pack_object_can_emit_skipped_base_callback_entry() {
2565        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2566        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
2567        encoder.write_all(b"a").unwrap();
2568        let compressed = encoder.finish().unwrap();
2569
2570        let mut object_data = Vec::new();
2571        object_data.push(0x31);
2572        object_data.extend_from_slice(&compressed);
2573
2574        // The skipped object's idx name is verified by streaming the payload through the hasher.
2575        let supplied_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
2576        let retention = super::DecodeRetention::default();
2577        let mut reader = Cursor::new(object_data);
2578        let mut offset = 0;
2579        let skipped = Pack::decode_pack_object_with_crc(
2580            get_hash_kind(),
2581            &mut reader,
2582            &mut offset,
2583            false,
2584            true,
2585            true,
2586            Some(supplied_hash),
2587            None,
2588            Some(&retention),
2589        )
2590        .unwrap()
2591        .unwrap();
2592
2593        assert_eq!(skipped.crc32, 0);
2594        assert!(skipped.data_decompressed.is_empty());
2595        assert_eq!(skipped.base_object_hash(), Some(supplied_hash));
2596        assert_eq!(offset, reader.get_ref().len());
2597
2598        // A wrong idx name for a skipped object is rejected instead of being emitted.
2599        let mut reader = Cursor::new(reader.into_inner());
2600        let mut offset = 0;
2601        let err = Pack::decode_pack_object_with_crc(
2602            get_hash_kind(),
2603            &mut reader,
2604            &mut offset,
2605            false,
2606            true,
2607            true,
2608            Some(ObjectHash::new(b"known-hash-from-idx")),
2609            None,
2610            Some(&retention),
2611        )
2612        .unwrap_err();
2613        assert!(err.to_string().contains("pack index names it"), "{err}");
2614    }
2615
2616    #[test]
2617    fn test_decode_pack_object_never_skips_delta_payload() {
2618        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2619        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
2620        // Delta header: base size 0x61, result size 0x62, one trailing byte.
2621        encoder.write_all(b"abc").unwrap();
2622        let compressed = encoder.finish().unwrap();
2623
2624        let mut object_data = Vec::new();
2625        object_data.push(0x63);
2626        object_data.push(5);
2627        object_data.extend_from_slice(&compressed);
2628
2629        let supplied_hash = ObjectHash::new(b"known-leaf-delta-hash");
2630        let retention = super::DecodeRetention::default();
2631        let init_offset = 20;
2632        // Low-memory callback mode (`emit_skipped_base_callback`) with an idx name for a leaf
2633        // delta nobody depends on: the payload is still fully decoded and the idx name is kept
2634        // only as a claim to verify after the delta is rebuilt (never emitted unverified).
2635        let mut reader = Cursor::new(object_data.clone());
2636        let mut offset = init_offset;
2637        let delta = Pack::decode_pack_object_with_crc(
2638            get_hash_kind(),
2639            &mut reader,
2640            &mut offset,
2641            true,
2642            true,
2643            true,
2644            Some(supplied_hash),
2645            None,
2646            Some(&retention),
2647        )
2648        .unwrap()
2649        .unwrap();
2650
2651        assert_eq!(delta.data_decompressed, b"abc");
2652        let expected_crc = crc32fast::hash(&object_data);
2653        assert_eq!(delta.crc32, expected_crc);
2654        assert_eq!(delta.known_hash, Some(supplied_hash));
2655        assert!(delta.is_delta_in_pack);
2656
2657        // An idx CRC that does not match the compressed bytes is rejected inside the object
2658        // decoder (so it holds for skipped, base and delta objects alike); the right CRC passes.
2659        for (known_crc, ok) in [(Some(expected_crc ^ 1), false), (Some(expected_crc), true)] {
2660            let mut reader = Cursor::new(object_data.clone());
2661            let mut offset = init_offset;
2662            let result = Pack::decode_pack_object_with_crc(
2663                get_hash_kind(),
2664                &mut reader,
2665                &mut offset,
2666                true,
2667                true,
2668                true,
2669                Some(supplied_hash),
2670                known_crc,
2671                Some(&retention),
2672            );
2673            match result {
2674                Ok(Some(_)) => assert!(ok),
2675                Err(err) => assert!(!ok && err.to_string().contains("CRC32"), "{err}"),
2676                Ok(None) => panic!("delta payload must never be skipped"),
2677            }
2678        }
2679        assert_eq!(
2680            delta.info,
2681            CacheObjectInfo::OffsetDelta(init_offset - 5, 0x62)
2682        );
2683        assert_eq!(offset, init_offset + object_data.len());
2684
2685        // Same for the plain no-callback path (no base-callback emission).
2686        let mut reader = Cursor::new(object_data.clone());
2687        let mut offset = init_offset;
2688        let delta = Pack::decode_pack_object_with_crc(
2689            get_hash_kind(),
2690            &mut reader,
2691            &mut offset,
2692            false,
2693            true,
2694            false,
2695            Some(supplied_hash),
2696            None,
2697            Some(&retention),
2698        )
2699        .unwrap()
2700        .unwrap();
2701        assert_eq!(delta.data_decompressed, b"abc");
2702        assert_eq!(delta.known_hash, Some(supplied_hash));
2703        assert_eq!(offset, init_offset + object_data.len());
2704    }
2705
2706    /// A thin or malformed pack whose delta base never appears — a ref-delta base outside the
2707    /// pack, or an offset-delta pointing at a non-object offset — is a `GitError`, never a panic.
2708    #[test]
2709    fn test_missing_delta_base_fails_closed() {
2710        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2711        let kind = HashKind::Sha1;
2712        let missing_base = ObjectHash::new_for_kind(kind, b"base object not in this pack");
2713        let delta_payload = [b"\x05\x05\x05".as_ref(), b"HELLO"].concat();
2714
2715        // 1) ref-delta whose base is not in the pack.
2716        let mut thin = Vec::new();
2717        thin.extend_from_slice(b"PACK");
2718        thin.extend_from_slice(&2u32.to_be_bytes());
2719        thin.extend_from_slice(&2u32.to_be_bytes());
2720        thin.push(0x35);
2721        append_compressed(&mut thin, b"hello");
2722        thin.push(0x78);
2723        thin.extend_from_slice(missing_base.as_ref());
2724        append_compressed(&mut thin, &delta_payload);
2725        let trailer = ObjectHash::new_for_kind(kind, &thin);
2726        thin.extend_from_slice(trailer.as_ref());
2727
2728        // 2) offset-delta whose base offset points one byte past the blob's object start.
2729        let mut skewed = Vec::new();
2730        skewed.extend_from_slice(b"PACK");
2731        skewed.extend_from_slice(&2u32.to_be_bytes());
2732        skewed.extend_from_slice(&2u32.to_be_bytes());
2733        let blob_offset = skewed.len() as u8;
2734        skewed.push(0x35);
2735        append_compressed(&mut skewed, b"hello");
2736        let delta_offset = skewed.len() as u8;
2737        skewed.push(0x68);
2738        skewed.push(delta_offset - (blob_offset + 1));
2739        append_compressed(&mut skewed, &delta_payload);
2740        let trailer = ObjectHash::new_for_kind(kind, &skewed);
2741        skewed.extend_from_slice(trailer.as_ref());
2742
2743        for (name, pack_data) in [("ref", thin), ("offset", skewed)] {
2744            for with_callback in [false, true] {
2745                let (_tmp_dir, tmp) = pack_test_tmp();
2746                let mut pack = Pack::new_with_hash_kind(kind, Some(1), None, Some(tmp), true);
2747                let result = if with_callback {
2748                    pack.decode(&mut Cursor::new(&pack_data), |_| {}, None::<fn(ObjectHash)>)
2749                } else {
2750                    let (dir, _) = pack_test_tmp();
2751                    let path = dir.path().join(format!("{name}.pack"));
2752                    fs::write(&path, &pack_data).unwrap();
2753                    pack.decode_file_without_callback(&path, None::<fn(ObjectHash)>)
2754                };
2755                let err = result.expect_err("missing delta base must be an error");
2756                assert!(
2757                    err.to_string().contains("not in the pack"),
2758                    "{name} delta (callback={with_callback}): {err}"
2759                );
2760            }
2761        }
2762    }
2763
2764    /// An idx whose entry does not point at its object's real start offset — or that lists one
2765    /// offset twice — is rejected by every file decoder even when names, CRCs and checksums
2766    /// verify: offsets are checked per object, never as a set.
2767    #[test]
2768    fn test_pack_decode_file_rejects_idx_offset_mismatch() {
2769        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2770        let kind = HashKind::Sha1;
2771        let hash_a =
2772            utils::calculate_object_hash_for_kind(kind, ObjectType::Blob, b"hello").unwrap();
2773        let hash_b =
2774            utils::calculate_object_hash_for_kind(kind, ObjectType::Blob, b"world").unwrap();
2775        let mut pack_data = Vec::new();
2776        pack_data.extend_from_slice(b"PACK");
2777        pack_data.extend_from_slice(&2u32.to_be_bytes());
2778        pack_data.extend_from_slice(&2u32.to_be_bytes());
2779        let offset_a = pack_data.len();
2780        pack_data.push(0x35);
2781        append_compressed(&mut pack_data, b"hello");
2782        let offset_b = pack_data.len();
2783        pack_data.push(0x35);
2784        append_compressed(&mut pack_data, b"world");
2785        let trailer = ObjectHash::new_for_kind(kind, &pack_data);
2786        pack_data.extend_from_slice(trailer.as_ref());
2787        let payload_end = pack_data.len() - kind.size();
2788        let crc_a = crc32fast::hash(&pack_data[offset_a..offset_b]);
2789        let crc_b = crc32fast::hash(&pack_data[offset_b..payload_end]);
2790
2791        let dir = tempdir().unwrap();
2792        let pack_path = dir.path().join("offsets.pack");
2793        fs::write(&pack_path, &pack_data).unwrap();
2794        // Names and CRCs are right, but the second entry claims offset 13 (inside the first
2795        // object; the byte there parses as a plausible object header, so the dependency scan
2796        // alone does not notice).
2797        write_test_idx_entries_for_kind(
2798            &pack_path,
2799            vec![(hash_a, offset_a as u32, crc_a), (hash_b, 13, crc_b)],
2800            kind,
2801        );
2802        for (i, with_callback) in [false, true].into_iter().enumerate() {
2803            let mut pack = Pack::new_with_hash_kind(
2804                kind,
2805                Some(1),
2806                None,
2807                Some(dir.path().join(format!("tmp{i}"))),
2808                true,
2809            );
2810            let err = if with_callback {
2811                pack.decode_file(&pack_path, |_| {}, None::<fn(ObjectHash)>)
2812            } else {
2813                pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
2814            }
2815            .unwrap_err();
2816            assert!(
2817                err.to_string().contains(&format!(
2818                    "starts at offset {offset_b} but the pack index records offset 13"
2819                )),
2820                "{err}"
2821            );
2822        }
2823        // The correct idx is accepted.
2824        write_test_idx_for_kind(
2825            &pack_path,
2826            vec![(hash_a, offset_a as u32), (hash_b, offset_b as u32)],
2827            kind,
2828        );
2829        let mut pack =
2830            Pack::new_with_hash_kind(kind, Some(1), None, Some(dir.path().join("tmp-ok")), true);
2831        pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
2832            .unwrap();
2833        assert_eq!(pack.number, 2);
2834        // One offset listed twice is rejected by the shared idx reader.
2835        write_test_idx_entries_for_kind(
2836            &pack_path,
2837            vec![
2838                (hash_a, offset_a as u32, crc_a),
2839                (hash_b, offset_a as u32, crc_b),
2840            ],
2841            kind,
2842        );
2843        let mut pack =
2844            Pack::new_with_hash_kind(kind, Some(1), None, Some(dir.path().join("tmp-dup")), true);
2845        let err = pack
2846            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
2847            .unwrap_err();
2848        assert!(err.to_string().contains("more than once"), "{err}");
2849    }
2850
2851    /// A `.idx` path that exists but cannot be opened (dangling symlink) is an error for the
2852    /// file decoders, never a silent fallback to the no-idx scan path.
2853    #[cfg(unix)]
2854    #[test]
2855    fn test_pack_decode_file_dangling_idx_symlink_fails_closed() {
2856        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2857        let (pack_data, _) = single_blob_pack_for_kind(HashKind::Sha1, b"dangling idx");
2858        let dir = tempdir().unwrap();
2859        let pack_path = dir.path().join("dangling.pack");
2860        fs::write(&pack_path, &pack_data).unwrap();
2861        let idx_path = pack_path.with_extension("idx");
2862        std::os::unix::fs::symlink(dir.path().join("missing.idx"), &idx_path).unwrap();
2863
2864        let mut pack = Pack::new_with_hash_kind(
2865            HashKind::Sha1,
2866            Some(1),
2867            None,
2868            Some(dir.path().join("tmp1")),
2869            true,
2870        );
2871        let err = pack
2872            .decode_file(&pack_path, |_| {}, None::<fn(ObjectHash)>)
2873            .unwrap_err();
2874        assert!(err.to_string().contains("cannot be read"), "{err}");
2875        let mut pack = Pack::new_with_hash_kind(
2876            HashKind::Sha1,
2877            Some(1),
2878            None,
2879            Some(dir.path().join("tmp2")),
2880            true,
2881        );
2882        let err = pack
2883            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
2884            .unwrap_err();
2885        assert!(err.to_string().contains("cannot be read"), "{err}");
2886
2887        // Removing the dangling link restores the (idx-less) scan path.
2888        fs::remove_file(&idx_path).unwrap();
2889        let mut pack = Pack::new_with_hash_kind(
2890            HashKind::Sha1,
2891            Some(1),
2892            None,
2893            Some(dir.path().join("tmp3")),
2894            true,
2895        );
2896        pack.decode_file(&pack_path, |_| {}, None::<fn(ObjectHash)>)
2897            .unwrap();
2898    }
2899
2900    #[test]
2901    fn test_skipped_low_memory_base_callbacks_without_cache_insert() {
2902        let hash = ObjectHash::new(b"known-leaf-base-hash");
2903        let seen = Arc::new(Mutex::new(Vec::new()));
2904        let callback_seen = Arc::clone(&seen);
2905        let callback: super::DecodeCallback = Arc::new(move |entry| {
2906            callback_seen.lock().unwrap().push((
2907                entry.inner.hash,
2908                entry.inner.data.len(),
2909                entry.meta.pack_offset,
2910            ));
2911        });
2912        let (_dir, cache_path) = pack_test_tmp();
2913        let shared_params = Arc::new(super::SharedParams {
2914            pool: Arc::new(ThreadPool::new(1)),
2915            waitlist: Arc::new(Waitlist::new()),
2916            caches: Arc::new(Caches::new(None, cache_path, 1)),
2917            cache_objs_mem_size: Arc::new(AtomicUsize::new(0)),
2918            callback: Some(callback),
2919            retention: Some(Arc::new(super::DecodeRetention::default())),
2920            skip_unneeded_objects: true,
2921            error: Mutex::new(None),
2922        });
2923        let obj = CacheObject {
2924            info: CacheObjectInfo::BaseObject(ObjectType::Blob, hash),
2925            offset: 64,
2926            crc32: 0,
2927            data_decompressed: Vec::new(),
2928            mem_recorder: None,
2929            is_delta_in_pack: false,
2930            known_hash: None,
2931        };
2932
2933        let remaining =
2934            Pack::try_process_skipped_low_memory_callback_object(&shared_params, obj, true);
2935
2936        assert!(remaining.is_none());
2937        assert_eq!(shared_params.caches.total_inserted(), 0);
2938        assert_eq!(seen.lock().unwrap().as_slice(), &[(hash, 0, Some(64))]);
2939    }
2940
2941    #[cfg(unix)]
2942    #[test]
2943    fn test_large_mem_decode_ignores_unrelated_open_pack_fd() {
2944        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2945        let dir = tempdir().unwrap();
2946        let (open_pack_data, open_hash) = single_blob_pack(b"open pack data");
2947        let open_pack_path = dir.path().join("open.pack");
2948        fs::write(&open_pack_path, open_pack_data).unwrap();
2949        write_test_idx(&open_pack_path, vec![(open_hash, 12)]);
2950        let _open_pack = fs::File::open(&open_pack_path).unwrap();
2951
2952        let (reader_pack_data, _) = single_blob_pack(b"reader data");
2953        let mut reader = Cursor::new(reader_pack_data);
2954        let decoded = Arc::new(Mutex::new(Vec::new()));
2955        let decoded_for_callback = Arc::clone(&decoded);
2956        let mut pack = Pack::new(
2957            Some(1),
2958            Some(super::UNBOUNDED_CACHE_THRESHOLD_BYTES),
2959            Some(dir.path().join("tmp")),
2960            true,
2961        );
2962
2963        pack.decode(
2964            &mut reader,
2965            move |entry| decoded_for_callback.lock().unwrap().push(entry.inner.data),
2966            None::<fn(ObjectHash)>,
2967        )
2968        .unwrap();
2969
2970        assert_eq!(*decoded.lock().unwrap(), vec![b"reader data".to_vec()]);
2971    }
2972
2973    #[cfg(unix)]
2974    #[test]
2975    fn test_consume_reader_exact_leaves_following_bytes() {
2976        let mut reader = Cursor::new(b"pack-datafollowing-data".to_vec());
2977        Pack::consume_reader_exact(&mut reader, b"pack-data".len() as u64).unwrap();
2978
2979        let mut rest = Vec::new();
2980        reader.read_to_end(&mut rest).unwrap();
2981        assert_eq!(rest, b"following-data");
2982    }
2983
2984    #[test]
2985    fn test_pack_decode_without_callback_empty_pack() {
2986        let _guard = set_hash_kind_for_test(HashKind::Sha1);
2987        let mut pack_data = Vec::new();
2988        pack_data.extend_from_slice(b"PACK");
2989        pack_data.extend_from_slice(&2u32.to_be_bytes());
2990        pack_data.extend_from_slice(&0u32.to_be_bytes());
2991        let trailer = Sha1::digest(&pack_data);
2992        pack_data.extend_from_slice(&trailer);
2993
2994        let mut reader = Cursor::new(pack_data);
2995        let mut pack = Pack::new(Some(1), None, None, true);
2996        pack.decode_without_callback(&mut reader, None::<fn(ObjectHash)>)
2997            .unwrap();
2998
2999        assert_eq!(pack.number, 0);
3000    }
3001
3002    #[test]
3003    fn test_pack_decode_without_callback_single_blob_pack() {
3004        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3005        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3006        encoder.write_all(b"a").unwrap();
3007        let compressed = encoder.finish().unwrap();
3008
3009        let mut pack_data = Vec::new();
3010        pack_data.extend_from_slice(b"PACK");
3011        pack_data.extend_from_slice(&2u32.to_be_bytes());
3012        pack_data.extend_from_slice(&1u32.to_be_bytes());
3013        pack_data.push(0x31);
3014        pack_data.extend_from_slice(&compressed);
3015        let trailer = Sha1::digest(&pack_data);
3016        pack_data.extend_from_slice(&trailer);
3017
3018        let mut reader = Cursor::new(pack_data);
3019        let mut pack = Pack::new(Some(1), None, None, true);
3020        pack.decode_without_callback(&mut reader, None::<fn(ObjectHash)>)
3021            .unwrap();
3022
3023        assert_eq!(pack.number, 1);
3024        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3025    }
3026
3027    #[test]
3028    fn test_pack_decode_large_mem_limit_uses_temp_retention_path() {
3029        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3030        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3031        encoder.write_all(b"a").unwrap();
3032        let compressed = encoder.finish().unwrap();
3033
3034        let mut pack_data = Vec::new();
3035        pack_data.extend_from_slice(b"PACK");
3036        pack_data.extend_from_slice(&2u32.to_be_bytes());
3037        pack_data.extend_from_slice(&1u32.to_be_bytes());
3038        pack_data.push(0x31);
3039        pack_data.extend_from_slice(&compressed);
3040        let trailer = Sha1::digest(&pack_data);
3041        pack_data.extend_from_slice(&trailer);
3042
3043        let seen = Arc::new(Mutex::new(Vec::new()));
3044        let seen_cb = Arc::clone(&seen);
3045        let mut reader = Cursor::new(pack_data);
3046        let mut pack = Pack::new(
3047            Some(1),
3048            Some(super::UNBOUNDED_CACHE_THRESHOLD_BYTES),
3049            None,
3050            true,
3051        );
3052        pack.decode(
3053            &mut reader,
3054            move |entry| seen_cb.lock().unwrap().push(entry.inner.data),
3055            None::<fn(ObjectHash)>,
3056        )
3057        .unwrap();
3058
3059        assert_eq!(pack.number, 1);
3060        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3061        assert_eq!(*seen.lock().unwrap(), vec![b"a".to_vec()]);
3062    }
3063
3064    #[test]
3065    fn test_pack_decode_file_without_callback_uses_idx() {
3066        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3067        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3068        encoder.write_all(b"a").unwrap();
3069        let compressed = encoder.finish().unwrap();
3070
3071        let mut pack_data = Vec::new();
3072        pack_data.extend_from_slice(b"PACK");
3073        pack_data.extend_from_slice(&2u32.to_be_bytes());
3074        pack_data.extend_from_slice(&1u32.to_be_bytes());
3075        pack_data.push(0x31);
3076        pack_data.extend_from_slice(&compressed);
3077        let trailer = Sha1::digest(&pack_data);
3078        pack_data.extend_from_slice(&trailer);
3079
3080        let dir = tempdir().unwrap();
3081        let pack_path = dir.path().join("single.pack");
3082        fs::write(&pack_path, &pack_data).unwrap();
3083
3084        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3085        let mut idx_data = Vec::new();
3086        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3087        idx_data.extend_from_slice(&2u32.to_be_bytes());
3088        let first = obj_hash.as_ref()[0] as usize;
3089        for fanout_idx in 0..256 {
3090            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3091            idx_data.extend_from_slice(&count.to_be_bytes());
3092        }
3093        idx_data.extend_from_slice(obj_hash.as_ref());
3094        // Real CRC32 of the object's compressed pack bytes (idx CRCs are verified).
3095        idx_data.extend_from_slice(
3096            &crc32fast::hash(&pack_data[12..pack_data.len() - 20]).to_be_bytes(),
3097        );
3098        idx_data.extend_from_slice(&12u32.to_be_bytes());
3099        append_test_idx_trailer(&mut idx_data, &trailer);
3100        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3101
3102        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3103        pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3104            .unwrap();
3105
3106        assert_eq!(pack.number, 1);
3107        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3108    }
3109
3110    #[test]
3111    fn test_pack_decode_file_callback_uses_idx_and_crc() {
3112        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3113        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3114        encoder.write_all(b"a").unwrap();
3115        let compressed = encoder.finish().unwrap();
3116
3117        let mut object_data = Vec::new();
3118        object_data.push(0x31);
3119        object_data.extend_from_slice(&compressed);
3120        let expected_crc = crc32fast::hash(&object_data);
3121
3122        let mut pack_data = Vec::new();
3123        pack_data.extend_from_slice(b"PACK");
3124        pack_data.extend_from_slice(&2u32.to_be_bytes());
3125        pack_data.extend_from_slice(&1u32.to_be_bytes());
3126        pack_data.extend_from_slice(&object_data);
3127        let trailer = Sha1::digest(&pack_data);
3128        pack_data.extend_from_slice(&trailer);
3129
3130        let dir = tempdir().unwrap();
3131        let pack_path = dir.path().join("single-callback.pack");
3132        fs::write(&pack_path, &pack_data).unwrap();
3133
3134        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3135        let mut idx_data = Vec::new();
3136        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3137        idx_data.extend_from_slice(&2u32.to_be_bytes());
3138        let first = obj_hash.as_ref()[0] as usize;
3139        for fanout_idx in 0..256 {
3140            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3141            idx_data.extend_from_slice(&count.to_be_bytes());
3142        }
3143        idx_data.extend_from_slice(obj_hash.as_ref());
3144        idx_data.extend_from_slice(&expected_crc.to_be_bytes());
3145        idx_data.extend_from_slice(&12u32.to_be_bytes());
3146        append_test_idx_trailer(&mut idx_data, &trailer);
3147        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3148
3149        let entries = Arc::new(std::sync::Mutex::new(Vec::new()));
3150        let entries_for_cb = Arc::clone(&entries);
3151        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3152        pack.decode_file(
3153            &pack_path,
3154            move |entry| entries_for_cb.lock().unwrap().push(entry),
3155            None::<fn(ObjectHash)>,
3156        )
3157        .unwrap();
3158
3159        let entries = Arc::try_unwrap(entries).unwrap().into_inner().unwrap();
3160        assert_eq!(entries.len(), 1);
3161        assert_eq!(entries[0].inner.hash, obj_hash);
3162        assert_eq!(entries[0].inner.data, b"a");
3163        assert_eq!(entries[0].meta.pack_offset, Some(12));
3164        assert_eq!(entries[0].meta.crc32, Some(expected_crc));
3165        assert_eq!(pack.number, 1);
3166        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3167    }
3168
3169    #[test]
3170    fn test_pack_decode_file_callback_rejects_idx_with_bad_checksum() {
3171        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3172        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3173        encoder.write_all(b"a").unwrap();
3174        let compressed = encoder.finish().unwrap();
3175
3176        let mut pack_data = Vec::new();
3177        pack_data.extend_from_slice(b"PACK");
3178        pack_data.extend_from_slice(&2u32.to_be_bytes());
3179        pack_data.extend_from_slice(&1u32.to_be_bytes());
3180        pack_data.push(0x31);
3181        pack_data.extend_from_slice(&compressed);
3182        let trailer = Sha1::digest(&pack_data);
3183        pack_data.extend_from_slice(&trailer);
3184
3185        let dir = tempdir().unwrap();
3186        let pack_path = dir.path().join("bad-idx-checksum.pack");
3187        fs::write(&pack_path, &pack_data).unwrap();
3188
3189        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3190        let mut idx_data = Vec::new();
3191        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3192        idx_data.extend_from_slice(&2u32.to_be_bytes());
3193        let first = obj_hash.as_ref()[0] as usize;
3194        for fanout_idx in 0..256 {
3195            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3196            idx_data.extend_from_slice(&count.to_be_bytes());
3197        }
3198        let hash_offset = idx_data.len();
3199        idx_data.extend_from_slice(obj_hash.as_ref());
3200        // Real CRC32 of the object's compressed pack bytes (idx CRCs are verified).
3201        idx_data.extend_from_slice(
3202            &crc32fast::hash(&pack_data[12..pack_data.len() - 20]).to_be_bytes(),
3203        );
3204        idx_data.extend_from_slice(&12u32.to_be_bytes());
3205        append_test_idx_trailer(&mut idx_data, &trailer);
3206        idx_data[hash_offset] ^= 0xff;
3207        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3208
3209        // A corrupt idx next to the pack is an error (fail-closed), not a silent full rescan.
3210        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3211        let err = pack
3212            .decode_file(&pack_path, |_| {}, None::<fn(ObjectHash)>)
3213            .unwrap_err();
3214        // Either the corrupted name trips the fanout/name validation or the checksum check.
3215        let msg = err.to_string();
3216        assert!(
3217            msg.contains("Pack index") || msg.contains("checksum"),
3218            "{msg}"
3219        );
3220
3221        // Removing the corrupt idx restores the scan path and yields the object.
3222        fs::remove_file(pack_path.with_extension("idx")).unwrap();
3223        let entries = Arc::new(std::sync::Mutex::new(Vec::new()));
3224        let entries_for_cb = Arc::clone(&entries);
3225        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp2")), true);
3226        pack.decode_file(
3227            &pack_path,
3228            move |entry| entries_for_cb.lock().unwrap().push(entry.inner.hash),
3229            None::<fn(ObjectHash)>,
3230        )
3231        .unwrap();
3232        assert_eq!(entries.lock().unwrap().as_slice(), &[obj_hash]);
3233    }
3234
3235    #[test]
3236    fn test_pack_decode_file_full_without_callback_uses_idx() {
3237        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3238        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3239        encoder.write_all(b"a").unwrap();
3240        let compressed = encoder.finish().unwrap();
3241
3242        let mut pack_data = Vec::new();
3243        pack_data.extend_from_slice(b"PACK");
3244        pack_data.extend_from_slice(&2u32.to_be_bytes());
3245        pack_data.extend_from_slice(&1u32.to_be_bytes());
3246        pack_data.push(0x31);
3247        pack_data.extend_from_slice(&compressed);
3248        let trailer = Sha1::digest(&pack_data);
3249        pack_data.extend_from_slice(&trailer);
3250
3251        let dir = tempdir().unwrap();
3252        let pack_path = dir.path().join("single-full-no-callback.pack");
3253        fs::write(&pack_path, &pack_data).unwrap();
3254
3255        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3256        let mut idx_data = Vec::new();
3257        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3258        idx_data.extend_from_slice(&2u32.to_be_bytes());
3259        let first = obj_hash.as_ref()[0] as usize;
3260        for fanout_idx in 0..256 {
3261            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3262            idx_data.extend_from_slice(&count.to_be_bytes());
3263        }
3264        idx_data.extend_from_slice(obj_hash.as_ref());
3265        // Real CRC32 of the object's compressed pack bytes (idx CRCs are verified).
3266        idx_data.extend_from_slice(
3267            &crc32fast::hash(&pack_data[12..pack_data.len() - 20]).to_be_bytes(),
3268        );
3269        idx_data.extend_from_slice(&12u32.to_be_bytes());
3270        append_test_idx_trailer(&mut idx_data, &trailer);
3271        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3272
3273        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3274        pack.decode_file_full_without_callback(&pack_path, None::<fn(ObjectHash)>)
3275            .unwrap();
3276
3277        assert_eq!(pack.number, 1);
3278        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3279    }
3280
3281    #[test]
3282    fn test_pack_decode_file_full_without_callback_uses_idx_large_offset() {
3283        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3284        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3285        encoder.write_all(b"a").unwrap();
3286        let compressed = encoder.finish().unwrap();
3287
3288        let mut pack_data = Vec::new();
3289        pack_data.extend_from_slice(b"PACK");
3290        pack_data.extend_from_slice(&2u32.to_be_bytes());
3291        pack_data.extend_from_slice(&1u32.to_be_bytes());
3292        pack_data.push(0x31);
3293        pack_data.extend_from_slice(&compressed);
3294        let trailer = Sha1::digest(&pack_data);
3295        pack_data.extend_from_slice(&trailer);
3296
3297        let dir = tempdir().unwrap();
3298        let pack_path = dir.path().join("single-full-no-callback-large-offset.pack");
3299        fs::write(&pack_path, &pack_data).unwrap();
3300
3301        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3302        let mut idx_data = Vec::new();
3303        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3304        idx_data.extend_from_slice(&2u32.to_be_bytes());
3305        let first = obj_hash.as_ref()[0] as usize;
3306        for fanout_idx in 0..256 {
3307            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3308            idx_data.extend_from_slice(&count.to_be_bytes());
3309        }
3310        idx_data.extend_from_slice(obj_hash.as_ref());
3311        // Real CRC32 of the object's compressed pack bytes (idx CRCs are verified).
3312        idx_data.extend_from_slice(
3313            &crc32fast::hash(&pack_data[12..pack_data.len() - 20]).to_be_bytes(),
3314        );
3315        idx_data.extend_from_slice(&0x8000_0000u32.to_be_bytes());
3316        idx_data.extend_from_slice(&12u64.to_be_bytes());
3317        append_test_idx_trailer(&mut idx_data, &trailer);
3318        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3319
3320        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3321        pack.decode_file_full_without_callback(&pack_path, None::<fn(ObjectHash)>)
3322            .unwrap();
3323
3324        assert_eq!(pack.number, 1);
3325        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3326    }
3327
3328    #[test]
3329    fn test_pack_decode_file_without_callback_falls_back_without_idx() {
3330        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3331        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3332        encoder.write_all(b"a").unwrap();
3333        let compressed = encoder.finish().unwrap();
3334
3335        let mut pack_data = Vec::new();
3336        pack_data.extend_from_slice(b"PACK");
3337        pack_data.extend_from_slice(&2u32.to_be_bytes());
3338        pack_data.extend_from_slice(&1u32.to_be_bytes());
3339        pack_data.push(0x31);
3340        pack_data.extend_from_slice(&compressed);
3341        let trailer = Sha1::digest(&pack_data);
3342        pack_data.extend_from_slice(&trailer);
3343
3344        let dir = tempdir().unwrap();
3345        let pack_path = dir.path().join("single-no-idx.pack");
3346        fs::write(&pack_path, &pack_data).unwrap();
3347
3348        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3349        pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3350            .unwrap();
3351
3352        assert_eq!(pack.number, 1);
3353        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
3354    }
3355
3356    #[test]
3357    fn test_pack_decode_file_without_callback_rejects_idx_pack_hash_mismatch() {
3358        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3359        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3360        encoder.write_all(b"a").unwrap();
3361        let compressed = encoder.finish().unwrap();
3362
3363        let mut pack_data = Vec::new();
3364        pack_data.extend_from_slice(b"PACK");
3365        pack_data.extend_from_slice(&2u32.to_be_bytes());
3366        pack_data.extend_from_slice(&1u32.to_be_bytes());
3367        pack_data.push(0x31);
3368        pack_data.extend_from_slice(&compressed);
3369        let trailer = Sha1::digest(&pack_data);
3370        pack_data.extend_from_slice(&trailer);
3371
3372        let dir = tempdir().unwrap();
3373        let pack_path = dir.path().join("bad-pack-hash.pack");
3374        fs::write(&pack_path, &pack_data).unwrap();
3375
3376        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3377        let mut idx_data = Vec::new();
3378        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3379        idx_data.extend_from_slice(&2u32.to_be_bytes());
3380        let first = obj_hash.as_ref()[0] as usize;
3381        for fanout_idx in 0..256 {
3382            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3383            idx_data.extend_from_slice(&count.to_be_bytes());
3384        }
3385        idx_data.extend_from_slice(obj_hash.as_ref());
3386        // Real CRC32 of the object's compressed pack bytes (idx CRCs are verified).
3387        idx_data.extend_from_slice(
3388            &crc32fast::hash(&pack_data[12..pack_data.len() - 20]).to_be_bytes(),
3389        );
3390        idx_data.extend_from_slice(&12u32.to_be_bytes());
3391        append_test_idx_trailer(&mut idx_data, &[0xff; 20]);
3392        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3393
3394        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3395        let err = pack
3396            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3397            .unwrap_err();
3398
3399        assert!(err.to_string().contains("does not match the trailer hash"));
3400    }
3401
3402    #[test]
3403    fn test_pack_decode_file_full_without_callback_rejects_stale_idx_after_pack_change() {
3404        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3405
3406        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3407        encoder.write_all(b"a").unwrap();
3408        let original_compressed = encoder.finish().unwrap();
3409
3410        let mut original_pack_data = Vec::new();
3411        original_pack_data.extend_from_slice(b"PACK");
3412        original_pack_data.extend_from_slice(&2u32.to_be_bytes());
3413        original_pack_data.extend_from_slice(&1u32.to_be_bytes());
3414        original_pack_data.push(0x31);
3415        original_pack_data.extend_from_slice(&original_compressed);
3416        let original_trailer = Sha1::digest(&original_pack_data);
3417
3418        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3419        encoder.write_all(b"b").unwrap();
3420        let changed_compressed = encoder.finish().unwrap();
3421        assert_eq!(original_compressed.len(), changed_compressed.len());
3422
3423        let mut changed_pack_data = Vec::new();
3424        changed_pack_data.extend_from_slice(b"PACK");
3425        changed_pack_data.extend_from_slice(&2u32.to_be_bytes());
3426        changed_pack_data.extend_from_slice(&1u32.to_be_bytes());
3427        changed_pack_data.push(0x31);
3428        changed_pack_data.extend_from_slice(&changed_compressed);
3429        changed_pack_data.extend_from_slice(&original_trailer);
3430
3431        let dir = tempdir().unwrap();
3432        let pack_path = dir.path().join("stale-idx.pack");
3433        fs::write(&pack_path, &changed_pack_data).unwrap();
3434
3435        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, b"a");
3436        let mut idx_data = Vec::new();
3437        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3438        idx_data.extend_from_slice(&2u32.to_be_bytes());
3439        let first = obj_hash.as_ref()[0] as usize;
3440        for fanout_idx in 0..256 {
3441            let count = if fanout_idx >= first { 1u32 } else { 0u32 };
3442            idx_data.extend_from_slice(&count.to_be_bytes());
3443        }
3444        idx_data.extend_from_slice(obj_hash.as_ref());
3445        // Real CRC32 of the object's compressed pack bytes (idx CRCs are verified).
3446        idx_data.extend_from_slice(
3447            &crc32fast::hash(&changed_pack_data[12..changed_pack_data.len() - 20]).to_be_bytes(),
3448        );
3449        idx_data.extend_from_slice(&12u32.to_be_bytes());
3450        append_test_idx_trailer(&mut idx_data, &original_trailer);
3451        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3452
3453        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
3454        let err = pack
3455            .decode_file_full_without_callback(&pack_path, None::<fn(ObjectHash)>)
3456            .unwrap_err();
3457
3458        // The stale idx is rejected fail-closed: either its object names no longer match the
3459        // changed pack content, or its recorded pack hash disagrees with the trailer.
3460        let msg = err.to_string();
3461        assert!(
3462            msg.contains("pack index names it") || msg.contains("does not match the trailer hash"),
3463            "{msg}"
3464        );
3465    }
3466
3467    fn append_compressed(buf: &mut Vec<u8>, data: &[u8]) {
3468        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
3469        encoder.write_all(data).unwrap();
3470        buf.extend_from_slice(&encoder.finish().unwrap());
3471    }
3472
3473    fn single_blob_pack(data: &[u8]) -> (Vec<u8>, ObjectHash) {
3474        let obj_hash = utils::calculate_object_hash(ObjectType::Blob, data);
3475        let mut pack_data = Vec::new();
3476        pack_data.extend_from_slice(b"PACK");
3477        pack_data.extend_from_slice(&2u32.to_be_bytes());
3478        pack_data.extend_from_slice(&1u32.to_be_bytes());
3479        pack_data.push(0x30 | data.len() as u8);
3480        append_compressed(&mut pack_data, data);
3481        let trailer = Sha1::digest(&pack_data);
3482        pack_data.extend_from_slice(&trailer);
3483        (pack_data, obj_hash)
3484    }
3485
3486    fn append_test_idx_trailer(idx_data: &mut Vec<u8>, pack_hash: &[u8]) {
3487        append_test_idx_trailer_for_kind(idx_data, pack_hash, get_hash_kind());
3488    }
3489
3490    fn append_test_idx_trailer_for_kind(idx_data: &mut Vec<u8>, pack_hash: &[u8], kind: HashKind) {
3491        idx_data.extend_from_slice(pack_hash);
3492        let mut idx_hash = crate::utils::HashAlgorithm::new_for_kind(kind);
3493        idx_hash.update(idx_data);
3494        idx_data.extend_from_slice(&idx_hash.finalize());
3495    }
3496
3497    /// Build a single-blob pack whose object ID and trailer use an explicit `kind`.
3498    fn single_blob_pack_for_kind(kind: HashKind, data: &[u8]) -> (Vec<u8>, ObjectHash) {
3499        let obj_hash = utils::calculate_object_hash_for_kind(kind, ObjectType::Blob, data).unwrap();
3500        let mut pack_data = Vec::new();
3501        pack_data.extend_from_slice(b"PACK");
3502        pack_data.extend_from_slice(&2u32.to_be_bytes());
3503        pack_data.extend_from_slice(&1u32.to_be_bytes());
3504        pack_data.push(0x30 | data.len() as u8);
3505        append_compressed(&mut pack_data, data);
3506        let trailer = ObjectHash::new_for_kind(kind, &pack_data);
3507        pack_data.extend_from_slice(trailer.as_ref());
3508        (pack_data, obj_hash)
3509    }
3510
3511    fn write_test_idx(pack_path: &Path, objects: Vec<(ObjectHash, u32)>) {
3512        write_test_idx_for_kind(pack_path, objects, get_hash_kind());
3513    }
3514
3515    fn write_test_idx_for_kind(pack_path: &Path, objects: Vec<(ObjectHash, u32)>, kind: HashKind) {
3516        // Real CRC32 of each object's compressed pack bytes (object spans run to the next
3517        // object's offset, or to the trailer for the last one).
3518        let pack_data = fs::read(pack_path).unwrap();
3519        let hash_size = kind.size();
3520        let mut spans: Vec<u32> = objects.iter().map(|(_, off)| *off).collect();
3521        spans.push((pack_data.len() - hash_size) as u32);
3522        spans.sort_unstable();
3523        let entries = objects
3524            .into_iter()
3525            .map(|(hash, offset)| {
3526                let end = spans.iter().copied().find(|s| *s > offset).unwrap();
3527                let crc = crc32fast::hash(&pack_data[offset as usize..end as usize]);
3528                (hash, offset, crc)
3529            })
3530            .collect();
3531        write_test_idx_entries_for_kind(pack_path, entries, kind);
3532    }
3533
3534    /// Write an idx v2 with explicit `(name, offset, crc32)` entries (checksums sealed).
3535    fn write_test_idx_entries_for_kind(
3536        pack_path: &Path,
3537        mut objects: Vec<(ObjectHash, u32, u32)>,
3538        kind: HashKind,
3539    ) {
3540        objects.sort_by(|a, b| a.0.as_ref().cmp(b.0.as_ref()));
3541        let pack_data = fs::read(pack_path).unwrap();
3542        let hash_size = kind.size();
3543        let mut idx_data = Vec::new();
3544        idx_data.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
3545        idx_data.extend_from_slice(&2u32.to_be_bytes());
3546        for fanout_idx in 0..256 {
3547            let count = objects
3548                .iter()
3549                .filter(|(hash, _, _)| hash.as_ref()[0] as usize <= fanout_idx)
3550                .count() as u32;
3551            idx_data.extend_from_slice(&count.to_be_bytes());
3552        }
3553        for (hash, _, _) in &objects {
3554            idx_data.extend_from_slice(hash.as_ref());
3555        }
3556        for (_, _, crc) in &objects {
3557            idx_data.extend_from_slice(&crc.to_be_bytes());
3558        }
3559        for (_, offset, _) in &objects {
3560            idx_data.extend_from_slice(&offset.to_be_bytes());
3561        }
3562        append_test_idx_trailer_for_kind(
3563            &mut idx_data,
3564            &pack_data[pack_data.len() - hash_size..],
3565            kind,
3566        );
3567        fs::write(pack_path.with_extension("idx"), idx_data).unwrap();
3568    }
3569
3570    /// Non-seekable, read-once byte source that counts every byte handed out.
3571    struct CountingOnce<'a> {
3572        data: &'a [u8],
3573        pos: usize,
3574        counter: Arc<AtomicUsize>,
3575    }
3576    impl Read for CountingOnce<'_> {
3577        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
3578            let n = buf.len().min(self.data.len() - self.pos);
3579            buf[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
3580            self.pos += n;
3581            self.counter.fetch_add(n, Ordering::SeqCst);
3582            Ok(n)
3583        }
3584    }
3585
3586    /// Hand-built BLAKE3 pack: base blob, offset delta and ref delta (32-byte BLAKE3 base ID),
3587    /// with a BLAKE3 trailer. Returns the bytes and the three expected object IDs.
3588    fn blake3_ref_delta_pack() -> (Vec<u8>, [ObjectHash; 3], [u32; 3]) {
3589        let kind = HashKind::Blake3;
3590        let base_hash =
3591            utils::calculate_object_hash_for_kind(kind, ObjectType::Blob, b"hello").unwrap();
3592        let ofs_hash =
3593            utils::calculate_object_hash_for_kind(kind, ObjectType::Blob, b"hi there").unwrap();
3594        let ref_hash =
3595            utils::calculate_object_hash_for_kind(kind, ObjectType::Blob, b"HELLO").unwrap();
3596        assert!(
3597            [base_hash, ofs_hash, ref_hash]
3598                .iter()
3599                .all(|h| h.kind() == kind)
3600        );
3601
3602        let mut pack_data = Vec::new();
3603        pack_data.extend_from_slice(b"PACK");
3604        pack_data.extend_from_slice(&2u32.to_be_bytes());
3605        pack_data.extend_from_slice(&3u32.to_be_bytes());
3606
3607        let base_offset = pack_data.len() as u32;
3608        pack_data.push(0x35);
3609        append_compressed(&mut pack_data, b"hello");
3610
3611        let ofs_offset = pack_data.len() as u32;
3612        pack_data.push(0x6b);
3613        pack_data.push((ofs_offset - base_offset) as u8);
3614        append_compressed(
3615            &mut pack_data,
3616            [b"\x05\x08\x08".as_ref(), b"hi there"].concat().as_slice(),
3617        );
3618
3619        let ref_offset = pack_data.len() as u32;
3620        pack_data.push(0x78);
3621        pack_data.extend_from_slice(base_hash.as_ref()); // 32-byte BLAKE3 base ID
3622        assert_eq!(base_hash.as_ref().len(), 32);
3623        append_compressed(
3624            &mut pack_data,
3625            [b"\x05\x05\x05".as_ref(), b"HELLO"].concat().as_slice(),
3626        );
3627
3628        let trailer = ObjectHash::new_for_kind(kind, &pack_data);
3629        pack_data.extend_from_slice(trailer.as_ref());
3630        (
3631            pack_data,
3632            [base_hash, ofs_hash, ref_hash],
3633            [base_offset, ofs_offset, ref_offset],
3634        )
3635    }
3636
3637    /// A BLAKE3 pack without deltas decodes through an explicit-kind `Pack` while the
3638    /// thread-local kind is SHA-1; the signature and object ID are `ObjectHash::Blake3`, and
3639    /// a SHA-256 `Pack` rejects the same bytes.
3640    #[test]
3641    fn blake3_no_delta() {
3642        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3643        let (pack_data, obj_hash) = single_blob_pack_for_kind(HashKind::Blake3, b"blake3 blob");
3644        assert_eq!(obj_hash.kind(), HashKind::Blake3);
3645        let trailer =
3646            ObjectHash::from_bytes_for_kind(HashKind::Blake3, &pack_data[pack_data.len() - 32..])
3647                .unwrap();
3648
3649        let (_tmp_dir, tmp) = pack_test_tmp();
3650        let mut pack = Pack::new_with_hash_kind(
3651            HashKind::Blake3,
3652            Some(1),
3653            Some(1024 * 1024),
3654            Some(tmp),
3655            true,
3656        );
3657        assert_eq!(pack.hash_kind, HashKind::Blake3);
3658        assert_eq!(pack.signature, ObjectHash::zero_for_kind(HashKind::Blake3));
3659        let seen = Arc::new(Mutex::new(Vec::new()));
3660        let sink = seen.clone();
3661        pack.decode(
3662            &mut Cursor::new(&pack_data),
3663            move |entry| sink.lock().unwrap().push(entry.inner.hash),
3664            None::<fn(ObjectHash)>,
3665        )
3666        .unwrap();
3667        assert_eq!(pack.number, 1);
3668        assert_eq!(pack.signature, trailer);
3669        assert_eq!(pack.signature.kind(), HashKind::Blake3);
3670        assert_eq!(seen.lock().unwrap().as_slice(), &[obj_hash]);
3671
3672        // Legacy `Pack::new` follows the thread-local (SHA-1) kind and therefore fails.
3673        let (_tmp_dir2, tmp2) = pack_test_tmp();
3674        let mut legacy = Pack::new(Some(1), Some(1024 * 1024), Some(tmp2), true);
3675        assert_eq!(legacy.hash_kind, HashKind::Sha1);
3676        assert!(
3677            legacy
3678                .decode(&mut Cursor::new(&pack_data), |_| {}, None::<fn(ObjectHash)>)
3679                .is_err()
3680        );
3681
3682        // Partial file decode: a checksum-valid idx naming the (skipped) leaf blob wrongly is
3683        // rejected; the correct idx is accepted.
3684        let dir = tempdir().unwrap();
3685        let pack_path = dir.path().join("blake3-leaf.pack");
3686        fs::write(&pack_path, &pack_data).unwrap();
3687        write_test_idx_for_kind(
3688            &pack_path,
3689            vec![(
3690                ObjectHash::new_for_kind(HashKind::Blake3, b"wrong name"),
3691                12,
3692            )],
3693            HashKind::Blake3,
3694        );
3695        let mut partial = Pack::new_with_hash_kind(
3696            HashKind::Blake3,
3697            Some(1),
3698            None,
3699            Some(dir.path().join("t1")),
3700            true,
3701        );
3702        let err = partial
3703            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3704            .unwrap_err();
3705        assert!(err.to_string().contains("pack index names it"), "{err}");
3706        write_test_idx_for_kind(&pack_path, vec![(obj_hash, 12)], HashKind::Blake3);
3707        let mut partial = Pack::new_with_hash_kind(
3708            HashKind::Blake3,
3709            Some(1),
3710            None,
3711            Some(dir.path().join("t2")),
3712            true,
3713        );
3714        partial
3715            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3716            .unwrap();
3717        assert_eq!(partial.signature, trailer);
3718
3719        // Same width, different algorithm: a SHA-256 pack must not accept a BLAKE3 trailer.
3720        let (_tmp_dir3, tmp3) = pack_test_tmp();
3721        let mut sha256 = Pack::new_with_hash_kind(
3722            HashKind::Sha256,
3723            Some(1),
3724            Some(1024 * 1024),
3725            Some(tmp3),
3726            true,
3727        );
3728        let err = sha256
3729            .decode(&mut Cursor::new(&pack_data), |_| {}, None::<fn(ObjectHash)>)
3730            .unwrap_err();
3731        assert!(
3732            err.to_string().contains("does not match the trailer hash"),
3733            "{err}"
3734        );
3735    }
3736
3737    /// Ref-delta bases are read as 32-byte BLAKE3 IDs and resolved by BLAKE3 identity; both
3738    /// the streaming decoder and the idx-backed file decoder agree on the three object IDs.
3739    #[test]
3740    fn blake3_ref_delta() {
3741        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3742        let (pack_data, [base_hash, ofs_hash, ref_hash], [base_offset, ofs_offset, ref_offset]) =
3743            blake3_ref_delta_pack();
3744        let trailer =
3745            ObjectHash::from_bytes_for_kind(HashKind::Blake3, &pack_data[pack_data.len() - 32..])
3746                .unwrap();
3747
3748        // Streaming decode with callbacks.
3749        let (_tmp_dir, tmp) = pack_test_tmp();
3750        let mut pack = Pack::new_with_hash_kind(HashKind::Blake3, Some(1), None, Some(tmp), true);
3751        let seen = Arc::new(Mutex::new(Vec::new()));
3752        let sink = seen.clone();
3753        pack.decode(
3754            &mut Cursor::new(&pack_data),
3755            move |entry| {
3756                sink.lock()
3757                    .unwrap()
3758                    .push((entry.inner.hash, entry.inner.data.clone()))
3759            },
3760            None::<fn(ObjectHash)>,
3761        )
3762        .unwrap();
3763        assert_eq!(pack.number, 3);
3764        assert_eq!(pack.signature, trailer);
3765        let seen = seen.lock().unwrap();
3766        let by_hash: std::collections::HashMap<ObjectHash, Vec<u8>> =
3767            seen.iter().cloned().collect();
3768        assert_eq!(by_hash.len(), 3);
3769        assert_eq!(by_hash[&base_hash], b"hello");
3770        assert_eq!(by_hash[&ofs_hash], b"hi there");
3771        assert_eq!(by_hash[&ref_hash], b"HELLO");
3772        assert!(by_hash.keys().all(|h| h.kind() == HashKind::Blake3));
3773
3774        // File decode backed by a BLAKE3 idx v2.
3775        let dir = tempdir().unwrap();
3776        let pack_path = dir.path().join("blake3-delta.pack");
3777        fs::write(&pack_path, &pack_data).unwrap();
3778        write_test_idx_for_kind(
3779            &pack_path,
3780            vec![
3781                (base_hash, base_offset),
3782                (ofs_hash, ofs_offset),
3783                (ref_hash, ref_offset),
3784            ],
3785            HashKind::Blake3,
3786        );
3787        let mut pack = Pack::new_with_hash_kind(
3788            HashKind::Blake3,
3789            Some(1),
3790            None,
3791            Some(dir.path().join("tmp")),
3792            true,
3793        );
3794        pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3795            .unwrap();
3796        assert_eq!(pack.number, 3);
3797        assert_eq!(pack.signature, trailer);
3798
3799        // A checksum-valid idx whose object names are wrong is rejected (object/index mismatch).
3800        let bogus = ObjectHash::new_for_kind(HashKind::Blake3, b"not the base");
3801        write_test_idx_for_kind(
3802            &pack_path,
3803            vec![
3804                (bogus, base_offset),
3805                (ofs_hash, ofs_offset),
3806                (ref_hash, ref_offset),
3807            ],
3808            HashKind::Blake3,
3809        );
3810        let mut pack = Pack::new_with_hash_kind(
3811            HashKind::Blake3,
3812            Some(1),
3813            None,
3814            Some(dir.path().join("tmp3")),
3815            true,
3816        );
3817        let err = pack
3818            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3819            .unwrap_err();
3820        assert!(err.to_string().contains("pack index names it"), "{err}");
3821        // A checksum-valid idx naming the *leaf delta* wrongly is rejected too: deltas are always
3822        // rebuilt (never skipped) so their names are verified.
3823        let bogus_leaf = ObjectHash::new_for_kind(HashKind::Blake3, b"not the leaf");
3824        write_test_idx_for_kind(
3825            &pack_path,
3826            vec![
3827                (base_hash, base_offset),
3828                (ofs_hash, ofs_offset),
3829                (bogus_leaf, ref_offset),
3830            ],
3831            HashKind::Blake3,
3832        );
3833        let mut pack = Pack::new_with_hash_kind(
3834            HashKind::Blake3,
3835            Some(1),
3836            None,
3837            Some(dir.path().join("tmp5")),
3838            true,
3839        );
3840        let err = pack
3841            .decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3842            .unwrap_err();
3843        assert!(err.to_string().contains("pack index names it"), "{err}");
3844        // An idx with correct names but a wrong CRC for one object is rejected by the
3845        // CRC-tracking (callback) decode.
3846        write_test_idx_for_kind(
3847            &pack_path,
3848            vec![
3849                (base_hash, base_offset),
3850                (ofs_hash, ofs_offset),
3851                (ref_hash, ref_offset),
3852            ],
3853            HashKind::Blake3,
3854        );
3855        let idx_path = pack_path.with_extension("idx");
3856        let mut idx_bytes = fs::read(&idx_path).unwrap();
3857        let crc_start = 8 + 256 * 4 + 3 * 32;
3858        idx_bytes[crc_start] ^= 0xff;
3859        // re-seal the idx checksum so only the CRC is wrong
3860        let hs = 32;
3861        let body_len = idx_bytes.len() - hs;
3862        let mut hasher = crate::utils::HashAlgorithm::new_for_kind(HashKind::Blake3);
3863        hasher.update(&idx_bytes[..body_len]);
3864        let reseal = hasher.finalize_object_hash();
3865        idx_bytes[body_len..].copy_from_slice(reseal.as_ref());
3866        fs::write(&idx_path, &idx_bytes).unwrap();
3867        let mut pack = Pack::new_with_hash_kind(
3868            HashKind::Blake3,
3869            Some(1),
3870            None,
3871            Some(dir.path().join("tmp6")),
3872            true,
3873        );
3874        let err = pack
3875            .decode_file(&pack_path, |_| {}, None::<fn(ObjectHash)>)
3876            .unwrap_err();
3877        assert!(err.to_string().contains("CRC32"), "{err}");
3878        // A SHA-256 idx (wrong kind, same width) for the BLAKE3 pack is rejected too.
3879        write_test_idx_for_kind(
3880            &pack_path,
3881            vec![
3882                (base_hash, base_offset),
3883                (ofs_hash, ofs_offset),
3884                (ref_hash, ref_offset),
3885            ],
3886            HashKind::Sha256,
3887        );
3888        let mut pack = Pack::new_with_hash_kind(
3889            HashKind::Blake3,
3890            Some(1),
3891            None,
3892            Some(dir.path().join("tmp4")),
3893            true,
3894        );
3895        assert!(
3896            pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
3897                .is_err()
3898        );
3899
3900        // A truncated pack (trailer cut short) fails closed instead of panicking.
3901        let (_tmp_dir2, tmp2) = pack_test_tmp();
3902        let mut truncated =
3903            Pack::new_with_hash_kind(HashKind::Blake3, Some(1), None, Some(tmp2), true);
3904        let cut = &pack_data[..pack_data.len() - 5];
3905        assert!(
3906            truncated
3907                .decode(&mut Cursor::new(cut), |_| {}, None::<fn(ObjectHash)>)
3908                .is_err()
3909        );
3910    }
3911
3912    /// Performance door: a BLAKE3 pack decodes from a non-seekable, read-once source in a
3913    /// single pass (bytes read == pack length) with a tiny memory limit forcing the spill path.
3914    #[test]
3915    fn blake3_single_pass_stream() {
3916        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3917        let (pack_data, hashes, _) = blake3_ref_delta_pack();
3918        let counter = Arc::new(AtomicUsize::new(0));
3919        let source = CountingOnce {
3920            data: &pack_data,
3921            pos: 0,
3922            counter: counter.clone(),
3923        };
3924        let mut reader = BufReader::with_capacity(64, source);
3925
3926        let (_tmp_dir, tmp) = pack_test_tmp();
3927        let mut pack =
3928            Pack::new_with_hash_kind(HashKind::Blake3, Some(1), Some(4096), Some(tmp), true);
3929        let seen = Arc::new(Mutex::new(Vec::new()));
3930        let sink = seen.clone();
3931        pack.decode(
3932            &mut reader,
3933            move |entry| sink.lock().unwrap().push(entry.inner.hash),
3934            None::<fn(ObjectHash)>,
3935        )
3936        .unwrap();
3937        assert_eq!(
3938            counter.load(Ordering::SeqCst),
3939            pack_data.len(),
3940            "pack must be read exactly once"
3941        );
3942        assert_eq!(pack.signature.kind(), HashKind::Blake3);
3943        let seen: std::collections::HashSet<ObjectHash> =
3944            seen.lock().unwrap().iter().copied().collect();
3945        assert_eq!(
3946            seen,
3947            hashes
3948                .iter()
3949                .copied()
3950                .collect::<std::collections::HashSet<ObjectHash>>()
3951        );
3952    }
3953
3954    #[test]
3955    fn test_pack_decode_file_without_callback_releases_delta_bases() {
3956        let _guard = set_hash_kind_for_test(HashKind::Sha1);
3957        let base_hash = utils::calculate_object_hash(ObjectType::Blob, b"hello");
3958        let ofs_hash = utils::calculate_object_hash(ObjectType::Blob, b"hi there");
3959        let ref_hash = utils::calculate_object_hash(ObjectType::Blob, b"HELLO");
3960
3961        let mut pack_data = Vec::new();
3962        pack_data.extend_from_slice(b"PACK");
3963        pack_data.extend_from_slice(&2u32.to_be_bytes());
3964        pack_data.extend_from_slice(&3u32.to_be_bytes());
3965
3966        let base_offset = pack_data.len() as u32;
3967        pack_data.push(0x35);
3968        append_compressed(&mut pack_data, b"hello");
3969
3970        let ofs_offset = pack_data.len() as u32;
3971        pack_data.push(0x6b);
3972        pack_data.push((ofs_offset - base_offset) as u8);
3973        append_compressed(
3974            &mut pack_data,
3975            [b"\x05\x08\x08".as_ref(), b"hi there"].concat().as_slice(),
3976        );
3977
3978        let ref_offset = pack_data.len() as u32;
3979        pack_data.push(0x78);
3980        pack_data.extend_from_slice(base_hash.as_ref());
3981        append_compressed(
3982            &mut pack_data,
3983            [b"\x05\x05\x05".as_ref(), b"HELLO"].concat().as_slice(),
3984        );
3985
3986        let trailer = Sha1::digest(&pack_data);
3987        pack_data.extend_from_slice(&trailer);
3988
3989        let dir = tempdir().unwrap();
3990        let pack_path = dir.path().join("delta.pack");
3991        fs::write(&pack_path, &pack_data).unwrap();
3992        write_test_idx(
3993            &pack_path,
3994            vec![
3995                (base_hash, base_offset),
3996                (ofs_hash, ofs_offset),
3997                (ref_hash, ref_offset),
3998            ],
3999        );
4000
4001        let mut pack = Pack::new(Some(1), None, Some(dir.path().join("tmp")), true);
4002        pack.decode_file_without_callback(&pack_path, None::<fn(ObjectHash)>)
4003            .unwrap();
4004
4005        assert_eq!(pack.number, 3);
4006        assert_eq!(pack.signature.to_string(), hex::encode(trailer));
4007    }
4008
4009    #[test]
4010    fn test_rebuild_delta_literal_instruction() {
4011        let _guard = set_hash_kind_for_test(HashKind::Sha1);
4012        let base = Arc::new(CacheObject::new_for_undeltified(
4013            ObjectType::Blob,
4014            b"hello".to_vec(),
4015            12,
4016            0,
4017        ));
4018        let delta = CacheObject {
4019            info: CacheObjectInfo::OffsetDelta(12, 8),
4020            offset: 20,
4021            crc32: 0,
4022            data_decompressed: [b"\x05\x08\x08".as_ref(), b"hi there"].concat(),
4023            mem_recorder: None,
4024            is_delta_in_pack: true,
4025            known_hash: None,
4026        };
4027
4028        let rebuilt = Pack::rebuild_delta(delta, base).unwrap();
4029
4030        assert_eq!(rebuilt.object_type(), ObjectType::Blob);
4031        assert_eq!(rebuilt.data_decompressed, b"hi there");
4032    }
4033
4034    #[test]
4035    fn test_rebuild_delta_malformed_stream_returns_error() {
4036        let _guard = set_hash_kind_for_test(HashKind::Sha1);
4037        let base = Arc::new(CacheObject::new_for_undeltified(
4038            ObjectType::Blob,
4039            b"hello".to_vec(),
4040            12,
4041            0,
4042        ));
4043        let delta = CacheObject {
4044            info: CacheObjectInfo::OffsetDelta(12, 0),
4045            offset: 20,
4046            crc32: 0,
4047            data_decompressed: Vec::new(),
4048            mem_recorder: None,
4049            is_delta_in_pack: true,
4050            known_hash: None,
4051        };
4052
4053        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4054            Pack::rebuild_delta(delta, base)
4055        }));
4056
4057        assert!(result.is_ok(), "malformed delta should not panic");
4058        let result = result.unwrap();
4059        assert!(
4060            matches!(result, Err(crate::errors::GitError::DeltaObjectError(_))),
4061            "unexpected decode result: {result:?}"
4062        );
4063    }
4064
4065    #[test]
4066    fn test_pack_decode_malformed_delta_returns_error_without_panic() {
4067        let _guard = set_hash_kind_for_test(HashKind::Sha1);
4068        let mut pack_data = Vec::new();
4069        pack_data.extend_from_slice(b"PACK");
4070        pack_data.extend_from_slice(&2u32.to_be_bytes());
4071        pack_data.extend_from_slice(&2u32.to_be_bytes());
4072
4073        let base_offset = pack_data.len();
4074        pack_data.push(0x31);
4075        append_compressed(&mut pack_data, b"a");
4076
4077        let delta_offset = pack_data.len();
4078        let delta_payload = vec![0x01, 0x02, b'b'];
4079        pack_data.push(0x63);
4080        pack_data.push((delta_offset - base_offset) as u8);
4081        append_compressed(&mut pack_data, &delta_payload);
4082
4083        let trailer = Sha1::digest(&pack_data);
4084        pack_data.extend_from_slice(&trailer);
4085
4086        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4087            let mut reader = Cursor::new(pack_data);
4088            let mut pack = Pack::new(Some(1), None, None, true);
4089            pack.decode(&mut reader, |_| {}, None::<fn(ObjectHash)>)
4090        }));
4091
4092        assert!(result.is_ok(), "malformed pack delta should not panic");
4093        let result = result.unwrap();
4094        assert!(
4095            matches!(result, Err(crate::errors::GitError::DeltaObjectError(_))),
4096            "unexpected decode result: {result:?}"
4097        );
4098    }
4099
4100    #[test]
4101    #[cfg(target_pointer_width = "32")]
4102    fn test_pack_new_mem_limit_no_overflow_32bit() {
4103        // In the old code, 1.2B * 4 produced an intermediate 4.8B value, which exceeds
4104        // 32-bit usize::MAX (~4.29B) and overflowed before a later division; this test
4105        // covers that former panic path.
4106        let mem_limit = 1_200_000_000usize;
4107        let (_tmp_dir, tmp) = pack_test_tmp();
4108        let result = std::panic::catch_unwind(|| {
4109            let _p = Pack::new(Some(1), Some(mem_limit), Some(tmp), true);
4110        });
4111        assert!(result.is_ok(), "Pack::new should not panic on 32-bit");
4112    }
4113
4114    /// Helper function to run decode tests without delta objects
4115    fn run_decode_no_delta(filename: &str, kind: HashKind) {
4116        let _guard = set_hash_kind_for_test(kind);
4117        let (source, _dl_guard) = download_pack_file(filename);
4118
4119        let (_tmp_dir, tmp) = pack_test_tmp();
4120
4121        let f = fs::File::open(source).unwrap();
4122        let mut buffered = BufReader::new(f);
4123        let mut p = Pack::new(None, Some(1024 * 1024 * 20), Some(tmp), true);
4124        p.decode(&mut buffered, |_| {}, None::<fn(ObjectHash)>)
4125            .unwrap();
4126    }
4127    #[test]
4128    fn test_pack_decode_without_delta() {
4129        run_decode_no_delta("small-sha1.pack", HashKind::Sha1);
4130        run_decode_no_delta("small-sha256.pack", HashKind::Sha256);
4131    }
4132
4133    /// Helper function to run decode tests with delta objects
4134    fn run_decode_with_ref_delta(filename: &str, kind: HashKind) {
4135        let _guard = set_hash_kind_for_test(kind);
4136        init_logger();
4137
4138        let (source, _dl_guard) = download_pack_file(filename);
4139
4140        let (_tmp_dir, tmp) = pack_test_tmp();
4141
4142        let f = fs::File::open(source).unwrap();
4143        let mut buffered = BufReader::new(f);
4144        let mut p = Pack::new(None, Some(1024 * 1024 * 20), Some(tmp), true);
4145        p.decode(&mut buffered, |_| {}, None::<fn(ObjectHash)>)
4146            .unwrap();
4147    }
4148    #[test]
4149    fn test_pack_decode_with_ref_delta() {
4150        run_decode_with_ref_delta("ref-delta-sha1.pack", HashKind::Sha1);
4151        run_decode_with_ref_delta("ref-delta-sha256.pack", HashKind::Sha256);
4152    }
4153
4154    /// Helper function to run decode tests without memory limit
4155    fn run_decode_no_mem_limit(filename: &str, kind: HashKind) {
4156        let _guard = set_hash_kind_for_test(kind);
4157        let (source, _dl_guard) = download_pack_file(filename);
4158
4159        let (_tmp_dir, tmp) = pack_test_tmp();
4160
4161        let f = fs::File::open(source).unwrap();
4162        let mut buffered = BufReader::new(f);
4163        let mut p = Pack::new(None, None, Some(tmp), true);
4164        p.decode(&mut buffered, |_| {}, None::<fn(ObjectHash)>)
4165            .unwrap();
4166    }
4167    #[test]
4168    fn test_pack_decode_no_mem_limit() {
4169        run_decode_no_mem_limit("small-sha1.pack", HashKind::Sha1);
4170        run_decode_no_mem_limit("small-sha256.pack", HashKind::Sha256);
4171    }
4172
4173    /// Helper function to run decode tests with delta objects
4174    async fn run_decode_large_with_delta(filename: &str, kind: HashKind) {
4175        let _guard = set_hash_kind_for_test(kind);
4176        init_logger();
4177        let (source, _dl_guard) = download_pack_file(filename);
4178
4179        let (_tmp_dir, tmp) = pack_test_tmp();
4180
4181        let f = fs::File::open(source).unwrap();
4182        let mut buffered = BufReader::new(f);
4183        let mut p = Pack::new(
4184            Some(4),
4185            Some(LARGE_PACK_TEST_MEM_LIMIT),
4186            Some(tmp.clone()),
4187            true,
4188        );
4189        let rt = p.decode(
4190            &mut buffered,
4191            |_obj| {
4192                // println!("{:?} {}", obj.hash.to_string(), offset);
4193            },
4194            None::<fn(ObjectHash)>,
4195        );
4196        if let Err(e) = rt {
4197            let _ = fs::remove_dir_all(&tmp);
4198            panic!("Error: {e:?}");
4199        }
4200    }
4201    #[cfg_attr(coverage, ignore)]
4202    #[ignore = "requires large remote pack fixture"]
4203    #[tokio::test]
4204    async fn test_pack_decode_with_large_file_with_delta_without_ref() {
4205        run_decode_large_with_delta("medium-sha1.pack", HashKind::Sha1).await;
4206        run_decode_large_with_delta("medium-sha256.pack", HashKind::Sha256).await;
4207    } // it will be stuck on dropping `Pack` on Windows if `mem_size` is None, so we need `mimalloc`
4208
4209    /// Helper function to run decode tests with large file stream
4210    async fn run_decode_large_stream(filename: &str, kind: HashKind) {
4211        let _guard = set_hash_kind_for_test(kind);
4212        init_logger();
4213        let (source, _dl_guard) = download_pack_file(filename);
4214
4215        let (_tmp_dir, tmp) = pack_test_tmp();
4216        let f = tokio::fs::File::open(source).await.unwrap();
4217        let stream = ReaderStream::new(f).map_err(axum::Error::new);
4218        let p = Pack::new(
4219            Some(4),
4220            Some(LARGE_PACK_TEST_MEM_LIMIT),
4221            Some(tmp.clone()),
4222            true,
4223        );
4224
4225        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
4226        let handle = tokio::spawn(async move { p.decode_stream(stream, tx, None).await });
4227        let count = Arc::new(AtomicUsize::new(0));
4228        let count_c = count.clone();
4229        // in tests, RUNTIME is single-threaded, so `sync code` will block the tokio runtime
4230        let consume = tokio::spawn(async move {
4231            let mut cnt = 0;
4232            while let Some(_entry) = rx.recv().await {
4233                cnt += 1;
4234            }
4235            tracing::info!("Received: {}", cnt);
4236            count_c.store(cnt, Ordering::Release);
4237        });
4238        let p = handle.await.unwrap();
4239        consume.await.unwrap();
4240        assert_eq!(count.load(Ordering::Acquire), p.number);
4241        assert_eq!(p.number, 35031);
4242    }
4243    #[cfg_attr(coverage, ignore)]
4244    #[ignore = "requires large remote pack fixture"]
4245    #[tokio::test]
4246    async fn test_decode_large_file_stream() {
4247        run_decode_large_stream("medium-sha1.pack", HashKind::Sha1).await;
4248        run_decode_large_stream("medium-sha256.pack", HashKind::Sha256).await;
4249    }
4250
4251    /// Helper function to run decode tests with large file async
4252    async fn run_decode_large_file_async(filename: &str, kind: HashKind) {
4253        let _guard = set_hash_kind_for_test(kind);
4254        let (source, _dl_guard) = download_pack_file(filename);
4255
4256        let (_tmp_dir, tmp) = pack_test_tmp();
4257        let f = fs::File::open(source).unwrap();
4258        let buffered = BufReader::new(f);
4259        let p = Pack::new(
4260            Some(4),
4261            Some(LARGE_PACK_TEST_MEM_LIMIT),
4262            Some(tmp.clone()),
4263            true,
4264        );
4265
4266        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
4267        let handle = p.decode_async(buffered, tx); // new thread
4268        let mut cnt = 0;
4269        while let Some(_entry) = rx.recv().await {
4270            cnt += 1; //use entry here
4271        }
4272        let p = handle.join().unwrap();
4273        assert_eq!(cnt, p.number);
4274    }
4275    #[cfg_attr(coverage, ignore)]
4276    #[ignore = "requires large remote pack fixture"]
4277    #[tokio::test]
4278    async fn test_decode_large_file_async() {
4279        run_decode_large_file_async("medium-sha1.pack", HashKind::Sha1).await;
4280        run_decode_large_file_async("medium-sha256.pack", HashKind::Sha256).await;
4281    }
4282
4283    /// Helper function to run decode tests with delta objects without reference
4284    fn run_decode_with_delta_no_ref(filename: &str, kind: HashKind) {
4285        let _guard = set_hash_kind_for_test(kind);
4286        let (source, _dl_guard) = download_pack_file(filename);
4287
4288        let (_tmp_dir, tmp) = pack_test_tmp();
4289
4290        let f = fs::File::open(source).unwrap();
4291        let mut buffered = BufReader::new(f);
4292        let mut p = Pack::new(None, Some(LARGE_PACK_TEST_MEM_LIMIT), Some(tmp), true);
4293        p.decode(&mut buffered, |_| {}, None::<fn(ObjectHash)>)
4294            .unwrap();
4295    }
4296    #[cfg_attr(coverage, ignore)]
4297    #[ignore = "requires large remote pack fixture"]
4298    #[test]
4299    fn test_pack_decode_with_delta_without_ref() {
4300        run_decode_with_delta_no_ref("medium-sha1.pack", HashKind::Sha1);
4301        run_decode_with_delta_no_ref("medium-sha256.pack", HashKind::Sha256);
4302    }
4303
4304    #[cfg_attr(coverage, ignore)]
4305    #[ignore = "requires large remote pack fixture"]
4306    #[test] // Take too long time
4307    fn test_pack_decode_multi_task_with_large_file_with_delta_without_ref() {
4308        let rt = tokio::runtime::Builder::new_current_thread()
4309            .enable_all()
4310            .build()
4311            .unwrap();
4312        rt.block_on(async move {
4313            // For each hash kind, run two decode tasks concurrently to simulate multi-task pressure.
4314            for (kind, filename) in [
4315                (HashKind::Sha1, "medium-sha1.pack"),
4316                (HashKind::Sha256, "medium-sha256.pack"),
4317            ] {
4318                let f1 = run_decode_large_with_delta(filename, kind);
4319                let f2 = run_decode_large_with_delta(filename, kind);
4320                let _ = futures::future::join(f1, f2).await;
4321            }
4322        });
4323    }
4324
4325    // -----------------------------------------------------------------------
4326    // PackStats tests (Experiment 3, Task 3)
4327    // -----------------------------------------------------------------------
4328
4329    /// Normal-path test: stats_pack on a small SHA-1 pack (no deltas).
4330    ///
4331    /// We download the same "small-sha1.pack" used by other decode tests,
4332    /// run stats_pack on it, and verify:
4333    ///  - total matches the header object count
4334    ///  - commits + trees + blobs + tags + deltas == total
4335    ///  - at least one commit and one blob exist (the pack is a real git repo extract)
4336    #[test]
4337    fn test_stats_pack_small_sha1() {
4338        let _guard = set_hash_kind_for_test(HashKind::Sha1);
4339        let (source, _dl_guard) = download_pack_file("small-sha1.pack");
4340
4341        let stats = Pack::stats_pack(source).expect("stats_pack should succeed");
4342
4343        eprintln!(
4344            "small-sha1 stats: total={}, commits={}, trees={}, blobs={}, tags={}, deltas={}",
4345            stats.total, stats.commits, stats.trees, stats.blobs, stats.tags, stats.deltas
4346        );
4347
4348        let sum = stats.commits + stats.trees + stats.blobs + stats.tags + stats.deltas;
4349        assert_eq!(
4350            sum, stats.total,
4351            "per-type counts should sum to total ({} vs {})",
4352            sum, stats.total
4353        );
4354
4355        assert!(stats.commits > 0, "expected at least one commit");
4356        assert!(stats.blobs > 0, "expected at least one blob");
4357    }
4358
4359    /// Normal-path test: stats_pack on a medium SHA-1 pack that contains offset-delta objects.
4360    ///
4361    /// "medium-sha1.pack" is used by the existing decode tests and is known to contain
4362    /// both base objects and offset-delta objects, so deltas > 0.
4363    #[test]
4364    fn test_stats_pack_medium_sha1_has_deltas() {
4365        let _guard = set_hash_kind_for_test(HashKind::Sha1);
4366        let (source, _dl_guard) = download_pack_file("medium-sha1.pack");
4367
4368        let stats = Pack::stats_pack(source).expect("stats_pack should succeed on medium pack");
4369
4370        eprintln!(
4371            "medium-sha1 stats: total={}, commits={}, trees={}, blobs={}, tags={}, deltas={}",
4372            stats.total, stats.commits, stats.trees, stats.blobs, stats.tags, stats.deltas
4373        );
4374
4375        let sum = stats.commits + stats.trees + stats.blobs + stats.tags + stats.deltas;
4376        assert_eq!(sum, stats.total, "per-type counts must equal total");
4377
4378        assert!(
4379            stats.deltas > 0,
4380            "expected delta objects in medium-sha1 pack"
4381        );
4382
4383        assert!(stats.total > 1000, "expected a sizeable medium pack");
4384    }
4385
4386    /// Error-path test: stats_pack on a path that does not exist.
4387    ///
4388    /// Must return Err, not panic.
4389    #[test]
4390    fn test_stats_pack_file_not_found() {
4391        let result = Pack::stats_pack(PathBuf::from("/nonexistent/path/to/fake.pack"));
4392        assert!(
4393            result.is_err(),
4394            "stats_pack should return Err for a missing file"
4395        );
4396    }
4397
4398    /// Error-path test: stats_pack on a file whose content is not a valid pack.
4399    ///
4400    /// We construct an in-memory byte sequence that starts with wrong magic bytes
4401    /// and write it to a temp file, then verify that stats_pack returns an error.
4402    #[test]
4403    fn test_stats_pack_invalid_pack_magic() {
4404        use std::io::Write;
4405
4406        use tempfile::NamedTempFile;
4407
4408        let mut tmp = NamedTempFile::new().expect("create temp file");
4409        tmp.write_all(b"FAKE\x00\x00\x00\x02\x00\x00\x00\x05")
4410            .expect("write temp bytes");
4411        let path = tmp.path().to_path_buf();
4412
4413        let result = Pack::stats_pack(path);
4414        assert!(
4415            result.is_err(),
4416            "stats_pack should return Err for invalid pack magic"
4417        );
4418    }
4419}