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