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