Skip to main content

git_internal/internal/pack/
stats.rs

1use std::{
2    collections::{HashMap, HashSet},
3    fmt,
4    fs::File,
5    io::{BufRead, BufReader, ErrorKind, Read},
6    path::Path,
7};
8
9use flate2::bufread::ZlibDecoder;
10
11use crate::{
12    errors::GitError,
13    hash::{HashKind, ObjectHash, get_hash_kind},
14    internal::pack::{Pack, pack_index, utils, wrapper::Wrapper},
15    utils::CountingReader,
16};
17
18#[derive(Debug, Default, Clone, PartialEq, Eq)]
19pub struct PackStats {
20    /// Repository hash kind the pack (trailer, ref-delta bases, idx) was verified with.
21    pub hash_kind: HashKind,
22    pub total: usize,
23    pub commits: usize,
24    pub trees: usize,
25    pub blobs: usize,
26    pub tags: usize,
27    pub deltas: usize,
28}
29
30struct PackScan {
31    stats: PackStats,
32    /// `(offset, name)` of every base (non-delta) object, streamed through the `kind` hasher.
33    base_objects: Vec<(usize, ObjectHash)>,
34    ref_delta_bases: HashSet<ObjectHash>,
35    /// Start offset of every object in the pack (base and delta).
36    object_offsets: HashSet<usize>,
37    pack_hash: ObjectHash,
38}
39
40struct PackIndexEntries {
41    names: HashSet<ObjectHash>,
42    /// Name recorded by the idx at each pack offset (offsets are unique).
43    by_offset: HashMap<u64, ObjectHash>,
44    pack_hash: ObjectHash,
45}
46
47impl fmt::Display for PackStats {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(
50            f,
51            "PackStats {{ total: {}, commits: {}, trees: {}, blobs: {}, tags: {}, deltas: {} }}",
52            self.total, self.commits, self.trees, self.blobs, self.tags, self.deltas
53        )
54    }
55}
56
57impl PackStats {
58    /// Empty statistics tagged with an explicit repository `hash_kind`.
59    pub fn new_with_hash_kind(hash_kind: HashKind) -> Self {
60        PackStats {
61            hash_kind,
62            ..Default::default()
63        }
64    }
65
66    /// Repository hash kind these statistics were computed for.
67    pub fn hash_kind(&self) -> HashKind {
68        self.hash_kind
69    }
70
71    /// Analyze a pack using the thread-local [`HashKind`]; compatibility wrapper around
72    /// [`PackStats::analyze_with_hash_kind`].
73    pub fn analyze<P: AsRef<Path>>(pack_path: P) -> Result<PackStats, GitError> {
74        Self::analyze_with_hash_kind(get_hash_kind(), pack_path)
75    }
76
77    /// Analyze a pack of an explicit repository `kind`: the pack trailer, every ref-delta
78    /// base ID and the accompanying idx (object names, pack checksum, idx checksum) are
79    /// parsed and verified with that kind and never inferred from their length.
80    pub fn analyze_with_hash_kind<P: AsRef<Path>>(
81        kind: HashKind,
82        pack_path: P,
83    ) -> Result<PackStats, GitError> {
84        let pack_path = pack_path.as_ref();
85        if !pack_path.exists() {
86            return Err(GitError::InvalidPackFile(format!(
87                "Pack file not found: {}",
88                pack_path.display()
89            )));
90        }
91
92        let f = File::open(pack_path)
93            .map_err(|e| GitError::InvalidPackFile(format!("Failed to open pack file: {e}")))?;
94        let scan = Self::scan(BufReader::new(f), kind)?;
95        let index = Self::read_pack_index_hashes(pack_path, kind)?;
96        if index.is_none() && !scan.ref_delta_bases.is_empty() {
97            return Err(GitError::InvalidPackFile(
98                "Pack index is required to verify ref-delta bases".to_string(),
99            ));
100        }
101        // An existing idx is verified against the pack even when there are no ref-deltas:
102        // object count, copied pack checksum, every base object's streamed content hash and
103        // every ref-delta base must all agree (fail-closed). This is a single-pass statistics
104        // scan that inflates and hashes every base payload but does not resolve delta chains, so the idx names of *delta* objects are
105        // outside its verification scope (their idx offsets must still be object boundaries);
106        // `Pack::decode_file_full_without_callback` (or any decode that resolves deltas)
107        // verifies those names by rebuilding each delta.
108        if let Some(index) = index {
109            if index.names.len() != scan.stats.total {
110                return Err(GitError::InvalidPackFile(format!(
111                    "Pack index lists {} objects but the pack contains {}",
112                    index.names.len(),
113                    scan.stats.total
114                )));
115            }
116            if index.pack_hash != scan.pack_hash {
117                return Err(GitError::InvalidPackFile(format!(
118                    "Pack index hash {} does not match pack trailer hash {}",
119                    index.pack_hash, scan.pack_hash
120                )));
121            }
122            // Every idx entry must point at an object boundary of this pack.
123            if let Some((offset, name)) = index.by_offset.iter().find(|(offset, _)| {
124                !usize::try_from(**offset).is_ok_and(|offset| scan.object_offsets.contains(&offset))
125            }) {
126                return Err(GitError::InvalidPackFile(format!(
127                    "Pack index entry {name} points at offset {offset}, which is not an object boundary of the pack"
128                )));
129            }
130            // Every base object must be named by the idx *at its own offset*: a set-level
131            // comparison would accept an idx whose names are merely permuted across offsets.
132            for (offset, hash) in &scan.base_objects {
133                match index.by_offset.get(&(*offset as u64)) {
134                    Some(name) if name == hash => {}
135                    Some(name) => {
136                        return Err(GitError::InvalidPackFile(format!(
137                            "Pack object {hash} ({kind}) at offset {offset} is not named by the pack index at that offset (index names {name})"
138                        )));
139                    }
140                    None => {
141                        return Err(GitError::InvalidPackFile(format!(
142                            "Pack object {hash} ({kind}) at offset {offset} is not named by the pack index (no index entry at that offset)"
143                        )));
144                    }
145                }
146            }
147            if let Some(base_hash) = scan
148                .ref_delta_bases
149                .iter()
150                .find(|base_hash| !index.names.contains(*base_hash))
151            {
152                return Err(GitError::InvalidPackFile(format!(
153                    "Ref-delta base {base_hash} is not present in the pack index"
154                )));
155            }
156        }
157
158        Ok(scan.stats)
159    }
160
161    pub fn validate_header<P: AsRef<Path>>(pack_path: P) -> Result<u32, GitError> {
162        let pack_path = pack_path.as_ref();
163        if !pack_path.exists() {
164            return Err(GitError::InvalidPackFile(format!(
165                "Pack file not found: {}",
166                pack_path.display()
167            )));
168        }
169
170        let f = File::open(pack_path)
171            .map_err(|e| GitError::InvalidPackFile(format!("Failed to open pack file: {e}")))?;
172        let mut reader = BufReader::new(f);
173
174        let (count, _) = Pack::check_header(&mut reader)?;
175        Ok(count)
176    }
177
178    fn scan(reader: impl BufRead, kind: HashKind) -> Result<PackScan, GitError> {
179        let mut reader = Wrapper::new_with_kind(reader, kind);
180        let (object_num, header_data) = Pack::check_header(&mut reader)?;
181        let mut stats = PackStats {
182            hash_kind: kind,
183            total: object_num as usize,
184            ..Default::default()
185        };
186        let first_object_offset = header_data.len();
187        let mut offset = first_object_offset;
188        let mut object_starts = HashSet::new();
189        let mut ref_delta_bases = HashSet::new();
190        let mut base_objects = Vec::new();
191
192        for _ in 0..object_num {
193            let object_start = offset;
194            let (type_bits, size) = utils::read_type_and_varint_size(&mut reader, &mut offset)
195                .map_err(|e| {
196                    GitError::InvalidPackFile(format!("Read error at offset {offset}: {e}"))
197                })?;
198
199            stats.count_type_bits(type_bits, offset)?;
200
201            match type_bits {
202                1..=4 => {
203                    // Stream the base object through the hasher (no payload retained) so its
204                    // name can be checked against the idx.
205                    let obj_type =
206                        crate::internal::object::types::ObjectType::from_pack_type_u8(type_bits)?;
207                    let (hash, consumed) =
208                        Pack::hash_compressed_object(&mut reader, obj_type, size, kind)?;
209                    add_to_offset(&mut offset, consumed)?;
210                    base_objects.push((object_start, hash));
211                }
212                5 | 6 => {
213                    let (delta_offset, consumed) = utils::read_offset_encoding(&mut reader)
214                        .map_err(|e| {
215                            GitError::InvalidPackFile(format!(
216                                "Read offset encoding error at offset {offset}: {e}"
217                            ))
218                        })?;
219                    let delta_offset = usize::try_from(delta_offset).map_err(|_| {
220                        GitError::InvalidPackFile(format!(
221                            "Offset delta at {object_start} exceeds platform limits"
222                        ))
223                    })?;
224                    let base_offset = object_start.checked_sub(delta_offset).ok_or_else(|| {
225                        GitError::InvalidPackFile(format!(
226                            "Offset delta at {object_start} points before pack data"
227                        ))
228                    })?;
229                    if delta_offset == 0
230                        || base_offset < first_object_offset
231                        || !object_starts.contains(&base_offset)
232                    {
233                        return Err(GitError::InvalidPackFile(format!(
234                            "Offset delta at {object_start} does not reference an earlier object"
235                        )));
236                    }
237                    add_to_offset(&mut offset, consumed)?;
238                    drain_zlib(&mut reader, &mut offset, size)?;
239                }
240                7 => {
241                    let base_hash =
242                        ObjectHash::from_stream_for_kind(kind, &mut reader).map_err(|e| {
243                            GitError::InvalidPackFile(format!(
244                                "Read hash error at offset {offset}: {e}"
245                            ))
246                        })?;
247                    add_to_offset(&mut offset, base_hash.size())?;
248                    ref_delta_bases.insert(base_hash);
249                    drain_zlib(&mut reader, &mut offset, size)?;
250                }
251                _ => unreachable!(),
252            }
253            object_starts.insert(object_start);
254        }
255
256        let computed_hash = reader.final_hash();
257        let trailer = ObjectHash::from_stream_for_kind(kind, &mut reader).map_err(|e| {
258            GitError::InvalidPackFile(format!("Failed to read trailer hash: {e:?}"))
259        })?;
260        if computed_hash != trailer {
261            return Err(GitError::InvalidPackFile(format!(
262                "Pack trailer mismatch: computed {computed_hash}, stored {trailer}"
263            )));
264        }
265        if !utils::is_eof(&mut reader) {
266            return Err(GitError::InvalidPackFile(
267                "Pack has trailing data after trailer".to_string(),
268            ));
269        }
270
271        Ok(PackScan {
272            stats,
273            base_objects,
274            ref_delta_bases,
275            object_offsets: object_starts,
276            pack_hash: trailer,
277        })
278    }
279
280    fn read_pack_index_hashes(
281        pack_path: &Path,
282        kind: HashKind,
283    ) -> Result<Option<PackIndexEntries>, GitError> {
284        let idx_path = pack_path.with_extension("idx");
285        // `symlink_metadata`: a dangling `.idx` symlink counts as present (and then fails to
286        // open) instead of being mistaken for a missing idx; only NotFound means "no idx".
287        match std::fs::symlink_metadata(&idx_path) {
288            Ok(_) => {}
289            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
290            Err(e) => {
291                return Err(GitError::InvalidPackFile(format!(
292                    "Pack index {} exists but cannot be read: {e}",
293                    idx_path.display()
294                )));
295            }
296        }
297        let idx_file = File::open(&idx_path).map_err(|e| {
298            GitError::InvalidPackFile(format!(
299                "Pack index {} exists but cannot be read: {e}",
300                idx_path.display()
301            ))
302        })?;
303        let idx_len = idx_file
304            .metadata()
305            .map_err(|e| GitError::InvalidPackFile(format!("Read pack index metadata error: {e}")))?
306            .len();
307        // Streamed, size-bounded parse (no whole-file buffer).
308        let parsed = pack_index::parse_idx_v2_from(BufReader::new(idx_file), kind, idx_len)?;
309        let mut names = HashSet::with_capacity(parsed.entries.len());
310        let mut by_offset = HashMap::with_capacity(parsed.entries.len());
311        for entry in parsed.entries {
312            names.insert(entry.hash);
313            if by_offset.insert(entry.offset, entry.hash).is_some() {
314                return Err(GitError::InvalidPackFile(format!(
315                    "Pack index lists offset {} more than once",
316                    entry.offset
317                )));
318            }
319        }
320        Ok(Some(PackIndexEntries {
321            names,
322            by_offset,
323            pack_hash: parsed.pack_hash,
324        }))
325    }
326
327    fn count_type_bits(&mut self, type_bits: u8, offset: usize) -> Result<(), GitError> {
328        match type_bits {
329            1 => {
330                self.commits += 1;
331            }
332            2 => {
333                self.trees += 1;
334            }
335            3 => {
336                self.blobs += 1;
337            }
338            4 => {
339                self.tags += 1;
340            }
341            5..=7 => {
342                self.deltas += 1;
343            }
344            _ => {
345                return Err(GitError::InvalidObjectType(format!(
346                    "Unknown pack type bits: {type_bits} at offset {offset}"
347                )));
348            }
349        }
350        Ok(())
351    }
352}
353
354fn drain_zlib(
355    reader: &mut impl BufRead,
356    offset: &mut usize,
357    expected_size: usize,
358) -> Result<(), GitError> {
359    let mut counting_reader = CountingReader::new(reader);
360    let mut deflate = ZlibDecoder::new(&mut counting_reader);
361    let mut remaining = expected_size;
362    let mut scratch = [0; 8192];
363
364    while remaining > 0 {
365        let chunk_len = remaining.min(scratch.len());
366        let bytes = deflate
367            .read(&mut scratch[..chunk_len])
368            .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
369        if bytes == 0 {
370            return Err(GitError::InvalidPackFile(format!(
371                "The object size is smaller than the expected size {expected_size}"
372            )));
373        }
374        remaining -= bytes;
375    }
376
377    let mut extra = [0; 1];
378    let extra_bytes = deflate
379        .read(&mut extra)
380        .map_err(|e| GitError::InvalidPackFile(format!("Decompression error: {e}")))?;
381    if extra_bytes != 0 {
382        return Err(GitError::InvalidPackFile(format!(
383            "The object size exceeds the expected size {expected_size}"
384        )));
385    }
386
387    let consumed = usize::try_from(counting_reader.bytes_read).map_err(|_| {
388        GitError::InvalidPackFile("Compressed object size exceeds platform limits".to_string())
389    })?;
390    add_to_offset(offset, consumed)
391}
392
393fn add_to_offset(offset: &mut usize, consumed: usize) -> Result<(), GitError> {
394    *offset = offset
395        .checked_add(consumed)
396        .ok_or_else(|| GitError::InvalidPackFile("Pack offset overflow".to_string()))?;
397    Ok(())
398}
399
400#[cfg(test)]
401mod tests {
402    use std::path::Path;
403
404    use super::*;
405    use crate::{
406        hash::{HashKind, set_hash_kind_for_test},
407        internal::pack::test_pack_download::download_pack_file,
408        utils::HashAlgorithm,
409    };
410
411    #[test]
412    fn test_analyze_small_pack_sha1() {
413        let _guard = set_hash_kind_for_test(HashKind::Sha1);
414        let (pack_path, _dl_guard) = download_pack_file("small-sha1.pack");
415        let stats = PackStats::analyze(pack_path).expect("Failed to analyze");
416
417        assert!(stats.total > 0);
418        assert_eq!(
419            stats.total,
420            stats.commits + stats.trees + stats.blobs + stats.tags + stats.deltas
421        );
422    }
423
424    #[test]
425    fn test_analyze_small_pack_sha256() {
426        let _guard = set_hash_kind_for_test(HashKind::Sha256);
427        let (pack_path, _dl_guard) = download_pack_file("small-sha256.pack");
428        let stats = PackStats::analyze(pack_path).expect("Failed to analyze");
429
430        assert!(stats.total > 0);
431        assert_eq!(
432            stats.total,
433            stats.commits + stats.trees + stats.blobs + stats.tags + stats.deltas
434        );
435    }
436
437    #[test]
438    fn test_analyze_delta_pack_sha1() {
439        let _guard = set_hash_kind_for_test(HashKind::Sha1);
440        let (pack_path, _dl_guard) = download_pack_file("ref-delta-sha1.pack");
441        let stats = PackStats::analyze(pack_path).expect("Failed to analyze");
442
443        assert!(stats.total > 0);
444
445        assert_eq!(
446            stats.total,
447            stats.commits + stats.trees + stats.blobs + stats.tags + stats.deltas
448        );
449    }
450
451    #[test]
452    fn test_analyze_delta_pack_sha256() {
453        let _guard = set_hash_kind_for_test(HashKind::Sha256);
454        let (pack_path, _dl_guard) = download_pack_file("ref-delta-sha256.pack");
455        let stats = PackStats::analyze(pack_path).expect("Failed to analyze");
456
457        assert!(stats.total > 0);
458        assert_eq!(
459            stats.total,
460            stats.commits + stats.trees + stats.blobs + stats.tags + stats.deltas
461        );
462    }
463
464    #[test]
465    fn test_nonexistent_file() {
466        let result = PackStats::analyze("tests/data/packs/nonexistent.pack");
467        assert!(result.is_err());
468    }
469
470    #[test]
471    fn test_invalid_pack_file() {
472        use std::io::Write;
473
474        use tempfile::NamedTempFile;
475
476        let mut temp = NamedTempFile::new().expect("create temp file");
477        temp.write_all(b"XXXX").expect("write temp file");
478        temp.flush().expect("flush temp file");
479
480        let result = PackStats::analyze(temp.path());
481        assert!(result.is_err());
482    }
483
484    #[test]
485    fn test_analyze_rejects_trailing_data() {
486        use std::{fs, io::Write};
487
488        use tempfile::NamedTempFile;
489
490        let _guard = set_hash_kind_for_test(HashKind::Sha1);
491        let (pack_path, _dl_guard) = download_pack_file("small-sha1.pack");
492        let mut bytes = fs::read(pack_path).expect("read pack fixture");
493        bytes.push(0);
494
495        let mut temp = NamedTempFile::new().expect("create temp file");
496        temp.write_all(&bytes).expect("write temp file");
497        temp.flush().expect("flush temp file");
498
499        let result = PackStats::analyze(temp.path());
500        assert!(result.is_err());
501    }
502
503    #[test]
504    fn test_analyze_huge_object_count_does_not_preallocate() {
505        use std::io::Write;
506
507        use tempfile::NamedTempFile;
508
509        let _guard = set_hash_kind_for_test(HashKind::Sha1);
510        let mut bytes = Vec::new();
511        bytes.extend_from_slice(b"PACK");
512        bytes.extend_from_slice(&2u32.to_be_bytes());
513        bytes.extend_from_slice(&u32::MAX.to_be_bytes());
514
515        let mut temp = NamedTempFile::new().expect("create temp file");
516        temp.write_all(&bytes).expect("write temp file");
517        temp.flush().expect("flush temp file");
518
519        let result = PackStats::analyze(temp.path());
520        assert!(result.is_err());
521    }
522
523    #[test]
524    fn test_analyze_ref_delta_requires_index() {
525        use std::io::Write;
526
527        use flate2::{Compression, write::ZlibEncoder};
528        use tempfile::NamedTempFile;
529
530        let _guard = set_hash_kind_for_test(HashKind::Sha1);
531        let mut deflate = ZlibEncoder::new(Vec::new(), Compression::default());
532        deflate.write_all(&[]).expect("write zlib payload");
533        let compressed_delta = deflate.finish().expect("finish zlib payload");
534
535        let mut bytes = Vec::new();
536        bytes.extend_from_slice(b"PACK");
537        bytes.extend_from_slice(&2u32.to_be_bytes());
538        bytes.extend_from_slice(&1u32.to_be_bytes());
539        write_pack_object_header(&mut bytes, 7, 0);
540        bytes.extend(std::iter::repeat_n(0, get_hash_kind().size()));
541        bytes.extend_from_slice(&compressed_delta);
542        append_pack_trailer(&mut bytes);
543
544        let mut temp = NamedTempFile::new().expect("create temp file");
545        temp.write_all(&bytes).expect("write temp file");
546        temp.flush().expect("flush temp file");
547
548        let result = PackStats::analyze(temp.path());
549        assert!(format!("{result:?}").contains("Pack index is required"));
550    }
551
552    #[test]
553    fn test_validate_header() {
554        let _guard = set_hash_kind_for_test(HashKind::Sha1);
555        let (pack_path, _dl_guard) = download_pack_file("small-sha1.pack");
556        let result = PackStats::validate_header(pack_path);
557        assert!(result.is_ok());
558        assert!(result.unwrap() > 0);
559    }
560
561    #[test]
562    fn test_validate_header_nonexistent() {
563        let result = PackStats::validate_header("tests/data/packs/nonexistent.pack");
564        assert!(result.is_err());
565    }
566
567    #[test]
568    fn test_validate_header_invalid_file() {
569        use std::io::Write;
570
571        use tempfile::NamedTempFile;
572
573        let mut temp = NamedTempFile::new().expect("create temp file");
574        temp.write_all(b"XX").expect("write temp file");
575        temp.flush().expect("flush temp file");
576
577        let result = PackStats::validate_header(temp.path());
578        assert!(result.is_err());
579    }
580
581    fn write_pack_object_header(out: &mut Vec<u8>, type_bits: u8, mut size: usize) {
582        let mut byte = ((type_bits & 0x07) << 4) | (size as u8 & 0x0f);
583        size >>= 4;
584        if size != 0 {
585            byte |= 0x80;
586        }
587        out.push(byte);
588
589        while size != 0 {
590            let mut next = (size as u8) & 0x7f;
591            size >>= 7;
592            if size != 0 {
593                next |= 0x80;
594            }
595            out.push(next);
596        }
597    }
598
599    fn append_pack_trailer(bytes: &mut Vec<u8>) {
600        append_pack_trailer_for_kind(bytes, get_hash_kind());
601    }
602
603    fn append_pack_trailer_for_kind(bytes: &mut Vec<u8>, kind: HashKind) {
604        let mut hash = HashAlgorithm::new_for_kind(kind);
605        hash.update(bytes);
606        let trailer = hash.finalize_object_hash();
607        bytes.extend_from_slice(trailer.as_ref());
608    }
609
610    fn append_zlib(out: &mut Vec<u8>, data: &[u8]) {
611        use std::io::Write;
612        let mut deflate =
613            flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
614        deflate.write_all(data).expect("zlib payload");
615        out.extend_from_slice(&deflate.finish().expect("finish zlib payload"));
616    }
617
618    /// Minimal idx v2 writer for one BLAKE3 pack (used to exercise ref-delta validation).
619    fn write_idx_v2_for_kind(
620        pack_path: &Path,
621        objects: &[(ObjectHash, u32)],
622        kind: HashKind,
623        version: u32,
624    ) {
625        let mut objects: Vec<(ObjectHash, u32)> = objects.to_vec();
626        objects.sort_by(|a, b| a.0.as_ref().cmp(b.0.as_ref()));
627        let mut idx = Vec::new();
628        idx.extend_from_slice(&0xff74_4f63u32.to_be_bytes());
629        idx.extend_from_slice(&version.to_be_bytes());
630        for fanout_idx in 0..256 {
631            let count = objects
632                .iter()
633                .filter(|(h, _)| h.as_ref()[0] as usize <= fanout_idx)
634                .count() as u32;
635            idx.extend_from_slice(&count.to_be_bytes());
636        }
637        for (h, _) in &objects {
638            idx.extend_from_slice(h.as_ref());
639        }
640        for _ in &objects {
641            idx.extend_from_slice(&0u32.to_be_bytes());
642        }
643        for (_, off) in &objects {
644            idx.extend_from_slice(&off.to_be_bytes());
645        }
646        let pack = std::fs::read(pack_path).unwrap();
647        idx.extend_from_slice(&pack[pack.len() - kind.size()..]);
648        let mut hasher = HashAlgorithm::new_for_kind(kind);
649        hasher.update(&idx);
650        let idx_hash = hasher.finalize_object_hash();
651        idx.extend_from_slice(idx_hash.as_ref());
652        std::fs::write(pack_path.with_extension("idx"), idx).unwrap();
653    }
654
655    /// `PackStats::analyze_with_hash_kind(Blake3)` verifies a BLAKE3 trailer, resolves 32-byte
656    /// BLAKE3 ref-delta bases through a BLAKE3 idx v2, rejects the same pack under SHA-256 and
657    /// rejects an idx whose version is not 2 — all with a SHA-1 thread-local kind.
658    #[test]
659    fn blake3_pack_stats() {
660        let _guard = set_hash_kind_for_test(HashKind::Sha1);
661        let kind = HashKind::Blake3;
662        let dir = tempfile::tempdir().unwrap();
663
664        // Two plain blobs.
665        let mut bytes = Vec::new();
666        bytes.extend_from_slice(b"PACK");
667        bytes.extend_from_slice(&2u32.to_be_bytes());
668        bytes.extend_from_slice(&2u32.to_be_bytes());
669        write_pack_object_header(&mut bytes, 3, 5);
670        append_zlib(&mut bytes, b"hello");
671        let world_offset = bytes.len() as u32;
672        write_pack_object_header(&mut bytes, 3, 5);
673        append_zlib(&mut bytes, b"world");
674        append_pack_trailer_for_kind(&mut bytes, kind);
675        let plain = dir.path().join("plain.pack");
676        std::fs::write(&plain, &bytes).unwrap();
677
678        let stats = PackStats::analyze_with_hash_kind(kind, &plain).expect("blake3 stats");
679        assert_eq!(stats.hash_kind(), HashKind::Blake3);
680        assert_eq!(PackStats::new_with_hash_kind(kind).hash_kind(), kind);
681        assert_eq!(stats.total, 2);
682        assert_eq!(stats.blobs, 2);
683        assert_eq!(stats.deltas, 0);
684        // Legacy `analyze` follows the thread-local (SHA-1) kind and cannot verify the trailer.
685        assert!(PackStats::analyze(&plain).is_err());
686        // An idx next to a plain pack is verified too: a checksum-valid idx naming an object
687        // wrongly is rejected, the correct one is accepted.
688        let hello = utils::calculate_object_hash_for_kind(
689            kind,
690            crate::internal::object::types::ObjectType::Blob,
691            b"hello",
692        )
693        .unwrap();
694        let world = utils::calculate_object_hash_for_kind(
695            kind,
696            crate::internal::object::types::ObjectType::Blob,
697            b"world",
698        )
699        .unwrap();
700        let bogus = ObjectHash::new_for_kind(kind, b"bogus");
701        write_idx_v2_for_kind(&plain, &[(hello, 12), (bogus, world_offset)], kind, 2);
702        let err = PackStats::analyze_with_hash_kind(kind, &plain).unwrap_err();
703        assert!(
704            err.to_string().contains("is not named by the pack index"),
705            "{err}"
706        );
707        write_idx_v2_for_kind(&plain, &[(hello, 12), (world, world_offset)], kind, 2);
708        assert_eq!(
709            PackStats::analyze_with_hash_kind(kind, &plain)
710                .unwrap()
711                .blobs,
712            2
713        );
714        // Swapping the offsets of two correctly named objects is caught: names are verified
715        // at their own offsets, not as a set.
716        write_idx_v2_for_kind(&plain, &[(hello, world_offset), (world, 12)], kind, 2);
717        let err = PackStats::analyze_with_hash_kind(kind, &plain).unwrap_err();
718        assert!(err.to_string().contains("index names"), "{err}");
719        // An idx entry that does not point at an object boundary is rejected.
720        write_idx_v2_for_kind(&plain, &[(hello, 12), (world, 13)], kind, 2);
721        let err = PackStats::analyze_with_hash_kind(kind, &plain).unwrap_err();
722        assert!(err.to_string().contains("not an object boundary"), "{err}");
723        // A dangling `.idx` symlink is an error, never a fallback to the no-idx path.
724        #[cfg(unix)]
725        {
726            let idx_path = plain.with_extension("idx");
727            std::fs::remove_file(&idx_path).unwrap();
728            std::os::unix::fs::symlink(dir.path().join("missing.idx"), &idx_path).unwrap();
729            let err = PackStats::analyze_with_hash_kind(kind, &plain).unwrap_err();
730            assert!(err.to_string().contains("cannot be read"), "{err}");
731            std::fs::remove_file(&idx_path).unwrap();
732        }
733        write_idx_v2_for_kind(&plain, &[(hello, 12), (world, world_offset)], kind, 2);
734        assert_eq!(
735            PackStats::analyze_with_hash_kind(kind, &plain)
736                .unwrap()
737                .blobs,
738            2
739        );
740        let err = PackStats::analyze_with_hash_kind(HashKind::Sha256, &plain).unwrap_err();
741        assert!(err.to_string().contains("Pack trailer mismatch"), "{err}");
742
743        // Base blob + ref delta whose base ID is a 32-byte BLAKE3 hash.
744        let base_hash = utils::calculate_object_hash_for_kind(
745            kind,
746            crate::internal::object::types::ObjectType::Blob,
747            b"hello",
748        )
749        .unwrap();
750        let mut bytes = Vec::new();
751        bytes.extend_from_slice(b"PACK");
752        bytes.extend_from_slice(&2u32.to_be_bytes());
753        bytes.extend_from_slice(&2u32.to_be_bytes());
754        let base_offset = bytes.len() as u32;
755        write_pack_object_header(&mut bytes, 3, 5);
756        append_zlib(&mut bytes, b"hello");
757        let delta_offset = bytes.len() as u32;
758        let delta_hash = utils::calculate_object_hash_for_kind(
759            kind,
760            crate::internal::object::types::ObjectType::Blob,
761            b"HELLO",
762        )
763        .unwrap();
764        write_pack_object_header(&mut bytes, 7, 8);
765        bytes.extend_from_slice(base_hash.as_ref());
766        append_zlib(
767            &mut bytes,
768            [b"\x05\x05\x05".as_ref(), b"HELLO"].concat().as_slice(),
769        );
770        append_pack_trailer_for_kind(&mut bytes, kind);
771        let delta = dir.path().join("delta.pack");
772        std::fs::write(&delta, &bytes).unwrap();
773
774        // Without an idx the ref-delta base cannot be verified.
775        assert!(
776            PackStats::analyze_with_hash_kind(kind, &delta)
777                .unwrap_err()
778                .to_string()
779                .contains("Pack index is required")
780        );
781        // Write the idx with the crate's own `IdxBuilder` (BLAKE3 names + checksums) so the
782        // writer and this reader are verified against each other end-to-end.
783        {
784            use crate::internal::pack::pack_index::{IdxBuilder, IndexEntry};
785            let pack_hash =
786                ObjectHash::from_bytes_for_kind(kind, &bytes[bytes.len() - 32..]).unwrap();
787            let rt = tokio::runtime::Builder::new_current_thread()
788                .enable_all()
789                .build()
790                .unwrap();
791            let idx_bytes = rt.block_on(async {
792                let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<u8>>(4096);
793                let mut builder = IdxBuilder::new(2, tx, pack_hash);
794                assert_eq!(builder.hash_kind(), kind);
795                builder
796                    .write_idx(vec![
797                        IndexEntry {
798                            hash: base_hash,
799                            crc32: 0,
800                            offset: base_offset as u64,
801                        },
802                        IndexEntry {
803                            hash: delta_hash,
804                            crc32: 0,
805                            offset: delta_offset as u64,
806                        },
807                    ])
808                    .await
809                    .unwrap();
810                let mut out = Vec::new();
811                while let Some(chunk) = rx.recv().await {
812                    out.extend_from_slice(&chunk);
813                }
814                out
815            });
816            std::fs::write(delta.with_extension("idx"), idx_bytes).unwrap();
817        }
818        let stats =
819            PackStats::analyze_with_hash_kind(kind, &delta).expect("blake3 ref-delta stats");
820        assert_eq!(stats.hash_kind(), kind);
821        assert_eq!(stats.total, 2);
822        assert_eq!(stats.blobs, 1);
823        assert_eq!(stats.deltas, 1);
824        // An idx that lists fewer objects than the pack is rejected.
825        write_idx_v2_for_kind(&delta, &[(base_hash, base_offset)], kind, 2);
826        let err = PackStats::analyze_with_hash_kind(kind, &delta).unwrap_err();
827        assert!(
828            err.to_string()
829                .contains("lists 1 objects but the pack contains 2"),
830            "{err}"
831        );
832        // An idx of any other version is rejected for BLAKE3.
833        write_idx_v2_for_kind(
834            &delta,
835            &[(base_hash, base_offset), (delta_hash, delta_offset)],
836            kind,
837            1,
838        );
839        let err = PackStats::analyze_with_hash_kind(kind, &delta).unwrap_err();
840        assert!(
841            err.to_string().contains("Only pack index v2") && err.to_string().contains("blake3"),
842            "{err}"
843        );
844    }
845}