Skip to main content

storage_kit/store/
packfile.rs

1//! Packfile on-disk layout — format v3, per the 2026-09-23
2//! storage-addressing rulings (the design and security reviews,
3//! Branch A). Entry meta is **54 bytes**; the `context` reservation the
4//! spec this superseded (the format-reservations spec)
5//! carried is withdrawn by both rulings — `(hash, context)` addressing
6//! never lands, so there is no 16-byte slot to grow into. `key_epoch`
7//! (u32, equality-only, single legal value `0` today) and `flags` (single
8//! legal value `0x00`, no bit assigned) remain exactly as that spec
9//! reserved them.
10//!
11//! Two files per pack: `<pack_id>.pack` (data) and `<pack_id>.idx` (index).
12//! The index is git-pack style: derived and rebuildable from the `.pack`
13//! file alone, and is never treated as a source of truth — losing an `.idx`
14//! is a `verify`/rebuild-away, not data loss.
15//!
16//! `.pack` layout:
17//! ```text
18//! header:  magic "BCPK" (4B) | format_ver u32 LE (=3) | partition_id (16B)
19//! entry*:  hash (32B) | codec (1B) | flags (1B) | key_epoch u32 LE (4B)
20//!          | uncompressed_len u64 LE (8B) | stored_len u64 LE (8B)
21//!          | payload (stored_len bytes)
22//! trailer: entry_count u64 LE | pack_content_hash (32B)
23//! ```
24//! `pack_content_hash` is the BLAKE3 hash of every byte in the file *before*
25//! the trailer (header + all entries) — it is also the pack's own content
26//! address: sealed packs are named `<pack_content_hash_hex>.pack`.
27//!
28//! The trailer is only ever written when a pack is **sealed**; the
29//! currently-open active pack has no trailer and is rebuilt by sequential
30//! scan on reopen (crash-safe by construction — a scan simply stops at the
31//! last complete entry).
32//!
33//! **The `.idx` is a lossless projection of the pack.** Every field in an
34//! idx record also exists in the pack entry it describes; the idx adds only
35//! the byte offset, the one fact the pack cannot carry about itself:
36//! `IDX_RECORD_LEN == ENTRY_META_LEN + 8`, asserted at compile time below.
37//! This also **restores `flags` to the index**, which v2 dropped — the
38//! projection invariant is worth more than the byte.
39//!
40//! **Fail-closed enforcement, on both sides.** The writer here never emits
41//! anything but the reserved values (`flags == 0x00`, `key_epoch == 0`) —
42//! [`PackWriter::append`] takes no parameters to supply them, by
43//! construction. [`EntryMeta::validate_reserved`] is the reader-side half:
44//! it is called on every entry [`ImmutableStore::get`](crate::store::ImmutableStore::get)
45//! hands a caller, and rejects a non-reserved value with
46//! [`StorageError::CorruptPack`], naming the field. It is **not** called on
47//! the raw byte-copy path ([`PackWriter::append_raw`], [`get_raw_at`],
48//! `rebuild_index_entries`, `read_index`) — those exist so a meta-preserving
49//! copy (GC's repack) can move an entry forward without decoding or
50//! trusting its meaning, which is what keeps GC key-blind once encryption
51//! lands. A v3 reader must never silently *ignore* a field it cannot
52//! honour when it is actually interpreting content; it does not need to
53//! interpret meta at all to relocate the bytes.
54//!
55//! `codec` gains a third discriminant, `Sealed = 2`, reserved and rejected
56//! at v3 (the security review's request, adopted in
57//! the format-reservations spec §R.2) — defined now so
58//! the value is not claimed for anything else, and becomes legal at the
59//! seal-freeze version. This crate implements **no encryption**; that is a
60//! separate, not-yet-landed workstream.
61
62use crate::addressing::{Hash, PartitionId, HASH_LEN, PARTITION_ID_LEN};
63use crate::error::{Result, StorageError};
64use std::collections::HashMap;
65use std::fs::{self, File, OpenOptions};
66use std::io::{Read, Seek, SeekFrom, Write};
67use std::path::{Path, PathBuf};
68
69pub const PACK_MAGIC: [u8; 4] = *b"BCPK";
70pub const IDX_MAGIC: [u8; 4] = *b"BCIX";
71pub const FORMAT_VERSION: u32 = 3;
72pub const HEADER_LEN: usize = 4 + 4 + PARTITION_ID_LEN;
73pub const TRAILER_LEN: usize = 8 + HASH_LEN;
74/// `hash(32) | codec(1) | flags(1) | key_epoch(4) | uncompressed_len(8) |
75/// stored_len(8)` = 54. Pinned by `ENTRY_META_LEN_IS_54` below — growing
76/// this is a compile error with a ruling attached, not a diff someone skims.
77pub const ENTRY_META_LEN: usize = HASH_LEN + 1 + 1 + 4 + 8 + 8;
78
79const _ENTRY_META_LEN_IS_54: () = assert!(
80    ENTRY_META_LEN == 54,
81    "ENTRY_META_LEN must be 54 per the 2026-09-23 storage-addressing rulings (Branch A) \
82     — see storage-addressing-hash-context-ruling-2026-09-23.md"
83);
84
85/// Storage codec applied to an entry's payload.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Codec {
88    /// Payload is stored uncompressed (used when Zstd does not help, e.g.
89    /// already-compressed or very small inputs).
90    Raw = 0,
91    /// Payload is Zstd-compressed.
92    Zstd = 1,
93    /// Payload is AEAD-sealed. **Reserved and rejected at format v3** — the
94    /// discriminant is defined now (the security review's request) so it is
95    /// not claimed for anything else; it becomes legal at the seal-freeze
96    /// version. This crate implements no encryption today and no writer
97    /// here ever emits this value.
98    Sealed = 2,
99}
100
101impl Codec {
102    fn from_u8(b: u8) -> Result<Self> {
103        match b {
104            0 => Ok(Codec::Raw),
105            1 => Ok(Codec::Zstd),
106            2 => Ok(Codec::Sealed),
107            other => Err(StorageError::CorruptPack(format!(
108                "unknown codec byte {other}"
109            ))),
110        }
111    }
112}
113
114/// Metadata for one stored entry (payload excluded).
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct EntryMeta {
117    pub hash: Hash,
118    pub codec: Codec,
119    /// Reserved. The only legal value at format v3 is `0x00` — no bit is
120    /// assigned, now or in this change. See the module docs: `flags` is
121    /// deliberately left wholly unassigned rather than given a `SEALED`
122    /// bit, because `Codec::Sealed` is the sole indicator that a payload is
123    /// sealed and a second field restating the same fact is a duplicated
124    /// state that will eventually disagree with the original.
125    pub flags: u8,
126    /// A u32 opaque key *selector*. Today its only interpretation is a
127    /// monotonic per-partition epoch counter; the sole legal value is `0`,
128    /// since this crate has no key-wrapping concept yet. **Equality only**
129    /// — code that orders it (`key_epoch < current_epoch`) has silently
130    /// spent the future key-table-index reinterpretation and is a defect.
131    pub key_epoch: u32,
132    pub uncompressed_len: u64,
133    pub stored_len: u64,
134}
135
136impl EntryMeta {
137    /// Fail-closed check that every field reserved at format v3 carries its
138    /// sole legal value. Called on every entry [`ImmutableStore::get`]
139    /// hands to a caller — the boundary that decodes and trusts the
140    /// payload's meaning. **Deliberately not called** on the raw byte-copy
141    /// path (`append_raw`, [`get_raw_at`], `rebuild_index_entries`,
142    /// `read_index`): a meta-preserving copy relocates bytes without
143    /// interpreting what they mean, which is what keeps GC key-blind.
144    ///
145    /// [`ImmutableStore::get`]: crate::store::ImmutableStore::get
146    pub fn validate_reserved(&self) -> Result<()> {
147        if self.flags != 0x00 {
148            return Err(StorageError::CorruptPack(format!(
149                "entry {}: flags is reserved and must be 0x00, got {:#04x}",
150                self.hash, self.flags
151            )));
152        }
153        if self.key_epoch != 0 {
154            return Err(StorageError::CorruptPack(format!(
155                "entry {}: key_epoch is reserved and must be 0, got {}",
156                self.hash, self.key_epoch
157            )));
158        }
159        if self.codec == Codec::Sealed {
160            return Err(StorageError::CorruptPack(format!(
161                "entry {}: codec Sealed is reserved and rejected at format v3",
162                self.hash
163            )));
164        }
165        Ok(())
166    }
167}
168
169/// Location of a sealed entry: which pack, and byte offset of its entry
170/// header within that pack.
171#[derive(Debug, Clone, Copy)]
172pub struct SealedLocation {
173    pub pack_id: Hash,
174    pub offset: u64,
175}
176
177const ZSTD_LEVEL: i32 = 3;
178
179/// Compress `data`, falling back to raw storage if compression doesn't
180/// actually shrink the payload (small or already-dense inputs).
181pub fn encode(data: &[u8]) -> Result<(Codec, Vec<u8>)> {
182    if data.is_empty() {
183        return Ok((Codec::Raw, Vec::new()));
184    }
185    let compressed = zstd::stream::encode_all(data, ZSTD_LEVEL)
186        .map_err(|e| StorageError::Compression(e.to_string()))?;
187    if compressed.len() < data.len() {
188        Ok((Codec::Zstd, compressed))
189    } else {
190        Ok((Codec::Raw, data.to_vec()))
191    }
192}
193
194pub fn decode(codec: Codec, stored: &[u8]) -> Result<Vec<u8>> {
195    match codec {
196        Codec::Raw => Ok(stored.to_vec()),
197        Codec::Zstd => {
198            zstd::stream::decode_all(stored).map_err(|e| StorageError::Compression(e.to_string()))
199        }
200        // Unreachable in practice: every caller runs `EntryMeta::validate_reserved`
201        // first, which rejects `Sealed` at v3. Kept as a hard error rather than
202        // `unreachable!()` so a future caller that skips validation fails safe
203        // instead of panicking.
204        Codec::Sealed => Err(StorageError::CorruptPack(
205            "codec Sealed is reserved and rejected at format v3; decode() must not be called \
206             without EntryMeta::validate_reserved() first"
207                .into(),
208        )),
209    }
210}
211
212fn write_header<W: Write>(w: &mut W, partition_id: &PartitionId) -> Result<()> {
213    w.write_all(&PACK_MAGIC)?;
214    w.write_all(&FORMAT_VERSION.to_le_bytes())?;
215    w.write_all(partition_id.as_bytes())?;
216    Ok(())
217}
218
219fn read_header<R: Read>(r: &mut R) -> Result<PartitionId> {
220    let mut magic = [0u8; 4];
221    r.read_exact(&mut magic)?;
222    if magic != PACK_MAGIC {
223        return Err(StorageError::CorruptPack("bad magic".into()));
224    }
225    let mut ver = [0u8; 4];
226    r.read_exact(&mut ver)?;
227    let ver = u32::from_le_bytes(ver);
228    if ver != FORMAT_VERSION {
229        return Err(StorageError::CorruptPack(format!(
230            "unsupported pack format_ver {ver} (expected {FORMAT_VERSION})"
231        )));
232    }
233    let mut pid = [0u8; PARTITION_ID_LEN];
234    r.read_exact(&mut pid)?;
235    Ok(PartitionId::from_bytes(pid))
236}
237
238/// An open, append-only pack. Entries are appended one at a time; the
239/// trailer is written only at `seal()` time.
240pub struct PackWriter {
241    path: PathBuf,
242    partition_id: PartitionId,
243    file: File,
244    /// Byte length of the file so far (header + entries written).
245    pub len: u64,
246    pub entry_count: u64,
247    /// In-memory offset index for entries written this process — avoids a
248    /// re-scan to serve a `get()` against data not yet sealed.
249    pub offsets: HashMap<Hash, u64>,
250}
251
252impl PackWriter {
253    /// Open (creating if absent) the active pack at `path` for `partition_id`,
254    /// rebuilding in-memory state by scanning any bytes already there
255    /// (resuming after a crash or a prior process exit).
256    pub fn open_active(path: &Path, partition_id: PartitionId) -> Result<Self> {
257        if let Some(parent) = path.parent() {
258            fs::create_dir_all(parent)?;
259        }
260        let is_new = !path.exists();
261        let mut file = OpenOptions::new()
262            .create(true)
263            .read(true)
264            .append(true)
265            .open(path)?;
266
267        if is_new {
268            write_header(&mut file, &partition_id)?;
269            file.flush()?;
270            return Ok(PackWriter {
271                path: path.to_path_buf(),
272                partition_id,
273                file,
274                len: HEADER_LEN as u64,
275                entry_count: 0,
276                offsets: HashMap::new(),
277            });
278        }
279
280        // Resume: sequential scan for whatever complete entries exist.
281        let mut reader = File::open(path)?;
282        let found_partition = read_header(&mut reader)?;
283        if found_partition != partition_id {
284            return Err(StorageError::PartitionBoundary(format!(
285                "active pack at {} belongs to partition {}, not {}",
286                path.display(),
287                found_partition.to_hex(),
288                partition_id.to_hex()
289            )));
290        }
291        let mut offsets = HashMap::new();
292        let mut pos = HEADER_LEN as u64;
293        let mut count = 0u64;
294        loop {
295            let entry_start = pos;
296            match read_entry_meta_at(&mut reader, entry_start) {
297                Ok(Some(meta)) => {
298                    offsets.insert(meta.hash, entry_start);
299                    pos = entry_start + ENTRY_META_LEN as u64 + meta.stored_len;
300                    count += 1;
301                }
302                Ok(None) => break, // clean EOF at an entry boundary
303                Err(_) => break,   // truncated/partial trailing entry — stop before it
304            }
305        }
306        Ok(PackWriter {
307            path: path.to_path_buf(),
308            partition_id,
309            file,
310            len: pos,
311            entry_count: count,
312            offsets,
313        })
314    }
315
316    /// Append one entry (dedup is the caller's responsibility — this always
317    /// writes). Returns the byte offset the entry starts at. Always emits
318    /// the reserved values for `flags`/`key_epoch` — there is no parameter
319    /// to supply anything else; that is the writer-side half of the
320    /// fail-closed rule (module docs).
321    pub fn append(
322        &mut self,
323        hash: Hash,
324        codec: Codec,
325        uncompressed_len: u64,
326        payload: &[u8],
327    ) -> Result<u64> {
328        let meta = EntryMeta {
329            hash,
330            codec,
331            flags: 0x00,
332            key_epoch: 0,
333            uncompressed_len,
334            stored_len: payload.len() as u64,
335        };
336        self.append_raw(&meta, payload)
337    }
338
339    /// Append one entry with an arbitrary, caller-supplied [`EntryMeta`] —
340    /// the byte-exact primitive a meta-preserving copy (GC's repack) needs
341    /// to relocate an entry without re-deriving `flags`/`key_epoch` from
342    /// scratch. **Not** a route for ordinary callers to set reserved
343    /// fields: `PartitionStore::put`
344    /// only ever reaches this through [`PackWriter::append`], which hard-codes
345    /// the reserved values. `packfile` is implementation, explicitly
346    /// outside the interface lock (see `lib.rs`); this is the escape hatch
347    /// that exists for exactly one job.
348    pub fn append_raw(&mut self, meta: &EntryMeta, payload: &[u8]) -> Result<u64> {
349        let offset = self.len;
350        let mut buf = Vec::with_capacity(ENTRY_META_LEN + payload.len());
351        buf.extend_from_slice(meta.hash.as_bytes());
352        buf.push(meta.codec as u8);
353        buf.push(meta.flags);
354        buf.extend_from_slice(&meta.key_epoch.to_le_bytes());
355        buf.extend_from_slice(&meta.uncompressed_len.to_le_bytes());
356        buf.extend_from_slice(&(payload.len() as u64).to_le_bytes());
357        buf.extend_from_slice(payload);
358        self.file.write_all(&buf)?;
359        self.file.flush()?;
360        self.len += buf.len() as u64;
361        self.entry_count += 1;
362        self.offsets.insert(meta.hash, offset);
363        Ok(offset)
364    }
365
366    pub fn read_payload_at(&self, offset: u64) -> Result<(EntryMeta, Vec<u8>)> {
367        let mut f = File::open(&self.path)?;
368        read_entry_full_at(&mut f, offset)
369    }
370
371    /// Seal this pack: write the trailer, rename to its content-addressed
372    /// final name (`<pack_content_hash>.pack`), and return the new id +
373    /// path. The writer is consumed — callers open a fresh `PackWriter` for
374    /// the next active pack.
375    pub fn seal(mut self, packs_dir: &Path) -> Result<(Hash, PathBuf)> {
376        self.file.flush()?;
377        // Hash everything written so far (header + entries), excluding the
378        // trailer we're about to append.
379        let mut hasher = blake3::Hasher::new();
380        let mut reader = File::open(&self.path)?;
381        std::io::copy(&mut reader, &mut hasher)?;
382        let pack_content_hash = Hash::from_bytes(*hasher.finalize().as_bytes());
383
384        self.file.write_all(&self.entry_count.to_le_bytes())?;
385        self.file.write_all(pack_content_hash.as_bytes())?;
386        self.file.flush()?;
387
388        let pack_id_hex = pack_content_hash.to_hex();
389        let shard = PartitionId::shard_prefix(&pack_id_hex).to_string();
390        let dest_dir = packs_dir.join(&shard);
391        fs::create_dir_all(&dest_dir)?;
392        let dest_path = dest_dir.join(format!("{pack_id_hex}.pack"));
393        fs::rename(&self.path, &dest_path)?;
394
395        // Build + persist the derived index alongside the sealed pack.
396        let entries = rebuild_index_entries(&dest_path)?;
397        write_index(
398            &dest_path.with_extension("idx"),
399            &self.partition_id,
400            &entries,
401        )?;
402
403        Ok((pack_content_hash, dest_path))
404    }
405
406    pub fn partition_id(&self) -> PartitionId {
407        self.partition_id
408    }
409}
410
411fn read_entry_meta_at<R: Read + Seek>(r: &mut R, offset: u64) -> Result<Option<EntryMeta>> {
412    r.seek(SeekFrom::Start(offset))?;
413    let mut meta_buf = [0u8; ENTRY_META_LEN];
414    match r.read_exact(&mut meta_buf) {
415        Ok(()) => {}
416        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
417        Err(e) => return Err(e.into()),
418    }
419    let hash = Hash::from_bytes(meta_buf[0..32].try_into().unwrap());
420    let codec = Codec::from_u8(meta_buf[32])?;
421    let flags = meta_buf[33];
422    let key_epoch = u32::from_le_bytes(meta_buf[34..38].try_into().unwrap());
423    let uncompressed_len = u64::from_le_bytes(meta_buf[38..46].try_into().unwrap());
424    let stored_len = u64::from_le_bytes(meta_buf[46..54].try_into().unwrap());
425    // Confirm the payload is actually present (not a torn write).
426    let mut probe = vec![0u8; stored_len as usize];
427    match r.read_exact(&mut probe) {
428        Ok(()) => {}
429        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
430        Err(e) => return Err(e.into()),
431    }
432    Ok(Some(EntryMeta {
433        hash,
434        codec,
435        flags,
436        key_epoch,
437        uncompressed_len,
438        stored_len,
439    }))
440}
441
442fn read_entry_full_at<R: Read + Seek>(r: &mut R, offset: u64) -> Result<(EntryMeta, Vec<u8>)> {
443    r.seek(SeekFrom::Start(offset))?;
444    let mut meta_buf = [0u8; ENTRY_META_LEN];
445    r.read_exact(&mut meta_buf)?;
446    let hash = Hash::from_bytes(meta_buf[0..32].try_into().unwrap());
447    let codec = Codec::from_u8(meta_buf[32])?;
448    let flags = meta_buf[33];
449    let key_epoch = u32::from_le_bytes(meta_buf[34..38].try_into().unwrap());
450    let uncompressed_len = u64::from_le_bytes(meta_buf[38..46].try_into().unwrap());
451    let stored_len = u64::from_le_bytes(meta_buf[46..54].try_into().unwrap());
452    let mut payload = vec![0u8; stored_len as usize];
453    r.read_exact(&mut payload)?;
454    Ok((
455        EntryMeta {
456            hash,
457            codec,
458            flags,
459            key_epoch,
460            uncompressed_len,
461            stored_len,
462        },
463        payload,
464    ))
465}
466
467/// Fetch one entry's `(meta, payload)` **without** decoding, hash-verifying,
468/// or validating reserved fields — the raw form a meta-preserving copy (GC's
469/// repack) needs so it can relocate an entry without interpreting what it
470/// means. Contrast [`get_at`], which is the validated, decoded, verified
471/// form real content reads go through.
472pub fn get_raw_at(pack_path: &Path, offset: u64) -> Result<(EntryMeta, Vec<u8>)> {
473    let mut f = File::open(pack_path)?;
474    read_entry_full_at(&mut f, offset)
475}
476
477/// Rebuild the full `(offset, meta)` list for a **sealed** pack by
478/// sequential scan, ignoring/validating against the trailer if present.
479pub fn rebuild_index_entries(pack_path: &Path) -> Result<Vec<(u64, EntryMeta)>> {
480    let mut f = File::open(pack_path)?;
481    let _partition_id = read_header(&mut f)?;
482    let file_len = f.metadata()?.len();
483    let scan_end = file_len.saturating_sub(TRAILER_LEN as u64);
484
485    let mut out = Vec::new();
486    let mut pos = HEADER_LEN as u64;
487    while pos < scan_end {
488        let entry_start = pos;
489        let meta = read_entry_meta_at(&mut f, entry_start)?.ok_or_else(|| {
490            StorageError::CorruptPack(format!(
491                "truncated entry at offset {entry_start} in {}",
492                pack_path.display()
493            ))
494        })?;
495        pos = entry_start + ENTRY_META_LEN as u64 + meta.stored_len;
496        out.push((entry_start, meta));
497    }
498    if pos != scan_end {
499        return Err(StorageError::CorruptPack(format!(
500            "entry scan did not land on trailer boundary in {}",
501            pack_path.display()
502        )));
503    }
504    Ok(out)
505}
506
507/// Read a sealed pack's trailer and verify `pack_content_hash` against the
508/// actual bytes preceding it. Returns `(entry_count, pack_content_hash)`.
509pub fn verify_trailer(pack_path: &Path) -> Result<(u64, Hash)> {
510    let mut f = File::open(pack_path)?;
511    let file_len = f.metadata()?.len();
512    if file_len < (HEADER_LEN + TRAILER_LEN) as u64 {
513        return Err(StorageError::CorruptPack(
514            "pack too short for trailer".into(),
515        ));
516    }
517    f.seek(SeekFrom::Start(file_len - TRAILER_LEN as u64))?;
518    let mut trailer = [0u8; TRAILER_LEN];
519    f.read_exact(&mut trailer)?;
520    let entry_count = u64::from_le_bytes(trailer[0..8].try_into().unwrap());
521    let recorded_hash = Hash::from_bytes(trailer[8..40].try_into().unwrap());
522
523    let mut hasher = blake3::Hasher::new();
524    let body = File::open(pack_path)?;
525    let mut limited = Read::take(body, file_len - TRAILER_LEN as u64);
526    std::io::copy(&mut limited, &mut hasher)?;
527    let actual_hash = Hash::from_bytes(*hasher.finalize().as_bytes());
528
529    if actual_hash != recorded_hash {
530        return Err(StorageError::CorruptPack(format!(
531            "pack_content_hash mismatch in {}: trailer says {}, computed {}",
532            pack_path.display(),
533            recorded_hash,
534            actual_hash
535        )));
536    }
537    Ok((entry_count, actual_hash))
538}
539
540/// Fetch and decode one entry's payload from a sealed pack at `offset`,
541/// verifying the stored bytes hash to the entry's own recorded hash. This
542/// is the validated read path: [`EntryMeta::validate_reserved`] runs before
543/// decode, so a non-reserved `flags`/`key_epoch`/`Sealed` codec is rejected
544/// rather than silently honoured or ignored.
545pub fn get_at(pack_path: &Path, offset: u64) -> Result<Vec<u8>> {
546    let mut f = File::open(pack_path)?;
547    let (meta, payload) = read_entry_full_at(&mut f, offset)?;
548    meta.validate_reserved()?;
549    let decoded = decode(meta.codec, &payload)?;
550    let actual = Hash::of(&decoded);
551    if actual != meta.hash {
552        return Err(StorageError::HashMismatch {
553            expected: meta.hash.to_hex(),
554            actual: actual.to_hex(),
555        });
556    }
557    if decoded.len() as u64 != meta.uncompressed_len {
558        return Err(StorageError::CorruptPack(format!(
559            "uncompressed_len mismatch for {}",
560            meta.hash
561        )));
562    }
563    Ok(decoded)
564}
565
566// ---------------------------------------------------------------------
567// .idx — git-pack style derived index. Never authoritative; always
568// rebuildable from the corresponding `.pack` via `rebuild_index_entries`.
569// ---------------------------------------------------------------------
570
571/// `hash(32) | offset(8) | codec(1) | flags(1) | key_epoch(4) |
572/// uncompressed_len(8) | stored_len(8)` = 62 — the entry meta with `offset`
573/// spliced in after `hash`, mirroring [`ENTRY_META_LEN`] exactly so a
574/// single shared encoder/decoder serves both and the projection invariant
575/// is obvious by inspection.
576const IDX_RECORD_LEN: usize = HASH_LEN + 8 + 1 + 1 + 4 + 8 + 8;
577
578const _IDX_RECORD_LEN_IS_ENTRY_META_LEN_PLUS_8: () = assert!(
579    IDX_RECORD_LEN == ENTRY_META_LEN + 8,
580    "IDX_RECORD_LEN must equal ENTRY_META_LEN + 8 — the idx adds only the byte offset, the one \
581     fact the pack cannot carry about itself"
582);
583
584pub fn write_index(
585    idx_path: &Path,
586    partition_id: &PartitionId,
587    entries: &[(u64, EntryMeta)],
588) -> Result<()> {
589    let mut sorted: Vec<&(u64, EntryMeta)> = entries.iter().collect();
590    sorted.sort_by_key(|(_, m)| *m.hash.as_bytes());
591
592    let mut buf = Vec::with_capacity(4 + 4 + PARTITION_ID_LEN + 8 + sorted.len() * IDX_RECORD_LEN);
593    buf.extend_from_slice(&IDX_MAGIC);
594    buf.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
595    buf.extend_from_slice(partition_id.as_bytes());
596    buf.extend_from_slice(&(sorted.len() as u64).to_le_bytes());
597    for (offset, meta) in sorted {
598        buf.extend_from_slice(meta.hash.as_bytes());
599        buf.extend_from_slice(&offset.to_le_bytes());
600        buf.push(meta.codec as u8);
601        buf.push(meta.flags);
602        buf.extend_from_slice(&meta.key_epoch.to_le_bytes());
603        buf.extend_from_slice(&meta.uncompressed_len.to_le_bytes());
604        buf.extend_from_slice(&meta.stored_len.to_le_bytes());
605    }
606    fs::write(idx_path, buf)?;
607    Ok(())
608}
609
610/// Read a `.idx` file into a `hash -> (offset, meta)` map — the full
611/// record, not merely the offset, so a caller (GC's meta-preserving copy)
612/// can read an entry's meta straight from the loaded index without
613/// touching the pack at all. Deliberately **not** validated here (see the
614/// module docs): a corrupt/tampered idx is always recoverable via
615/// `rebuild_index_entries`, and interpreting meta is `get()`'s job, not
616/// the index loader's. Callers should not treat a missing/corrupt index as
617/// an error condition for the store as a whole.
618pub fn read_index(idx_path: &Path) -> Result<HashMap<Hash, (u64, EntryMeta)>> {
619    let bytes = fs::read(idx_path)?;
620    if bytes.len() < 4 + 4 + PARTITION_ID_LEN + 8 {
621        return Err(StorageError::CorruptPack("idx too short".into()));
622    }
623    if bytes[0..4] != IDX_MAGIC {
624        return Err(StorageError::CorruptPack("bad idx magic".into()));
625    }
626    let count_off = 4 + 4 + PARTITION_ID_LEN;
627    let count = u64::from_le_bytes(bytes[count_off..count_off + 8].try_into().unwrap()) as usize;
628    let mut out = HashMap::with_capacity(count);
629    let mut pos = count_off + 8;
630    for _ in 0..count {
631        if pos + IDX_RECORD_LEN > bytes.len() {
632            return Err(StorageError::CorruptPack("idx truncated".into()));
633        }
634        let hash = Hash::from_bytes(bytes[pos..pos + 32].try_into().unwrap());
635        let offset = u64::from_le_bytes(bytes[pos + 32..pos + 40].try_into().unwrap());
636        let codec = Codec::from_u8(bytes[pos + 40])?;
637        let flags = bytes[pos + 41];
638        let key_epoch = u32::from_le_bytes(bytes[pos + 42..pos + 46].try_into().unwrap());
639        let uncompressed_len = u64::from_le_bytes(bytes[pos + 46..pos + 54].try_into().unwrap());
640        let stored_len = u64::from_le_bytes(bytes[pos + 54..pos + 62].try_into().unwrap());
641        out.insert(
642            hash,
643            (
644                offset,
645                EntryMeta {
646                    hash,
647                    codec,
648                    flags,
649                    key_epoch,
650                    uncompressed_len,
651                    stored_len,
652                },
653            ),
654        );
655        pos += IDX_RECORD_LEN;
656    }
657    Ok(out)
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663    use tempfile::tempdir;
664
665    #[test]
666    fn append_seal_and_read_back() {
667        let dir = tempdir().unwrap();
668        let packs_dir = dir.path().join("packs");
669        let partition_id = PartitionId::derive("test-partition");
670
671        let mut writer =
672            PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
673        let data = b"hello, packfile";
674        let hash = Hash::of(data);
675        let (codec, payload) = encode(data).unwrap();
676        let offset = writer
677            .append(hash, codec, data.len() as u64, &payload)
678            .unwrap();
679
680        let (pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
681        assert!(pack_path.exists());
682
683        let (entry_count, content_hash) = verify_trailer(&pack_path).unwrap();
684        assert_eq!(entry_count, 1);
685        assert_eq!(content_hash, pack_id);
686
687        let round_tripped = get_at(&pack_path, offset).unwrap();
688        assert_eq!(round_tripped, data);
689    }
690
691    #[test]
692    fn active_pack_resumes_after_reopen() {
693        let dir = tempdir().unwrap();
694        let active_path = dir.path().join("active/active.pack");
695        let partition_id = PartitionId::derive("resume-partition");
696
697        {
698            let mut writer = PackWriter::open_active(&active_path, partition_id).unwrap();
699            let (codec, payload) = encode(b"first").unwrap();
700            writer
701                .append(Hash::of(b"first"), codec, 5, &payload)
702                .unwrap();
703        }
704        let writer = PackWriter::open_active(&active_path, partition_id).unwrap();
705        assert_eq!(writer.entry_count, 1);
706        assert!(writer.offsets.contains_key(&Hash::of(b"first")));
707    }
708
709    #[test]
710    fn index_roundtrips() {
711        let dir = tempdir().unwrap();
712        let packs_dir = dir.path().join("packs");
713        let partition_id = PartitionId::derive("idx-partition");
714        let mut writer =
715            PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
716        let (codec, payload) = encode(b"index me").unwrap();
717        writer
718            .append(Hash::of(b"index me"), codec, 8, &payload)
719            .unwrap();
720        let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
721
722        let idx_path = pack_path.with_extension("idx");
723        let idx = read_index(&idx_path).unwrap();
724        assert_eq!(idx.len(), 1);
725        assert!(idx.contains_key(&Hash::of(b"index me")));
726
727        // Index is derived — rebuilding from the pack alone must agree.
728        let rebuilt = rebuild_index_entries(&pack_path).unwrap();
729        assert_eq!(rebuilt.len(), 1);
730        assert_eq!(rebuilt[0].1.hash, Hash::of(b"index me"));
731    }
732
733    #[test]
734    fn entry_meta_len_is_54_and_idx_record_len_is_62() {
735        assert_eq!(ENTRY_META_LEN, 54);
736        assert_eq!(IDX_RECORD_LEN, 62);
737    }
738
739    #[test]
740    fn append_always_emits_reserved_flags_and_key_epoch() {
741        let dir = tempdir().unwrap();
742        let partition_id = PartitionId::derive("reserved-values-partition");
743        let mut writer =
744            PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
745        let (codec, payload) = encode(b"ordinary entry").unwrap();
746        let offset = writer
747            .append(Hash::of(b"ordinary entry"), codec, 14, &payload)
748            .unwrap();
749        let (meta, _) = writer.read_payload_at(offset).unwrap();
750        assert_eq!(meta.flags, 0x00);
751        assert_eq!(meta.key_epoch, 0);
752        meta.validate_reserved().unwrap();
753    }
754
755    #[test]
756    fn get_at_rejects_non_reserved_flags() {
757        let dir = tempdir().unwrap();
758        let packs_dir = dir.path().join("packs");
759        let partition_id = PartitionId::derive("bad-flags-partition");
760        let mut writer =
761            PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
762        let data = b"tampered meta";
763        let (codec, payload) = encode(data).unwrap();
764        let meta = EntryMeta {
765            hash: Hash::of(data),
766            codec,
767            flags: 0x01, // non-reserved
768            key_epoch: 0,
769            uncompressed_len: data.len() as u64,
770            stored_len: payload.len() as u64,
771        };
772        let offset = writer.append_raw(&meta, &payload).unwrap();
773        let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
774
775        let err = get_at(&pack_path, offset).expect_err("non-reserved flags must be rejected");
776        assert!(matches!(err, StorageError::CorruptPack(_)));
777
778        // The raw path is deliberately meta-blind and must still succeed —
779        // this is the primitive GC's meta-preserving copy depends on.
780        let (raw_meta, raw_payload) = get_raw_at(&pack_path, offset).unwrap();
781        assert_eq!(raw_meta.flags, 0x01);
782        assert_eq!(raw_payload, payload);
783    }
784
785    #[test]
786    fn get_at_rejects_non_reserved_key_epoch() {
787        let dir = tempdir().unwrap();
788        let packs_dir = dir.path().join("packs");
789        let partition_id = PartitionId::derive("bad-key-epoch-partition");
790        let mut writer =
791            PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
792        let data = b"tampered epoch";
793        let (codec, payload) = encode(data).unwrap();
794        let meta = EntryMeta {
795            hash: Hash::of(data),
796            codec,
797            flags: 0x00,
798            key_epoch: 7, // non-reserved
799            uncompressed_len: data.len() as u64,
800            stored_len: payload.len() as u64,
801        };
802        let offset = writer.append_raw(&meta, &payload).unwrap();
803        let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
804
805        let err = get_at(&pack_path, offset).expect_err("non-reserved key_epoch must be rejected");
806        assert!(matches!(err, StorageError::CorruptPack(_)));
807    }
808
809    #[test]
810    fn get_at_rejects_sealed_codec_at_v3() {
811        let dir = tempdir().unwrap();
812        let packs_dir = dir.path().join("packs");
813        let partition_id = PartitionId::derive("sealed-codec-partition");
814        let mut writer =
815            PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
816        let data = b"sealed at v3, rejected";
817        let meta = EntryMeta {
818            hash: Hash::of(data),
819            codec: Codec::Sealed,
820            flags: 0x00,
821            key_epoch: 0,
822            uncompressed_len: data.len() as u64,
823            stored_len: data.len() as u64,
824        };
825        let offset = writer.append_raw(&meta, data).unwrap();
826        let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
827
828        let err = get_at(&pack_path, offset).expect_err("Codec::Sealed must be rejected at v3");
829        assert!(matches!(err, StorageError::CorruptPack(_)));
830    }
831
832    #[test]
833    fn append_raw_preserves_meta_through_a_copy() {
834        // The primitive GC's meta-preserving repack is built on: copy a
835        // (meta, payload) pair, byte-for-byte, into a fresh pack, and read
836        // the same meta back — no re-derivation, no silent re-stamping.
837        let source_dir = tempdir().unwrap();
838        let dest_dir = tempdir().unwrap();
839        let partition_id = PartitionId::derive("append-raw-copy-partition");
840
841        let mut source =
842            PackWriter::open_active(&source_dir.path().join("active/active.pack"), partition_id)
843                .unwrap();
844        let data = b"copy me forward with meta intact";
845        let (codec, payload) = encode(data).unwrap();
846        let source_meta = EntryMeta {
847            hash: Hash::of(data),
848            codec,
849            flags: 0x00,
850            key_epoch: 0,
851            uncompressed_len: data.len() as u64,
852            stored_len: payload.len() as u64,
853        };
854        let source_offset = source.append_raw(&source_meta, &payload).unwrap();
855        let (fetched_meta, fetched_payload) = source.read_payload_at(source_offset).unwrap();
856        assert_eq!(fetched_meta, source_meta);
857
858        let mut dest =
859            PackWriter::open_active(&dest_dir.path().join("active/active.pack"), partition_id)
860                .unwrap();
861        let dest_offset = dest.append_raw(&fetched_meta, &fetched_payload).unwrap();
862        let (copied_meta, copied_payload) = dest.read_payload_at(dest_offset).unwrap();
863
864        assert_eq!(
865            copied_meta, source_meta,
866            "meta must survive the copy exactly"
867        );
868        assert_eq!(copied_payload, payload);
869    }
870}