heddle-objects 0.15.4

An AI-native version control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::HashSet,
    fs,
    fs::File,
    path::{Path, PathBuf},
    sync::{Mutex, OnceLock},
    time::SystemTime,
};

use memmap2::{Mmap, MmapOptions};

use super::{
    CHECKSUM_CHUNK_BYTES, CHECKSUM_LEN, HEADER_LEN, INDEX_MAGIC, LARGE_OFFSET_FLAG, MAGIC,
    MAX_CHAIN_DEPTH, RECORD_BLOCK_ENTRIES, TRAILER_HEADER_LEN, TRAILER_MAGIC, VERSION,
    checked_slice,
    codec::{
        Dictionary, LookupState, decode_anchor, decode_delta, lookup_record, parse_record_header,
        record_base_distance,
    },
    invalid, read_u16, read_u32, read_u64, usize_from_u64,
};
use crate::{
    object::{ContentHash, Tree, TreeEntry},
    store::{HeddleError, Result},
};

type DecodedIndex = (Vec<([u8; 32], u32)>, Vec<u64>);

pub(crate) struct Npk1Pack {
    mmap: Mmap,
    dictionary: Dictionary,
    records_offset: usize,
    record_offsets: Vec<u64>,
    object_index: Vec<([u8; 32], u32)>,
    trailer_offset: usize,
    chunk_hashes: Vec<[u8; CHECKSUM_LEN]>,
    verified_chunks: Mutex<Vec<bool>>,
}

impl Npk1Pack {
    pub(crate) fn open(path: &Path) -> Result<Self> {
        Self::open_with_validation(path, true)
    }

    fn open_direct(path: &Path) -> Result<Self> {
        Self::open_with_validation(path, false)
    }

    fn open_with_validation(path: &Path, verify_all: bool) -> Result<Self> {
        let file = File::open(path)?;
        let len = usize::try_from(file.metadata()?.len())
            .map_err(|_| invalid("pack exceeds address space"))?;
        if len < HEADER_LEN + TRAILER_HEADER_LEN + CHECKSUM_LEN {
            return Err(invalid(
                "pack is shorter than its header and checksum manifest",
            ));
        }
        // SAFETY: the mapping is read-only and owns no references into a
        // mutable buffer. NPK1 files are immutable after their atomic rename;
        // repack unlinks old generations only after readers have dropped the
        // manager lock, while an existing mmap remains valid after unlink.
        let mmap = unsafe { MmapOptions::new().map(&file)? };
        let bytes = mmap.as_ref();
        if checked_slice(bytes, 0, 4, "pack magic")? != MAGIC {
            return Err(invalid("invalid pack magic"));
        }
        let version = read_u32(bytes, 4, "pack version")?;
        if version != VERSION {
            return Err(HeddleError::StorageFormatTooNew {
                storage: path.display().to_string(),
                found: version,
                supported: VERSION,
            });
        }
        let object_count = read_u32(bytes, 8, "object count")? as usize;
        if bytes[12] as usize != MAX_CHAIN_DEPTH {
            return Err(invalid("unsupported chain-depth contract"));
        }
        if bytes[13] != 0 || bytes[56..64].iter().any(|byte| *byte != 0) {
            return Err(invalid("non-zero reserved header field"));
        }
        if read_u16(bytes, 14, "record block size")? as usize != RECORD_BLOCK_ENTRIES {
            return Err(invalid("unsupported record block size"));
        }
        let name_offset = usize_from_u64(read_u64(bytes, 16, "name offset")?, "name offset")?;
        let target_offset = usize_from_u64(read_u64(bytes, 24, "target offset")?, "target offset")?;
        let records_offset =
            usize_from_u64(read_u64(bytes, 32, "records offset")?, "records offset")?;
        let index_offset = usize_from_u64(read_u64(bytes, 40, "index offset")?, "index offset")?;
        let trailer_offset =
            usize_from_u64(read_u64(bytes, 48, "trailer offset")?, "trailer offset")?;
        if name_offset != HEADER_LEN
            || !(name_offset <= target_offset
                && target_offset <= records_offset
                && records_offset <= index_offset
                && index_offset <= trailer_offset)
            || trailer_offset >= len
        {
            return Err(invalid("invalid pack section offsets"));
        }
        let chunk_hashes = decode_checksum_trailer(&bytes[trailer_offset..], trailer_offset)?;
        let mut verified_chunks = vec![false; chunk_hashes.len()];
        verify_range_impl(
            bytes,
            trailer_offset,
            &chunk_hashes,
            &mut verified_chunks,
            0,
            HEADER_LEN,
        )?;
        verify_range_impl(
            bytes,
            trailer_offset,
            &chunk_hashes,
            &mut verified_chunks,
            name_offset,
            records_offset - name_offset,
        )?;
        verify_range_impl(
            bytes,
            trailer_offset,
            &chunk_hashes,
            &mut verified_chunks,
            index_offset,
            trailer_offset - index_offset,
        )?;
        let dictionary = Dictionary::decode(
            &bytes[name_offset..target_offset],
            &bytes[target_offset..records_offset],
        )?;
        let (object_index, record_offsets) = decode_index(
            &bytes[index_offset..trailer_offset],
            object_count,
            index_offset - records_offset,
        )?;
        let pack = Self {
            mmap,
            dictionary,
            records_offset,
            record_offsets,
            object_index,
            trailer_offset,
            chunk_hashes,
            verified_chunks: Mutex::new(verified_chunks),
        };
        if verify_all {
            pack.verify_range(0, trailer_offset)?;
            pack.validate_record_graph()?;
        }
        Ok(pack)
    }

    pub(super) fn contains(&self, expected: &ContentHash) -> bool {
        self.object_index
            .binary_search_by_key(expected.as_bytes(), |(hash, _)| *hash)
            .is_ok()
    }

    pub(crate) fn ids(&self) -> impl Iterator<Item = ContentHash> + '_ {
        self.object_index
            .iter()
            .map(|(hash, _)| ContentHash::from_bytes(*hash))
    }

    fn object_ordinal(&self, expected: &ContentHash) -> Result<usize> {
        let index = self
            .object_index
            .binary_search_by_key(expected.as_bytes(), |(hash, _)| *hash)
            .map_err(|_| HeddleError::NotFound(format!("NPK1 tree {expected}")))?;
        Ok(self.object_index[index].1 as usize)
    }

    fn record_bounds(&self, ordinal: usize) -> Result<(usize, usize)> {
        let start = *self
            .record_offsets
            .get(ordinal)
            .ok_or_else(|| invalid("record ordinal out of bounds"))?;
        let end = *self
            .record_offsets
            .get(ordinal + 1)
            .ok_or_else(|| invalid("record end ordinal out of bounds"))?;
        let start = usize_from_u64(start, "record offset")?;
        let len = usize_from_u64(
            end.checked_sub(start as u64)
                .ok_or_else(|| invalid("record offsets are reversed"))?,
            "record length",
        )?;
        let absolute = self
            .records_offset
            .checked_add(start)
            .ok_or_else(|| invalid("absolute record offset overflow"))?;
        Ok((absolute, len))
    }

    fn record_unverified(&self, ordinal: usize) -> Result<&[u8]> {
        let (absolute, len) = self.record_bounds(ordinal)?;
        checked_slice(&self.mmap, absolute, len, "record")
    }

    fn record(&self, ordinal: usize) -> Result<&[u8]> {
        let (absolute, len) = self.record_bounds(ordinal)?;
        self.verify_range(absolute, len)?;
        checked_slice(&self.mmap, absolute, len, "record")
    }

    fn verify_range(&self, offset: usize, len: usize) -> Result<()> {
        let mut verified = self
            .verified_chunks
            .lock()
            .map_err(|_| invalid("checksum cache lock is poisoned"))?;
        verify_range_impl(
            &self.mmap,
            self.trailer_offset,
            &self.chunk_hashes,
            &mut verified,
            offset,
            len,
        )
    }

    fn validate_record_graph(&self) -> Result<()> {
        let mut depths = Vec::with_capacity(self.object_index.len());
        for ordinal in 0..self.object_index.len() {
            let record = self.record_unverified(ordinal)?;
            let _ = parse_record_header(record)?;
            let depth = match record_base_distance(record)? {
                None => 0,
                Some(distance) => {
                    if distance == 0 || distance > ordinal {
                        return Err(invalid("delta base is not strictly backward"));
                    }
                    depths[ordinal - distance] + 1
                }
            };
            if depth > MAX_CHAIN_DEPTH {
                return Err(invalid("delta chain exceeds the depth bound"));
            }
            depths.push(depth);
        }
        Ok(())
    }

    pub(crate) fn resolve(&self, expected: &ContentHash) -> Result<Tree> {
        let mut ordinal = self.object_ordinal(expected)?;
        let mut chain = Vec::with_capacity(MAX_CHAIN_DEPTH + 1);
        let mut deltas = 0usize;
        loop {
            chain.push(ordinal);
            let record = self.record(ordinal)?;
            let Some(distance) = record_base_distance(record)? else {
                break;
            };
            deltas += 1;
            if deltas > MAX_CHAIN_DEPTH || distance == 0 || distance > ordinal {
                return Err(invalid("invalid or over-depth delta chain"));
            }
            ordinal -= distance;
        }
        let anchor = chain
            .pop()
            .ok_or_else(|| invalid("empty resolution chain"))?;
        let mut tree = decode_anchor(self.record(anchor)?, &self.dictionary)?;
        while let Some(delta) = chain.pop() {
            tree = decode_delta(self.record(delta)?, &tree, &self.dictionary)?;
        }
        let found = tree.hash();
        if found != *expected {
            return Err(HeddleError::Corruption {
                expected: *expected,
                found,
            });
        }
        Ok(tree)
    }

    pub(super) fn lookup(&self, expected: &ContentHash, name: &str) -> Result<Option<TreeEntry>> {
        let Some(wanted_name) = self.dictionary.name_ids.get(name).copied() else {
            return Ok(None);
        };
        let mut ordinal = self.object_ordinal(expected)?;
        let mut deltas = 0usize;
        loop {
            let (absolute, len) = self.record_bounds(ordinal)?;
            let record = checked_slice(&self.mmap, absolute, len, "record")?;
            // The tag, fixed set of prefix varints, and block count occupy at
            // most 32 bytes. Verify through them before trusting block_count
            // for the descriptor allocation, including across a chunk edge.
            self.verify_range(absolute, len.min(64))?;
            let header = parse_record_header(record)?;
            let header_len = header
                .blocks
                .first()
                .map_or(record.len(), |block| block.payload_offset);
            self.verify_range(absolute, header_len)?;
            if let Some(block_index) = header
                .blocks
                .partition_point(|block| block.first_name <= wanted_name)
                .checked_sub(1)
            {
                let block = &header.blocks[block_index];
                self.verify_range(
                    absolute
                        .checked_add(block.payload_offset)
                        .ok_or_else(|| invalid("absolute block offset overflow"))?,
                    block.stored_len,
                )?;
            }
            let (state, entry) = lookup_record(record, &self.dictionary, wanted_name)?;
            match state {
                LookupState::Found => return Ok(entry),
                LookupState::Removed => return Ok(None),
                LookupState::Missing => {}
            }
            let Some(distance) = record_base_distance(record)? else {
                return Ok(None);
            };
            deltas += 1;
            if deltas > MAX_CHAIN_DEPTH || distance == 0 || distance > ordinal {
                return Err(invalid("invalid or over-depth lookup chain"));
            }
            ordinal -= distance;
        }
    }

    #[cfg(test)]
    pub(super) fn depth(&self, expected: &ContentHash) -> Result<usize> {
        let mut ordinal = self.object_ordinal(expected)?;
        let mut depth = 0usize;
        while let Some(distance) = record_base_distance(self.record(ordinal)?)? {
            depth += 1;
            if depth > MAX_CHAIN_DEPTH || distance == 0 || distance > ordinal {
                return Err(invalid("invalid test chain"));
            }
            ordinal -= distance;
        }
        Ok(depth)
    }
}

fn decode_checksum_trailer(bytes: &[u8], data_len: usize) -> Result<Vec<[u8; CHECKSUM_LEN]>> {
    if checked_slice(bytes, 0, 4, "checksum manifest magic")? != TRAILER_MAGIC {
        return Err(invalid("invalid checksum manifest magic"));
    }
    if read_u32(bytes, 4, "checksum chunk size")? as usize != CHECKSUM_CHUNK_BYTES {
        return Err(invalid("unsupported checksum chunk size"));
    }
    let chunk_count = read_u32(bytes, 8, "checksum chunk count")? as usize;
    if chunk_count != data_len.div_ceil(CHECKSUM_CHUNK_BYTES) {
        return Err(invalid("checksum chunk count mismatch"));
    }
    if read_u32(bytes, 12, "checksum manifest reserved field")? != 0 {
        return Err(invalid("non-zero checksum manifest reserved field"));
    }
    let hashes_len = chunk_count
        .checked_mul(CHECKSUM_LEN)
        .ok_or_else(|| invalid("checksum manifest size overflow"))?;
    let checksum_offset = TRAILER_HEADER_LEN
        .checked_add(hashes_len)
        .ok_or_else(|| invalid("checksum manifest size overflow"))?;
    if checksum_offset
        .checked_add(CHECKSUM_LEN)
        .is_none_or(|expected| expected != bytes.len())
    {
        return Err(invalid("checksum manifest length mismatch"));
    }
    if blake3::hash(&bytes[..checksum_offset]).as_bytes()
        != checked_slice(
            bytes,
            checksum_offset,
            CHECKSUM_LEN,
            "checksum manifest checksum",
        )?
    {
        return Err(invalid("checksum manifest checksum mismatch"));
    }
    let mut hashes = Vec::with_capacity(chunk_count);
    for index in 0..chunk_count {
        hashes.push(
            checked_slice(
                bytes,
                TRAILER_HEADER_LEN + index * CHECKSUM_LEN,
                CHECKSUM_LEN,
                "checksum chunk hash",
            )?
            .try_into()
            .map_err(|_| invalid("invalid checksum chunk hash"))?,
        );
    }
    Ok(hashes)
}

fn verify_range_impl(
    bytes: &[u8],
    data_len: usize,
    hashes: &[[u8; CHECKSUM_LEN]],
    verified: &mut [bool],
    offset: usize,
    len: usize,
) -> Result<()> {
    if hashes.len() != verified.len() {
        return Err(invalid("checksum cache length mismatch"));
    }
    let end = offset
        .checked_add(len)
        .ok_or_else(|| invalid("checksum range overflow"))?;
    if end > data_len {
        return Err(invalid("checksum range extends into the manifest"));
    }
    if len == 0 {
        return Ok(());
    }
    let first = offset / CHECKSUM_CHUNK_BYTES;
    let last = (end - 1) / CHECKSUM_CHUNK_BYTES;
    for index in first..=last {
        if *verified
            .get(index)
            .ok_or_else(|| invalid("checksum chunk ordinal out of bounds"))?
        {
            continue;
        }
        let start = index
            .checked_mul(CHECKSUM_CHUNK_BYTES)
            .ok_or_else(|| invalid("checksum chunk offset overflow"))?;
        let chunk_end = start.saturating_add(CHECKSUM_CHUNK_BYTES).min(data_len);
        let chunk = checked_slice(bytes, start, chunk_end - start, "checksum chunk")?;
        let expected = hashes
            .get(index)
            .ok_or_else(|| invalid("checksum hash ordinal out of bounds"))?;
        if blake3::hash(chunk).as_bytes() != expected {
            return Err(invalid(format!("checksum mismatch in chunk {index}")));
        }
        verified[index] = true;
    }
    Ok(())
}

fn decode_index(bytes: &[u8], expected_objects: usize, records_len: usize) -> Result<DecodedIndex> {
    if checked_slice(bytes, 0, 4, "index magic")? != INDEX_MAGIC {
        return Err(invalid("invalid index magic"));
    }
    let object_count = read_u32(bytes, 4, "index object count")? as usize;
    if object_count != expected_objects {
        return Err(invalid("index object count disagrees with pack header"));
    }
    let escape_count = read_u32(bytes, 8, "large-offset count")? as usize;
    if read_u32(bytes, 12, "index reserved field")? != 0 {
        return Err(invalid("non-zero index reserved field"));
    }
    let entries_start = 16usize + 256 * 4;
    let entries_len = object_count
        .checked_mul(36)
        .ok_or_else(|| invalid("index entries overflow"))?;
    let offsets_start = entries_start
        .checked_add(entries_len)
        .ok_or_else(|| invalid("index offset table position overflow"))?;
    let offsets_len = object_count
        .checked_add(1)
        .and_then(|count| count.checked_mul(4))
        .ok_or_else(|| invalid("record offset table overflow"))?;
    let escapes_start = offsets_start
        .checked_add(offsets_len)
        .ok_or_else(|| invalid("large-offset table position overflow"))?;
    let escapes_len = escape_count
        .checked_mul(8)
        .ok_or_else(|| invalid("large-offset table overflow"))?;
    let checksum_offset = escapes_start
        .checked_add(escapes_len)
        .ok_or_else(|| invalid("index checksum position overflow"))?;
    if checksum_offset
        .checked_add(CHECKSUM_LEN)
        .is_none_or(|expected| expected != bytes.len())
    {
        return Err(invalid("index length mismatch"));
    }
    if blake3::hash(&bytes[..checksum_offset]).as_bytes()
        != checked_slice(bytes, checksum_offset, CHECKSUM_LEN, "index checksum")?
    {
        return Err(invalid("index checksum mismatch"));
    }

    let mut fanout = [0u32; 256];
    let mut previous_fanout = 0u32;
    for (index, count) in fanout.iter_mut().enumerate() {
        *count = read_u32(bytes, 16 + index * 4, "fanout row")?;
        if *count < previous_fanout {
            return Err(invalid("index fanout is not monotonic"));
        }
        previous_fanout = *count;
    }
    if fanout[255] as usize != object_count {
        return Err(invalid("index fanout total mismatch"));
    }
    let mut object_index = Vec::with_capacity(object_count);
    let mut seen_ordinals = HashSet::with_capacity(object_count);
    for index in 0..object_count {
        let offset = entries_start + index * 36;
        let hash: [u8; 32] = checked_slice(bytes, offset, 32, "index hash")?
            .try_into()
            .map_err(|_| invalid("invalid index hash"))?;
        if object_index
            .last()
            .is_some_and(|(previous, _)| previous >= &hash)
        {
            return Err(invalid("index hashes are not strictly sorted"));
        }
        let ordinal = read_u32(bytes, offset + 32, "record ordinal")?;
        if ordinal as usize >= object_count || !seen_ordinals.insert(ordinal) {
            return Err(invalid("record ordinal is duplicate or out of bounds"));
        }
        object_index.push((hash, ordinal));
    }
    let mut recomputed_fanout = [0u32; 256];
    for (hash, _) in &object_index {
        recomputed_fanout[hash[0] as usize] += 1;
    }
    let mut cumulative = 0u32;
    for count in &mut recomputed_fanout {
        cumulative += *count;
        *count = cumulative;
    }
    if recomputed_fanout != fanout {
        return Err(invalid("index fanout does not match its hashes"));
    }

    let escapes = (0..escape_count)
        .map(|index| read_u64(bytes, escapes_start + index * 8, "large record offset"))
        .collect::<Result<Vec<_>>>()?;
    let mut record_offsets = Vec::with_capacity(object_count + 1);
    for index in 0..=object_count {
        let encoded = read_u32(bytes, offsets_start + index * 4, "record offset")?;
        let offset = if encoded & LARGE_OFFSET_FLAG == 0 {
            encoded as u64
        } else {
            let escape = (encoded & !LARGE_OFFSET_FLAG) as usize;
            *escapes
                .get(escape)
                .ok_or_else(|| invalid("large record offset ordinal out of bounds"))?
        };
        if record_offsets
            .last()
            .is_some_and(|previous| *previous >= offset)
            && index > 0
        {
            return Err(invalid("record offsets are not strictly increasing"));
        }
        record_offsets.push(offset);
    }
    if record_offsets.first() != Some(&0) || record_offsets.last() != Some(&(records_len as u64)) {
        return Err(invalid("record offsets do not span the record section"));
    }
    Ok((object_index, record_offsets))
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct PackFingerprint {
    path: PathBuf,
    len: u64,
    modified: Option<SystemTime>,
}

struct CachedPack {
    fingerprint: PackFingerprint,
    pack: OnceLock<std::result::Result<Npk1Pack, String>>,
}

impl CachedPack {
    fn open(&self) -> Result<&Npk1Pack> {
        match self.pack.get_or_init(|| {
            Npk1Pack::open_direct(&self.fingerprint.path).map_err(|error| error.to_string())
        }) {
            Ok(pack) => Ok(pack),
            Err(error) => Err(invalid(format!(
                "cannot open {}: {error}",
                self.fingerprint.path.display()
            ))),
        }
    }
}

pub(crate) struct Npk1Manager {
    packs_dir: PathBuf,
    packs: Vec<CachedPack>,
    fingerprints: Vec<PackFingerprint>,
}

impl Npk1Manager {
    pub(crate) fn new(packs_dir: PathBuf) -> Self {
        let fingerprints = discover(&packs_dir).unwrap_or_default();
        let packs = cached(&fingerprints);
        Self {
            packs_dir,
            packs,
            fingerprints,
        }
    }

    pub(crate) fn reload(&mut self) -> Result<()> {
        let fingerprints = discover(&self.packs_dir)?;
        self.packs = cached(&fingerprints);
        self.fingerprints = fingerprints;
        Ok(())
    }

    pub(crate) fn needs_reload(&self) -> Result<bool> {
        Ok(discover(&self.packs_dir)? != self.fingerprints)
    }

    pub(crate) fn file_paths(&self) -> Vec<&Path> {
        self.fingerprints
            .iter()
            .map(|fingerprint| fingerprint.path.as_path())
            .collect()
    }

    pub(crate) fn has_tree(&self, hash: &ContentHash) -> Result<bool> {
        for cached in self.packs.iter().rev() {
            if cached.open()?.contains(hash) {
                return Ok(true);
            }
        }
        Ok(false)
    }

    pub(crate) fn get_tree(&self, hash: &ContentHash) -> Result<Option<Tree>> {
        for cached in self.packs.iter().rev() {
            let pack = cached.open()?;
            if pack.contains(hash) {
                return pack.resolve(hash).map(Some);
            }
        }
        Ok(None)
    }

    pub(crate) fn get_entry(&self, hash: &ContentHash, name: &str) -> Result<Option<TreeEntry>> {
        for cached in self.packs.iter().rev() {
            let pack = cached.open()?;
            if pack.contains(hash) {
                return pack.lookup(hash, name);
            }
        }
        Ok(None)
    }

    pub(crate) fn list_ids(&self) -> Result<Vec<ContentHash>> {
        let mut ids = HashSet::new();
        for cached in &self.packs {
            ids.extend(cached.open()?.ids());
        }
        let mut ids = ids.into_iter().collect::<Vec<_>>();
        ids.sort();
        Ok(ids)
    }
}

fn cached(fingerprints: &[PackFingerprint]) -> Vec<CachedPack> {
    fingerprints
        .iter()
        .cloned()
        .map(|fingerprint| CachedPack {
            fingerprint,
            pack: OnceLock::new(),
        })
        .collect()
}

fn discover(packs_dir: &Path) -> Result<Vec<PackFingerprint>> {
    if !packs_dir.exists() {
        return Ok(Vec::new());
    }
    let mut packs = Vec::new();
    for entry in fs::read_dir(packs_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().is_none_or(|extension| extension != "npk") {
            continue;
        }
        let metadata = entry.metadata()?;
        if !metadata.is_file() {
            continue;
        }
        packs.push(PackFingerprint {
            path,
            len: metadata.len(),
            modified: metadata.modified().ok(),
        });
    }
    packs.sort_by(|left, right| {
        left.modified
            .cmp(&right.modified)
            .then_with(|| left.path.cmp(&right.path))
    });
    Ok(packs)
}