Skip to main content

git_internal/internal/pack/
cache.rs

1//! Multi-tier cache for pack decoding that combines an in-memory LRU with spill-to-disk storage and
2//! bookkeeping for concurrent rebuild tasks.
3
4use std::{
5    fs, io,
6    path::{Path, PathBuf},
7    sync::{
8        Arc, Mutex, Once,
9        atomic::{AtomicBool, Ordering},
10    },
11    thread::sleep,
12};
13
14use dashmap::{DashMap, DashSet};
15use lru_mem::{LruCache, entry_size};
16use threadpool::ThreadPool;
17
18use crate::{
19    hash::ObjectHash,
20    internal::pack::cache_object::{ArcWrapper, CacheObject, FileLoadStore, MemSizeRecorder},
21    time_it,
22};
23
24/// Cache format version appended to the disk path so that caches written with an
25/// incompatible serialization format (for example the previous bincode layout, or the
26/// `rkyv-v1` layout whose spill file names were untagged hex and could therefore alias a
27/// SHA-256 and a BLAKE3 object with identical bytes) are ignored instead of causing
28/// deserialization errors or cross-kind reads.
29const CACHE_LAYOUT_VERSION: &str = "rkyv-v2";
30
31/// Trait defining the interface for a multi-tier cache system.
32/// This cache supports insertion and retrieval of objects by both offset and hash,
33/// as well as memory usage tracking and clearing functionality.
34pub trait _Cache {
35    fn new(mem_size: Option<usize>, tmp_path: PathBuf, thread_num: usize) -> Self
36    where
37        Self: Sized;
38    fn get_hash(&self, offset: usize) -> Option<ObjectHash>;
39    fn insert(&self, offset: usize, hash: ObjectHash, obj: CacheObject) -> Arc<CacheObject>;
40    fn get_by_offset(&self, offset: usize) -> Option<Arc<CacheObject>>;
41    fn get_by_hash(&self, h: ObjectHash) -> Option<Arc<CacheObject>>;
42    fn total_inserted(&self) -> usize;
43    fn memory_used(&self) -> usize;
44    fn clear(&self);
45}
46
47impl lru_mem::HeapSize for ObjectHash {
48    fn heap_size(&self) -> usize {
49        0
50    }
51}
52
53/// Multi-tier cache implementation combining an in-memory LRU cache with spill-to-disk storage.
54/// It uses a DashMap for offset-to-hash mapping and a DashSet to track cached hashes.
55/// The cache supports concurrent rebuild tasks using a thread pool.
56pub struct Caches {
57    map_offset: DashMap<usize, ObjectHash>, // offset to hash
58    hash_set: DashSet<ObjectHash>,          // item in the cache
59    resident_hash_set: DashSet<ObjectHash>, // item currently held in the in-memory LRU
60    // dropping large lru cache will take a long time on Windows without multi-thread IO
61    // because "multi-thread IO" clone Arc<CacheObject>, so it won't be dropped in the main thread,
62    // and `CacheObjects` will be killed by OS after Process ends abnormally
63    // Solution: use `mimalloc`
64    lru_cache: Mutex<LruCache<ObjectHash, ArcWrapper<CacheObject>>>,
65    unbounded_cache: Option<DashMap<ObjectHash, Arc<CacheObject>>>,
66    unbounded_offset_cache: Option<DashMap<usize, Arc<CacheObject>>>,
67    mem_size: Option<usize>,
68    tmp_path: PathBuf,
69    path_prefixes: [Once; 256],
70    pool: Arc<ThreadPool>,
71    complete_signal: Arc<AtomicBool>,
72}
73
74impl Caches {
75    /// only get object from memory, not from tmp file
76    fn try_get(&self, hash: ObjectHash) -> Option<Arc<CacheObject>> {
77        let mut map = self.lru_cache.lock().unwrap();
78        map.get(&hash).map(|x| x.data.clone())
79    }
80
81    fn insert_lru_resident(
82        &self,
83        map: &mut LruCache<ObjectHash, ArcWrapper<CacheObject>>,
84        hash: ObjectHash,
85        obj: ArcWrapper<CacheObject>,
86    ) {
87        let size = entry_size(&hash, &obj);
88        if size <= map.max_size() {
89            while map.current_size() + size > map.max_size() {
90                if let Some((evicted_hash, _)) = map.remove_lru() {
91                    self.resident_hash_set.remove(&evicted_hash);
92                } else {
93                    break;
94                }
95            }
96        }
97
98        if map.insert(hash, obj).is_ok() {
99            self.resident_hash_set.insert(hash);
100        } else {
101            self.resident_hash_set.remove(&hash);
102        }
103    }
104
105    /// !IMPORTANT: because of the process of pack, the file must be written / be writing before, so it won't be dead lock
106    /// fall back to temp to get item. **invoker should ensure the hash is in the cache, or it will block forever**
107    fn get_fallback(&self, hash: ObjectHash) -> io::Result<Arc<CacheObject>> {
108        let path = self.generate_temp_path(&self.tmp_path, hash);
109        // read from tmp file
110        let obj = {
111            loop {
112                match Self::read_from_temp(&path) {
113                    Ok(x) => break x,
114                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
115                        sleep(std::time::Duration::from_millis(10));
116                        continue;
117                    }
118                    Err(e) => return Err(e), // other error
119                }
120            }
121        };
122
123        let mut map = self.lru_cache.lock().unwrap();
124        let obj = Arc::new(obj);
125        let mut x = ArcWrapper::new(
126            obj.clone(),
127            self.complete_signal.clone(),
128            Some(self.pool.clone()),
129        );
130        x.set_store_path(path);
131        self.insert_lru_resident(&mut map, hash, x);
132        Ok(obj)
133    }
134
135    /// generate the temp file path: `<tmp>/<layout>/<2 hex>/<kind>-<hex>`.
136    ///
137    /// The file name carries the hash kind (ADR-GI-B3-05): SHA-256 and BLAKE3 IDs print as
138    /// the same 64 hex characters, so an untagged name would let one kind read the other's
139    /// spilled object. The two-character subdirectory keeps the per-first-byte `Once`
140    /// directory creation shared across kinds.
141    fn generate_temp_path(&self, tmp_path: &Path, hash: ObjectHash) -> PathBuf {
142        let kind = hash.kind().as_str();
143        let hash_str = hash._to_string();
144        // Reserve capacity for base path, layout, 2-char subdir, kind tag, hex hash and separators
145        let mut path = PathBuf::with_capacity(
146            self.tmp_path.capacity() + CACHE_LAYOUT_VERSION.len() + kind.len() + hash_str.len() + 8,
147        );
148        path.push(tmp_path);
149        path.push(CACHE_LAYOUT_VERSION);
150        path.push(&hash_str[..2]); // use first 2 chars as the directory
151        self.path_prefixes[hash.as_ref()[0] as usize].call_once(|| {
152            // Check if the directory exists, if not, create it
153            if !path.exists() {
154                fs::create_dir_all(&path).unwrap();
155            }
156        });
157        path.push(format!("{kind}-{hash_str}"));
158        path
159    }
160
161    /// read CacheObject from temp file
162    fn read_from_temp(path: &Path) -> io::Result<CacheObject> {
163        let obj = CacheObject::f_load(path)?;
164        // Deserializing will also create an object but without Construction outside and `::new()`
165        // So if you want to do sth. while Constructing, impl Deserialize trait yourself
166        obj.record_mem_size();
167        Ok(obj)
168    }
169
170    /// number of queued tasks in the thread pool
171    pub fn queued_tasks(&self) -> usize {
172        self.pool.queued_count()
173    }
174
175    pub(crate) fn is_unbounded(&self) -> bool {
176        self.mem_size.is_none()
177    }
178
179    /// memory used by the index (exclude lru_cache which is contained in CacheObject::get_mem_size())
180    pub fn memory_used_index(&self) -> usize {
181        let hash_cache_size = if let Some(cache) = &self.unbounded_cache {
182            cache.capacity()
183                * (std::mem::size_of::<ObjectHash>() + std::mem::size_of::<Arc<CacheObject>>())
184        } else {
185            self.hash_set.capacity() * std::mem::size_of::<ObjectHash>()
186        };
187        let offset_cache_size = if let Some(cache) = &self.unbounded_offset_cache {
188            cache.capacity()
189                * (std::mem::size_of::<usize>() + std::mem::size_of::<Arc<CacheObject>>())
190        } else {
191            self.map_offset.capacity()
192                * (std::mem::size_of::<usize>() + std::mem::size_of::<ObjectHash>())
193        };
194        hash_cache_size + offset_cache_size
195    }
196
197    pub(crate) fn shutdown(&self) {
198        time_it!("Caches clear", {
199            self.complete_signal.store(true, Ordering::Release);
200            self.pool.join();
201            self.lru_cache
202                .lock()
203                .unwrap_or_else(|e| e.into_inner())
204                .clear();
205            if let Some(cache) = &self.unbounded_cache {
206                cache.clear();
207                cache.shrink_to_fit();
208            }
209            if let Some(cache) = &self.unbounded_offset_cache {
210                cache.clear();
211                cache.shrink_to_fit();
212            }
213            self.hash_set.clear();
214            self.hash_set.shrink_to_fit();
215            self.resident_hash_set.clear();
216            self.resident_hash_set.shrink_to_fit();
217            self.map_offset.clear();
218            self.map_offset.shrink_to_fit();
219        });
220    }
221
222    /// remove the tmp dir
223    pub fn remove_tmp_dir(&self) -> io::Result<()> {
224        time_it!("Remove tmp dir", {
225            if self.tmp_path.exists() {
226                match fs::remove_dir_all(&self.tmp_path) {
227                    Ok(()) => {}
228                    Err(e) if e.kind() == io::ErrorKind::NotFound => {}
229                    Err(e) => return Err(e),
230                }
231
232                if let Some(parent) = self.tmp_path.parent() {
233                    let is_cache_temp = parent
234                        .file_name()
235                        .and_then(|n| n.to_str())
236                        .map(|n| n == ".cache_temp")
237                        .unwrap_or(false);
238                    if is_cache_temp {
239                        match fs::remove_dir(parent) {
240                            Ok(()) => {}
241                            Err(e)
242                                if matches!(
243                                    e.kind(),
244                                    io::ErrorKind::DirectoryNotEmpty | io::ErrorKind::NotFound
245                                ) => {}
246                            Err(e) => return Err(e),
247                        }
248                    }
249                }
250            }
251
252            Ok(())
253        })
254    }
255
256    pub fn remove_unbounded(&self, offset: usize, hash: ObjectHash) {
257        if self.unbounded_cache.is_some() && self.lru_cache.lock().unwrap().remove(&hash).is_some()
258        {
259            self.resident_hash_set.remove(&hash);
260        }
261        if let Some(cache) = &self.unbounded_offset_cache {
262            cache.remove(&offset);
263        }
264        if let Some(cache) = &self.unbounded_cache {
265            cache.remove(&hash);
266        }
267    }
268}
269
270impl _Cache for Caches {
271    /// @param size: the size of the memory lru cache. **None means no limit**
272    /// @param tmp_path: the path to store the cache object in the tmp file
273    fn new(mem_size: Option<usize>, tmp_path: PathBuf, thread_num: usize) -> Self
274    where
275        Self: Sized,
276    {
277        // `None` means no limit, so no need to create the tmp dir
278        if mem_size.is_some() {
279            fs::create_dir_all(&tmp_path).unwrap();
280        }
281
282        Caches {
283            map_offset: DashMap::new(),
284            hash_set: DashSet::new(),
285            resident_hash_set: DashSet::new(),
286            lru_cache: Mutex::new(LruCache::new(mem_size.unwrap_or(usize::MAX))),
287            unbounded_cache: mem_size.is_none().then(DashMap::new),
288            unbounded_offset_cache: mem_size.is_none().then(DashMap::new),
289            mem_size,
290            tmp_path,
291            path_prefixes: [const { Once::new() }; 256],
292            pool: Arc::new(ThreadPool::new(thread_num)),
293            complete_signal: Arc::new(AtomicBool::new(false)),
294        }
295    }
296
297    fn get_hash(&self, offset: usize) -> Option<ObjectHash> {
298        if let Some(cache) = &self.unbounded_offset_cache {
299            return cache.get(&offset).and_then(|obj| obj.base_object_hash());
300        }
301        self.map_offset.get(&offset).map(|x| *x)
302    }
303
304    fn insert(&self, offset: usize, hash: ObjectHash, obj: CacheObject) -> Arc<CacheObject> {
305        let obj_arc = Arc::new(obj);
306        if let Some(cache) = &self.unbounded_cache {
307            cache.insert(hash, obj_arc.clone());
308            if let Some(offset_cache) = &self.unbounded_offset_cache {
309                offset_cache.insert(offset, obj_arc.clone());
310            }
311            let mut map = self.lru_cache.lock().unwrap();
312            let a_obj = ArcWrapper::new(
313                obj_arc.clone(),
314                self.complete_signal.clone(),
315                Some(self.pool.clone()),
316            );
317            self.insert_lru_resident(&mut map, hash, a_obj);
318        } else {
319            // ? whether insert to cache directly or only write to tmp file
320            //
321            // Scope the `lru_cache` guard so it is released BEFORE we write
322            // `map_offset` below. Holding lru across the `map_offset` DashMap
323            // write, while get_by_offset() takes the `map_offset` shard read
324            // lock and then locks lru, is an ABBA lock-order inversion that
325            // deadlocks concurrent pack decoding. (This inner scope existed in
326            // 0.7.6 and was lost when insert was refactored to use
327            // `insert_lru_resident`; its removal introduced the deadlock.)
328            {
329                let mut map = self.lru_cache.lock().unwrap();
330                let mut a_obj = ArcWrapper::new(
331                    obj_arc.clone(),
332                    self.complete_signal.clone(),
333                    Some(self.pool.clone()),
334                );
335                if self.mem_size.is_some() {
336                    a_obj.set_store_path(self.generate_temp_path(&self.tmp_path, hash));
337                }
338                self.insert_lru_resident(&mut map, hash, a_obj);
339            }
340            self.hash_set.insert(hash);
341            // order matters as for reading in 'get_by_offset()': the object is
342            // made resident in lru above before its offset becomes visible here.
343            self.map_offset.insert(offset, hash);
344        }
345
346        obj_arc
347    }
348
349    /// get object by offset, from memory or tmp file
350    fn get_by_offset(&self, offset: usize) -> Option<Arc<CacheObject>> {
351        // IMPORTANT: never hold a `map_offset` / `unbounded_offset_cache`
352        // DashMap shard read-guard across a `lru_cache` lock. `insert()` holds
353        // the `lru_cache` mutex across a `map_offset` write (lru -> shard), so
354        // taking the shard read-lock here and then locking `lru_cache`
355        // (shard -> lru) forms an ABBA lock-order inversion that deadlocks
356        // concurrent pack decoding. Copy the hash out and drop the shard
357        // read-guard BEFORE calling into `try_get` / `get_by_hash` (both of
358        // which lock `lru_cache`).
359        if let Some(cache) = &self.unbounded_offset_cache {
360            let hash = cache.get(&offset).and_then(|obj| obj.base_object_hash());
361            return hash.and_then(|hash| self.try_get(hash));
362        }
363
364        let hash = self.map_offset.get(&offset).map(|x| *x);
365        hash.and_then(|hash| self.get_by_hash(hash))
366    }
367
368    /// get object by hash, from memory or tmp file
369    fn get_by_hash(&self, hash: ObjectHash) -> Option<Arc<CacheObject>> {
370        if self.mem_size.is_none() {
371            if let Some(cache) = &self.unbounded_cache
372                && !cache.contains_key(&hash)
373            {
374                return None;
375            }
376            return self.try_get(hash);
377        }
378
379        // check if the hash is in the cache( lru or tmp file)
380        if self.hash_set.contains(&hash) {
381            if !self.resident_hash_set.contains(&hash) {
382                return self.get_fallback(hash).ok();
383            }
384            match self.try_get(hash) {
385                Some(x) => Some(x),
386                None => {
387                    if self.mem_size.is_none() {
388                        panic!("should not be here when mem_size is not set")
389                    }
390                    self.get_fallback(hash).ok()
391                }
392            }
393        } else {
394            None
395        }
396    }
397
398    fn total_inserted(&self) -> usize {
399        if self.mem_size.is_some() {
400            self.hash_set.len()
401        } else if let Some(cache) = &self.unbounded_offset_cache {
402            cache.len()
403        } else {
404            self.map_offset.len()
405        }
406    }
407    fn memory_used(&self) -> usize {
408        self.lru_cache.lock().unwrap().current_size() + self.memory_used_index()
409    }
410    fn clear(&self) {
411        self.shutdown();
412
413        assert_eq!(self.pool.queued_count(), 0);
414        assert_eq!(self.pool.active_count(), 0);
415        assert_eq!(self.lru_cache.lock().unwrap().len(), 0);
416    }
417}
418
419#[cfg(test)]
420mod test {
421    use std::{sync::Arc, thread};
422
423    use super::*;
424    use crate::{
425        hash::{HashKind, ObjectHash, set_hash_kind_for_test},
426        internal::{object::types::ObjectType, pack::cache_object::CacheObjectInfo},
427    };
428
429    /// Helper to build a base CacheObject with given size and hash.
430    fn make_obj(size: usize, hash: ObjectHash) -> CacheObject {
431        CacheObject {
432            info: CacheObjectInfo::BaseObject(ObjectType::Blob, hash),
433            data_decompressed: vec![0; size],
434            mem_recorder: None,
435            offset: 0,
436            crc32: 0,
437            is_delta_in_pack: false,
438            known_hash: None,
439        }
440    }
441
442    /// test single-threaded cache behavior with different hash kinds and capacities
443    #[test]
444    fn test_cache_single_thread() {
445        for (kind, cap, size_ab, size_c) in [
446            (HashKind::Sha1, 2048usize, 800usize, 1700usize),
447            (HashKind::Sha256, 4096usize, 1500usize, 3000usize),
448        ] {
449            let _guard = set_hash_kind_for_test(kind);
450            // A private temp dir (honours TMPDIR) instead of a repo-relative path, so the
451            // test is isolated and runs in read-only checkouts (GC-11).
452            let tmp_dir = tempfile::tempdir().unwrap();
453            let tmp_path = tmp_dir.path().join("cache");
454
455            let cache = Caches::new(Some(cap), tmp_path, 1);
456            let a_hash = ObjectHash::new(String::from("a").as_bytes());
457            let b_hash = ObjectHash::new(String::from("b").as_bytes());
458            let c_hash = ObjectHash::new(String::from("c").as_bytes());
459
460            let a = make_obj(size_ab, a_hash);
461            let b = make_obj(size_ab, b_hash);
462            let c = make_obj(size_c, c_hash);
463
464            // insert a
465            cache.insert(a.offset, a_hash, a.clone());
466            assert!(cache.hash_set.contains(&a_hash));
467            assert!(cache.try_get(a_hash).is_some());
468
469            // insert b, a should still be in cache
470            cache.insert(b.offset, b_hash, b.clone());
471            assert!(cache.hash_set.contains(&b_hash));
472            assert!(cache.try_get(b_hash).is_some());
473            assert!(cache.try_get(a_hash).is_some());
474
475            // insert c which will evict both a and b
476            cache.insert(c.offset, c_hash, c.clone());
477            assert!(cache.try_get(a_hash).is_none());
478            assert!(cache.try_get(b_hash).is_none());
479            assert!(cache.try_get(c_hash).is_some());
480            assert!(cache.get_by_hash(c_hash).is_some());
481
482            // Join the spill workers before the temp dir goes away, then prove the cleanup:
483            // `close` fails if anything is still being written into the directory.
484            cache.shutdown();
485            tmp_dir.close().unwrap();
486        }
487    }
488
489    /// consider the multi-threaded scenario where different threads use different hash kinds
490    #[test]
491    fn test_cache_multi_thread_mixed_hash_kinds() {
492        let tmp_dir = tempfile::tempdir().unwrap();
493        let tmp_path = tmp_dir.path().join("cache");
494
495        let cache = Arc::new(Caches::new(Some(4096), tmp_path, 2));
496
497        let cache_sha1 = Arc::clone(&cache);
498        let handle_sha1 = thread::spawn(move || {
499            let _g = set_hash_kind_for_test(HashKind::Sha1);
500            let hash = ObjectHash::new(b"sha1-entry");
501            let obj = CacheObject {
502                info: CacheObjectInfo::BaseObject(ObjectType::Blob, hash),
503                data_decompressed: vec![0; 800],
504                mem_recorder: None,
505                offset: 1,
506                crc32: 0,
507                is_delta_in_pack: false,
508                known_hash: None,
509            };
510            cache_sha1.insert(obj.offset, hash, obj.clone());
511            assert!(cache_sha1.hash_set.contains(&hash));
512            assert!(cache_sha1.try_get(hash).is_some());
513        });
514
515        let cache_sha256 = Arc::clone(&cache);
516        let handle_sha256 = thread::spawn(move || {
517            let _g = set_hash_kind_for_test(HashKind::Sha256);
518            let hash = ObjectHash::new(b"sha256-entry");
519            let obj = CacheObject {
520                info: CacheObjectInfo::BaseObject(ObjectType::Blob, hash),
521                data_decompressed: vec![0; 1500],
522                mem_recorder: None,
523                offset: 2,
524                crc32: 0,
525                is_delta_in_pack: false,
526                known_hash: None,
527            };
528            cache_sha256.insert(obj.offset, hash, obj.clone());
529            assert!(cache_sha256.hash_set.contains(&hash));
530            assert!(cache_sha256.try_get(hash).is_some());
531        });
532
533        handle_sha1.join().unwrap();
534        handle_sha256.join().unwrap();
535
536        assert_eq!(cache.total_inserted(), 2);
537        cache.shutdown();
538        tmp_dir.close().unwrap();
539    }
540
541    #[test]
542    fn test_remove_tmp_dir_does_not_panic_when_cleanup_fails() {
543        let dir = tempfile::tempdir().unwrap();
544        let tmp_path = dir.path().join("not-a-directory");
545        fs::write(&tmp_path, b"cache marker").unwrap();
546        let cache = Caches::new(None, tmp_path, 1);
547
548        let result =
549            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cache.remove_tmp_dir()));
550
551        assert!(result.is_ok(), "cache cleanup should not panic");
552        assert!(
553            result.unwrap().is_err(),
554            "cleanup failure should be returned"
555        );
556    }
557
558    #[test]
559    fn test_unbounded_cache_skips_hash_set_index() {
560        let _guard = set_hash_kind_for_test(HashKind::Sha1);
561        let tmp_dir = tempfile::tempdir().unwrap();
562        let tmp_path = tmp_dir.path().join("cache");
563        let cache = Caches::new(None, tmp_path, 1);
564        let hash = ObjectHash::new(b"unbounded-entry");
565        let obj = make_obj(64, hash);
566
567        cache.insert(obj.offset, hash, obj);
568
569        assert!(cache.hash_set.is_empty());
570        assert!(cache.resident_hash_set.contains(&hash));
571        assert_eq!(cache.total_inserted(), 1);
572        assert_eq!(cache.get_hash(0), Some(hash));
573        assert!(cache.try_get(hash).is_some());
574        assert!(cache.get_by_hash(hash).is_some());
575        assert!(
576            cache
577                .get_by_hash(ObjectHash::new(b"missing-entry"))
578                .is_none()
579        );
580        assert!(cache.get_by_offset(0).is_some());
581        assert!(cache.memory_used_index() > 0);
582        cache.shutdown();
583        tmp_dir.close().unwrap();
584    }
585
586    #[test]
587    fn test_bounded_cache_tracks_resident_entries() {
588        let _guard = set_hash_kind_for_test(HashKind::Sha1);
589        let tmp_dir = tempfile::tempdir().unwrap();
590        let tmp_path = tmp_dir.path().join("cache");
591
592        let cache = Caches::new(Some(2048), tmp_path, 1);
593        let a_hash = ObjectHash::new(b"resident-a");
594        let b_hash = ObjectHash::new(b"resident-b");
595        let a = make_obj(1800, a_hash);
596        let b = make_obj(1800, b_hash);
597
598        cache.insert(a.offset, a_hash, a);
599        assert!(cache.hash_set.contains(&a_hash));
600        assert!(cache.resident_hash_set.contains(&a_hash));
601
602        cache.insert(b.offset + 1, b_hash, b);
603        assert!(cache.hash_set.contains(&a_hash));
604        assert!(cache.hash_set.contains(&b_hash));
605        assert!(!cache.resident_hash_set.contains(&a_hash));
606        assert!(cache.resident_hash_set.contains(&b_hash));
607        cache.shutdown();
608        tmp_dir.close().unwrap();
609    }
610
611    /// Regression test for the ABBA lock-order inversion between the `lru_cache`
612    /// `Mutex` and the `map_offset` `DashMap` shard lock that deadlocked pack
613    /// decoding (git-internal <= 0.8.2).
614    ///
615    /// Two code paths acquired the two locks in opposite order:
616    ///   * `insert()` (bounded path): lock `lru_cache`, then — while still
617    ///     holding it — write `map_offset`  (order: lru -> shard).
618    ///   * `get_by_offset()`: hold the `map_offset` shard read-guard across
619    ///     `get_by_hash()`/`try_get()`, which lock `lru_cache` (order: shard -> lru).
620    ///
621    /// When a base `insert()` and a delta `get_by_offset()` hit the same
622    /// `DashMap` shard concurrently they wait on each other forever. This test
623    /// hammers both paths on a tiny offset space (so they collide on the same
624    /// shard) from many threads and fails via a watchdog timeout if they wedge.
625    /// It completes near-instantly once the inversion is fixed.
626    #[test]
627    fn test_cache_concurrent_insert_get_by_offset_no_deadlock() {
628        let _guard = set_hash_kind_for_test(HashKind::Sha1);
629        let tmp = std::env::temp_dir().join(format!(
630            "gi_cache_abba_{}_{:?}",
631            std::process::id(),
632            thread::current().id()
633        ));
634        if tmp.exists() {
635            let _ = fs::remove_dir_all(&tmp);
636        }
637
638        // Bounded cache (mem_size = Some) exercises the buggy lru -> map_offset
639        // ordering in insert(). Sized large enough that every object stays
640        // resident, so get_by_offset() resolves via try_get() (which locks
641        // lru_cache) rather than the disk fallback — keeping the race tight and
642        // deterministic without depending on eviction.
643        let cache = Arc::new(Caches::new(Some(1 << 20), tmp.clone(), 8));
644
645        // A small offset space keeps writers and readers colliding on the same
646        // DashMap shards, which is what the inversion needs to wedge.
647        const OFFSETS: usize = 8;
648        const ITERS: usize = 20_000;
649        const WRITERS: usize = 6;
650        const READERS: usize = 6;
651
652        let hashes: Arc<Vec<ObjectHash>> = Arc::new(
653            (0..OFFSETS)
654                .map(|i| ObjectHash::new(format!("obj-{i}").as_bytes()))
655                .collect(),
656        );
657
658        let (done_tx, done_rx) = std::sync::mpsc::channel();
659        let mut handles = Vec::new();
660
661        for _ in 0..WRITERS {
662            let cache = cache.clone();
663            let hashes = hashes.clone();
664            let done_tx = done_tx.clone();
665            handles.push(thread::spawn(move || {
666                let _g = set_hash_kind_for_test(HashKind::Sha1);
667                for k in 0..ITERS {
668                    let o = k % OFFSETS;
669                    let obj = CacheObject {
670                        info: CacheObjectInfo::BaseObject(ObjectType::Blob, hashes[o]),
671                        data_decompressed: vec![0u8; 64],
672                        mem_recorder: None,
673                        offset: o,
674                        crc32: 0,
675                        is_delta_in_pack: false,
676                        known_hash: None,
677                    };
678                    cache.insert(o, hashes[o], obj);
679                }
680                let _ = done_tx.send(());
681            }));
682        }
683
684        for _ in 0..READERS {
685            let cache = cache.clone();
686            let done_tx = done_tx.clone();
687            handles.push(thread::spawn(move || {
688                let _g = set_hash_kind_for_test(HashKind::Sha1);
689                for k in 0..ITERS {
690                    let o = k % OFFSETS;
691                    let _ = cache.get_by_offset(o);
692                }
693                let _ = done_tx.send(());
694            }));
695        }
696        drop(done_tx);
697
698        // Watchdog: every worker must finish well within the timeout. On the
699        // pre-fix code the pool wedges (lru_cache <-> map_offset) and this times
700        // out; on fixed code all workers finish in well under a second.
701        let workers = WRITERS + READERS;
702        for finished in 0..workers {
703            if done_rx
704                .recv_timeout(std::time::Duration::from_secs(30))
705                .is_err()
706            {
707                panic!(
708                    "cache deadlock: only {finished}/{workers} workers finished within 30s — \
709                     the lru_cache <-> map_offset ABBA lock-order inversion has regressed"
710                );
711            }
712        }
713
714        for h in handles {
715            h.join().unwrap();
716        }
717        // Drain the spill thread-pool before deleting the temp dir so in-flight
718        // f_save tasks don't race with cleanup.
719        cache.clear();
720        let _ = fs::remove_dir_all(&tmp);
721    }
722
723    /// Spill files are namespaced by hash kind: a SHA-256 and a BLAKE3 object with identical
724    /// 32 bytes never share a path, and each is read back with its own data after eviction.
725    #[test]
726    fn blake3_spill_namespace() {
727        let _guard = set_hash_kind_for_test(HashKind::Sha1);
728        let tmp = tempfile::tempdir().unwrap();
729        let tmp_path = tmp.path().join("spill");
730        let cache = Caches::new(Some(1024), tmp_path.clone(), 1);
731
732        let sha256_hash = ObjectHash::Sha256([0x42; 32]);
733        let blake3_hash = ObjectHash::Blake3([0x42; 32]);
734        assert_eq!(sha256_hash.to_string(), blake3_hash.to_string());
735        assert_ne!(sha256_hash, blake3_hash);
736
737        let sha256_path = cache.generate_temp_path(&tmp_path, sha256_hash);
738        let blake3_path = cache.generate_temp_path(&tmp_path, blake3_hash);
739        assert_ne!(sha256_path, blake3_path);
740        assert!(
741            sha256_path
742                .file_name()
743                .unwrap()
744                .to_str()
745                .unwrap()
746                .starts_with("sha256-")
747        );
748        assert!(
749            blake3_path
750                .file_name()
751                .unwrap()
752                .to_str()
753                .unwrap()
754                .starts_with("blake3-")
755        );
756        assert_eq!(sha256_path.parent(), blake3_path.parent());
757        assert!(sha256_path.to_str().unwrap().contains(CACHE_LAYOUT_VERSION));
758
759        let mut sha256_obj = make_obj(700, sha256_hash);
760        sha256_obj.data_decompressed = vec![1; 700];
761        sha256_obj.offset = 1;
762        let mut blake3_obj = make_obj(800, blake3_hash);
763        blake3_obj.data_decompressed = vec![2; 800];
764        blake3_obj.offset = 2;
765        let mut third = make_obj(900, ObjectHash::Blake3([0x99; 32]));
766        third.offset = 3;
767
768        cache.insert(1, sha256_hash, sha256_obj);
769        cache.insert(2, blake3_hash, blake3_obj); // evicts the SHA-256 object to disk
770        cache.insert(3, ObjectHash::Blake3([0x99; 32]), third); // evicts the BLAKE3 object to disk
771        assert!(cache.hash_set.contains(&sha256_hash));
772        assert!(cache.hash_set.contains(&blake3_hash));
773
774        let back_sha256 = cache
775            .get_by_hash(sha256_hash)
776            .expect("spilled sha256 object");
777        assert_eq!(back_sha256.data_decompressed, vec![1; 700]);
778        assert_eq!(back_sha256.base_object_hash(), Some(sha256_hash));
779        let back_blake3 = cache
780            .get_by_hash(blake3_hash)
781            .expect("spilled blake3 object");
782        assert_eq!(back_blake3.data_decompressed, vec![2; 800]);
783        assert_eq!(back_blake3.base_object_hash(), Some(blake3_hash));
784        assert_eq!(cache.get_hash(1), Some(sha256_hash));
785        assert_eq!(cache.get_hash(2), Some(blake3_hash));
786        assert!(sha256_path.exists() && blake3_path.exists());
787    }
788}