Skip to main content

apr_format/v2/
reader_impl.rs

1//! v2 reader impls + shard manifest (issue #2231).
2//!
3//! Formerly `include!`d into `v2/mod.rs`; now a real module. The `AprV2Reader`
4//! and `AprV2ReaderRef` struct declarations live here next to their `impl`s
5//! (private fields).
6//!
7//! # Sovereignty seam (issue #2231)
8//!
9//! The dequantizing `get_tensor_as_f32` accessor (which needed the GGUF Q4_K /
10//! Q6_K dequant kernels + the local f16-scaled `dequantize_q4`) is **severed**
11//! from the leaf: it pulls quantization/physics that belongs to the framework.
12//! The leaf exposes only the raw container bytes ([`AprV2Reader::get_tensor_data`])
13//! and the trivial F32-only typed view ([`AprV2Reader::get_f32_tensor`]).
14//! `aprender-core` re-attaches the dequantizing accessor as the `AprV2DequantExt`
15//! extension trait.
16
17use super::{
18    is_aligned_64, AprV2Header, AprV2Metadata, TensorDType, TensorIndexEntry, V2FormatError,
19    HEADER_SIZE_V2,
20};
21use serde::{Deserialize, Serialize};
22use std::collections::HashMap;
23use std::io::Read;
24
25/// APR v2 format reader (owns data - copies input)
26#[derive(Debug)]
27pub struct AprV2Reader {
28    header: AprV2Header,
29    metadata: AprV2Metadata,
30    tensor_index: Vec<TensorIndexEntry>,
31    data: Vec<u8>,
32}
33
34/// APR v2 format reader with zero-copy (borrows data - for mmap)
35///
36/// This reader borrows the data slice instead of copying it, enabling
37/// true zero-copy access when used with memory-mapped files.
38///
39/// # Example
40///
41/// ```ignore
42/// use apr_format::v2::AprV2ReaderRef;
43///
44/// let bytes: &[u8] = /* mmap'd slice */;
45/// let reader = AprV2ReaderRef::from_bytes(bytes)?;
46/// let weights = reader.get_f32_tensor("embed_tokens.weight")?;
47/// ```
48#[derive(Debug)]
49pub struct AprV2ReaderRef<'a> {
50    header: AprV2Header,
51    metadata: AprV2Metadata,
52    tensor_index: Vec<TensorIndexEntry>,
53    data: &'a [u8],
54}
55
56/// Parse and bounds-check the JSON metadata section (FALSIFY-PARSE-001).
57///
58/// All offsets/sizes here come straight from the (attacker-controllable) file
59/// header — the CRC32 checksum is computed over the header itself, so a
60/// corrupted file can carry a matching checksum. Therefore every offset+size is
61/// validated with checked arithmetic and `slice::get` (never `[start..end]`
62/// indexing, which panics on out-of-range / `start > end`).
63fn parse_metadata_section(
64    data: &[u8],
65    metadata_offset: u64,
66    metadata_size: u32,
67) -> Result<AprV2Metadata, V2FormatError> {
68    let start = usize::try_from(metadata_offset)
69        .map_err(|_| V2FormatError::InvalidHeader("metadata_offset exceeds usize".to_string()))?;
70    let end = start
71        .checked_add(metadata_size as usize)
72        .ok_or_else(|| V2FormatError::InvalidHeader("metadata offset+size overflow".to_string()))?;
73    let slice = data
74        .get(start..end)
75        .ok_or_else(|| V2FormatError::InvalidHeader("file too small for metadata".to_string()))?;
76    AprV2Metadata::from_json(slice)
77}
78
79/// The smallest encodable tensor-index entry, in bytes, as `TensorIndexEntry::from_bytes`
80/// reads it: u16 name length + u8 dtype + u8 ndim + u64 offset + u64 size (an empty
81/// name and zero dimensions). Public: a caller bounding the index extent BEFORE any
82/// reader runs (aprender-decide's rung 2) uses this one definition.
83pub const MIN_INDEX_ENTRY_BYTES: usize = 20;
84
85/// The unit the index reservation is counted in: the LARGER of an entry's on-disk
86/// minimum and its in-memory size. A parsed `TensorIndexEntry` holds a `String` and a
87/// `Vec` besides its scalars, so it is several times the 20-byte on-disk minimum;
88/// counting capacity in on-disk units let a forged count reserve ~3.6x the file size
89/// (V2-b, plan 08-20).
90pub(super) const INDEX_RESERVE_UNIT_BYTES: usize = {
91    let in_memory = std::mem::size_of::<TensorIndexEntry>();
92    if in_memory > MIN_INDEX_ENTRY_BYTES {
93        in_memory
94    } else {
95        MIN_INDEX_ENTRY_BYTES
96    }
97};
98
99/// The tensor-index vector's initial capacity: the declared `tensor_count`, but never
100/// more entries than would occupy, IN MEMORY, the `remaining` index bytes the file
101/// actually holds.
102///
103/// `tensor_count` comes from the header, and the header CRC covers only the header, so
104/// a small file with a valid CRC can declare `u32::MAX` entries. Reserving that many
105/// up front would request hundreds of GB before the first entry is parsed. Bounding in
106/// on-disk units is not enough either: that still reserves `size_of::<TensorIndexEntry>()
107/// / 20` times the index bytes. With the in-memory unit the up-front reservation never
108/// exceeds the bytes the file supplies; a valid index that holds more entries than that
109/// simply grows the vector as it parses. The parse loop still iterates `tensor_count`
110/// times and fails on the first entry the bytes cannot hold, so a valid file behaves
111/// exactly as before.
112pub(super) fn index_capacity(tensor_count: u32, remaining: usize) -> usize {
113    (tensor_count as usize).min(remaining / INDEX_RESERVE_UNIT_BYTES)
114}
115
116#[cfg(test)]
117thread_local! {
118    /// The capacity the most recent `parse_tensor_index_section` on this thread actually
119    /// reserved, read back from `Vec::capacity` AFTER the allocation — so a change to how
120    /// the reservation is computed cannot slip past the test that watches it. A counting
121    /// global allocator is not available (`unsafe_code = "forbid"`).
122    static LAST_INDEX_RESERVE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
123}
124
125/// Test hook: the index capacity (in entries) the last parse on this thread reserved.
126#[cfg(test)]
127pub(super) fn last_index_reserve() -> usize {
128    LAST_INDEX_RESERVE.with(std::cell::Cell::get)
129}
130
131/// Parse and bounds-check the tensor index section (FALSIFY-PARSE-001).
132///
133/// `tensor_index_offset` is attacker-controllable; previously it was used
134/// directly as `&data[pos..]`, which PANICS ("range start index out of bounds")
135/// when the offset points past EOF. Now the start offset is validated against
136/// the file length before slicing, and each entry advances `pos` with the same
137/// `slice::get` guard.
138fn parse_tensor_index_section(
139    data: &[u8],
140    tensor_index_offset: u64,
141    tensor_count: u32,
142) -> Result<Vec<TensorIndexEntry>, V2FormatError> {
143    let mut pos = usize::try_from(tensor_index_offset).map_err(|_| {
144        V2FormatError::InvalidTensorIndex("tensor_index_offset exceeds usize".to_string())
145    })?;
146
147    let remaining_index_bytes = data.len().saturating_sub(pos);
148    let mut tensor_index = Vec::with_capacity(index_capacity(tensor_count, remaining_index_bytes));
149    #[cfg(test)]
150    LAST_INDEX_RESERVE.with(|c| c.set(tensor_index.capacity()));
151    for _ in 0..tensor_count {
152        // `data.get(pos..)` returns None only when pos > data.len(); pos == len
153        // yields an empty slice, which TensorIndexEntry::from_bytes rejects
154        // cleanly. This replaces the panicking `&data[pos..]`.
155        let remaining = data.get(pos..).ok_or_else(|| {
156            V2FormatError::InvalidTensorIndex("tensor index offset past end of file".to_string())
157        })?;
158        let (entry, consumed) = TensorIndexEntry::from_bytes(remaining)?;
159        tensor_index.push(entry);
160        pos = pos.checked_add(consumed).ok_or_else(|| {
161            V2FormatError::InvalidTensorIndex("tensor index position overflow".to_string())
162        })?;
163    }
164
165    // Verify tensor names are STRICTLY increasing (WR-01 / AL5, plan 08-20). Every
166    // lookup (`get_tensor`, `get_tensor_data`) takes the first match, so an index that
167    // names a tensor twice would let a second, never-validated entry ride behind the
168    // first. Equal adjacent names are therefore refused, not merely out-of-order ones.
169    for pair in tensor_index.windows(2) {
170        let (prev, cur) = (&pair[0].name, &pair[1].name);
171        if cur == prev {
172            return Err(V2FormatError::InvalidTensorIndex(format!(
173                "duplicate tensor name {cur:?} in tensor index"
174            )));
175        }
176        if cur < prev {
177            return Err(V2FormatError::InvalidTensorIndex(format!(
178                "tensor index not sorted: {cur:?} follows {prev:?}"
179            )));
180        }
181    }
182
183    Ok(tensor_index)
184}
185
186/// The minimum file length the container's own header + tensor index imply
187/// (issue #2612).
188///
189/// # The invariant
190///
191/// ```text
192/// data_offset + max(entry.offset + align_64(entry.size)) <= file_length
193/// ```
194///
195/// Every byte of every tensor the index declares must exist inside the file,
196/// **and so must the 64-byte alignment padding that follows it** — both APR v2
197/// writers (`AprV2Writer::write`, `AprV2StreamingWriter::add_tensor`) pad every
198/// tensor unconditionally, the last one included. This is pure arithmetic over
199/// the container's self-description: it reads no tensor data, so it costs
200/// O(tensor_count) regardless of file size, and it holds for every APR v2
201/// writer, because the on-disk order is header, metadata, index, data, footer —
202/// the declared extent of a complete file is always bounded by EOF.
203///
204/// The GGUF path has enforced the same invariant since GH-707 / S1-FIX
205/// (`Truncated GGUF: file is N bytes but tensor data starts at byte M`). The
206/// APR path had no equivalent, and the asymmetry is exactly why a `.apr`
207/// truncated to 4.5% of its length validated clean: header, metadata and index
208/// all live in FRONT of the data section, so every structure the reader
209/// actually parses survives the truncation intact.
210///
211/// # The residual, stated precisely
212///
213/// Both writers append a **4-byte CRC32 footer** after the padded data section,
214/// so the true length of a file they produced is `required_file_len(data) + 4`.
215/// This function deliberately stops short of it, and the reason is a
216/// measurement, not caution: of the ten parseable APR v2 files in the local
217/// corpus, **two carry no footer at all** —
218/// `~/models/qwen2.5-coder-1.5b-instruct-q4k.apr` and its `-q4k-v2` sibling are
219/// each exactly `required_file_len` bytes long, four short of
220/// `required_file_len + 4`. Requiring the footer would report both intact files
221/// as truncated. So a file missing only its last 4 bytes still passes this
222/// check; catching that needs check 4 (footer CRC32), which is still a declared
223/// `Skip("Footer not implemented")` stub — and which cannot simply be switched
224/// on for the same reason those two files just demonstrated.
225///
226/// Including the padding, verified against the same corpus, removes the rest of
227/// the tail slack: the unpadded bound left up to 63 further bytes undetected
228/// (measured 60 on `whisper.apr/models/tiny-int8.apr`, 36 on the in-tree
229/// `tests/fixtures/golden_v2.apr`), and the padded bound is `<= file_length` on
230/// all ten.
231///
232/// # Errors
233///
234/// Returns [`V2FormatError`] when `data` is not an APR v2 container at all (too
235/// short for the header, or wrong magic) — the caller cannot conclude anything
236/// about truncation in that case — or when the tensor index itself cannot be
237/// parsed, which IS evidence of a damaged file and should be reported as such.
238pub fn required_file_len(data: &[u8]) -> Result<u64, V2FormatError> {
239    // 64-byte alignment, in u64 so a u64 tensor size never round-trips through
240    // usize (32-bit targets) on its way to the comparison.
241    const ALIGN: u64 = 64;
242
243    let header = AprV2Header::from_bytes(data)?;
244    let tensor_index =
245        parse_tensor_index_section(data, header.tensor_index_offset, header.tensor_count)?;
246
247    let mut required = header.data_offset;
248    for entry in &tensor_index {
249        let overflow = || {
250            V2FormatError::InvalidTensorIndex(format!(
251                "tensor '{}' extent overflows u64 (offset {}, size {})",
252                entry.name, entry.offset, entry.size
253            ))
254        };
255        let padded_size = entry
256            .size
257            .checked_add(ALIGN - 1)
258            .map(|v| v & !(ALIGN - 1))
259            .ok_or_else(overflow)?;
260        let end = header
261            .data_offset
262            .checked_add(entry.offset)
263            .and_then(|start| start.checked_add(padded_size))
264            .ok_or_else(overflow)?;
265        required = required.max(end);
266    }
267    Ok(required)
268}
269
270impl AprV2Reader {
271    /// Read from bytes
272    ///
273    /// # Errors
274    /// Returns error if parsing fails.
275    ///
276    /// # LAYOUT-002 Jidoka Guard
277    /// Rejects APR files with `LAYOUT_COLUMN_MAJOR` flag set, as these indicate
278    /// improperly converted GGUF files that would produce garbage output.
279    pub fn from_bytes(data: &[u8]) -> Result<Self, V2FormatError> {
280        if data.len() < HEADER_SIZE_V2 {
281            return Err(V2FormatError::InvalidHeader("file too small".to_string()));
282        }
283
284        // Parse header
285        let header = AprV2Header::from_bytes(data)?;
286
287        // Verify checksum
288        if !header.verify_checksum() {
289            return Err(V2FormatError::ChecksumMismatch);
290        }
291
292        // LAYOUT-002: Jidoka Guard - Reject "dirty" APR files with column-major layout
293        if !header.flags.is_layout_valid() {
294            return Err(V2FormatError::InvalidHeader(
295                "LAYOUT-002 violation: APR file has LAYOUT_COLUMN_MAJOR flag set. \
296                 This indicates a dirty import from GGUF without proper transpose. \
297                 Re-import the model using `apr import` with LAYOUT-002 enforcement."
298                    .to_string(),
299            ));
300        }
301
302        // Parse metadata (FALSIFY-PARSE-001 / PMAT-822: checked arithmetic +
303        // .get() so a corrupted metadata_offset/size can never panic-slice).
304        let metadata = parse_metadata_section(data, header.metadata_offset, header.metadata_size)?;
305
306        // Parse tensor index
307        let tensor_index =
308            parse_tensor_index_section(data, header.tensor_index_offset, header.tensor_count)?;
309
310        Ok(Self {
311            header,
312            metadata,
313            tensor_index,
314            data: data.to_vec(),
315        })
316    }
317
318    /// Read from a Read impl
319    ///
320    /// # Errors
321    /// Returns error if read fails.
322    pub fn from_reader<R: Read>(reader: &mut R) -> Result<Self, V2FormatError> {
323        let mut data = Vec::new();
324        reader
325            .read_to_end(&mut data)
326            .map_err(|e| V2FormatError::IoError(e.to_string()))?;
327        Self::from_bytes(&data)
328    }
329
330    /// Get header
331    #[must_use]
332    pub fn header(&self) -> &AprV2Header {
333        &self.header
334    }
335
336    /// Get metadata
337    #[must_use]
338    pub fn metadata(&self) -> &AprV2Metadata {
339        &self.metadata
340    }
341
342    /// Get tensor names
343    #[must_use]
344    pub fn tensor_names(&self) -> Vec<&str> {
345        self.tensor_index.iter().map(|e| e.name.as_str()).collect()
346    }
347
348    /// Get tensor by name
349    #[must_use]
350    pub fn get_tensor(&self, name: &str) -> Option<&TensorIndexEntry> {
351        self.tensor_index.iter().find(|e| e.name == name)
352    }
353
354    /// Get tensor data by name
355    #[must_use]
356    pub fn get_tensor_data(&self, name: &str) -> Option<&[u8]> {
357        let entry = self.get_tensor(name)?;
358        // FALSIFY-PARSE-001 / PMAT-822: data_offset + offset (u64) and
359        // start + size (usize) can both wrap for a crafted header, letting a
360        // wrapped `end <= len` check pass over an OOB region. Use checked
361        // arithmetic + `slice::get` so any overflow / past-EOF range → None.
362        let abs_offset = self.header.data_offset.checked_add(entry.offset)?;
363        let start = usize::try_from(abs_offset).ok()?;
364        let end = start.checked_add(usize::try_from(entry.size).ok()?)?;
365        self.data.get(start..end)
366    }
367
368    /// Get tensor as f32 slice (F32 dtype only)
369    #[must_use]
370    pub fn get_f32_tensor(&self, name: &str) -> Option<Vec<f32>> {
371        let entry = self.get_tensor(name)?;
372        if entry.dtype != TensorDType::F32 {
373            return None;
374        }
375
376        let data = self.get_tensor_data(name)?;
377        // `as_chunks::<4>()` rather than `chunks_exact(4)`: same semantics
378        // (the ragged tail is the discarded `.1`), but it yields `&[u8; 4]`,
379        // so `from_le_bytes` takes the array directly instead of a
380        // reassembled one. clippy::chunks_exact_to_as_chunks (new in 1.98)
381        // flags the old form; caught by the Toolchain Ceiling lane, which is
382        // exactly the drift it exists to catch.
383        let floats: Vec<f32> = data
384            .as_chunks::<4>()
385            .0
386            .iter()
387            .map(|chunk| f32::from_le_bytes(*chunk))
388            .collect();
389
390        Some(floats)
391    }
392
393    // NOTE (issue #2231): `get_tensor_as_f32` (the dequantizing accessor) is
394    // SEVERED from the sovereign leaf — it needed the GGUF Q4_K/Q6_K dequant
395    // kernels + the f16-scaled `dequantize_q4`, all framework/quant concerns.
396    // `aprender-core` re-attaches it via the `AprV2DequantExt` extension trait.
397
398    /// Check if all tensors are 64-byte aligned
399    #[must_use]
400    pub fn verify_alignment(&self) -> bool {
401        let data_offset = self.header.data_offset as usize;
402        self.tensor_index
403            .iter()
404            .all(|e| is_aligned_64(data_offset + e.offset as usize))
405    }
406
407    /// Borrow the parsed tensor index (used by the core dequant extension).
408    #[must_use]
409    pub fn tensor_index(&self) -> &[TensorIndexEntry] {
410        &self.tensor_index
411    }
412}
413
414impl<'a> AprV2ReaderRef<'a> {
415    /// Read from bytes (zero-copy - borrows data)
416    ///
417    /// Unlike `AprV2Reader::from_bytes`, this does NOT copy the input data.
418    /// The reader borrows the slice, making it ideal for use with mmap.
419    ///
420    /// # Errors
421    /// Returns error if parsing fails.
422    ///
423    /// # LAYOUT-002 Jidoka Guard
424    /// Rejects APR files with `LAYOUT_COLUMN_MAJOR` flag set, as these indicate
425    /// improperly converted GGUF files that would produce garbage output.
426    pub fn from_bytes(data: &'a [u8]) -> Result<Self, V2FormatError> {
427        if data.len() < HEADER_SIZE_V2 {
428            return Err(V2FormatError::InvalidHeader("file too small".to_string()));
429        }
430
431        // Parse header
432        let header = AprV2Header::from_bytes(data)?;
433
434        // Verify checksum
435        if !header.verify_checksum() {
436            return Err(V2FormatError::ChecksumMismatch);
437        }
438
439        // LAYOUT-002: Jidoka Guard - Reject "dirty" APR files with column-major layout
440        if !header.flags.is_layout_valid() {
441            return Err(V2FormatError::InvalidHeader(
442                "LAYOUT-002 violation: APR file has LAYOUT_COLUMN_MAJOR flag set. \
443                 This indicates a dirty import from GGUF without proper transpose. \
444                 Re-import the model using `apr import` with LAYOUT-002 enforcement."
445                    .to_string(),
446            ));
447        }
448
449        // Parse metadata (FALSIFY-PARSE-001 / PMAT-822: checked arithmetic +
450        // .get() so a corrupted metadata_offset/size can never panic-slice).
451        let metadata = parse_metadata_section(data, header.metadata_offset, header.metadata_size)?;
452
453        // Parse tensor index
454        let tensor_index =
455            parse_tensor_index_section(data, header.tensor_index_offset, header.tensor_count)?;
456
457        Ok(Self {
458            header,
459            metadata,
460            tensor_index,
461            data, // Borrow, no copy!
462        })
463    }
464
465    /// Get header
466    #[must_use]
467    pub fn header(&self) -> &AprV2Header {
468        &self.header
469    }
470
471    /// Get metadata
472    #[must_use]
473    pub fn metadata(&self) -> &AprV2Metadata {
474        &self.metadata
475    }
476
477    /// Get tensor names
478    #[must_use]
479    pub fn tensor_names(&self) -> Vec<&str> {
480        self.tensor_index.iter().map(|e| e.name.as_str()).collect()
481    }
482
483    /// Get tensor by name
484    #[must_use]
485    pub fn get_tensor(&self, name: &str) -> Option<&TensorIndexEntry> {
486        self.tensor_index.iter().find(|e| e.name == name)
487    }
488
489    /// Get tensor data by name (zero-copy slice into mmap)
490    #[must_use]
491    pub fn get_tensor_data(&self, name: &str) -> Option<&[u8]> {
492        let entry = self.get_tensor(name)?;
493        // FALSIFY-PARSE-001 / PMAT-822: data_offset + offset (u64) and
494        // start + size (usize) can both wrap for a crafted header, letting a
495        // wrapped `end <= len` check pass over an OOB region. Use checked
496        // arithmetic + `slice::get` so any overflow / past-EOF range → None.
497        let abs_offset = self.header.data_offset.checked_add(entry.offset)?;
498        let start = usize::try_from(abs_offset).ok()?;
499        let end = start.checked_add(usize::try_from(entry.size).ok()?)?;
500        self.data.get(start..end)
501    }
502
503    /// Get tensor as f32 Vec (copies data from mmap to `Vec<f32>`)
504    ///
505    /// Note: This allocates memory for the f32 values. For very large tensors,
506    /// consider using `get_tensor_data` and processing in chunks.
507    #[must_use]
508    pub fn get_f32_tensor(&self, name: &str) -> Option<Vec<f32>> {
509        let entry = self.get_tensor(name)?;
510        if entry.dtype != TensorDType::F32 {
511            return None;
512        }
513
514        let data = self.get_tensor_data(name)?;
515        // `as_chunks::<4>()` rather than `chunks_exact(4)`: same semantics
516        // (the ragged tail is the discarded `.1`), but it yields `&[u8; 4]`,
517        // so `from_le_bytes` takes the array directly instead of a
518        // reassembled one. clippy::chunks_exact_to_as_chunks (new in 1.98)
519        // flags the old form; caught by the Toolchain Ceiling lane, which is
520        // exactly the drift it exists to catch.
521        let floats: Vec<f32> = data
522            .as_chunks::<4>()
523            .0
524            .iter()
525            .map(|chunk| f32::from_le_bytes(*chunk))
526            .collect();
527
528        Some(floats)
529    }
530
531    // NOTE (issue #2231): `get_tensor_as_f32` severed from the leaf — see the
532    // owning-reader note above. Re-attached in core via `AprV2DequantExt`.
533
534    /// Check if all tensors are 64-byte aligned
535    #[must_use]
536    pub fn verify_alignment(&self) -> bool {
537        let data_offset = self.header.data_offset as usize;
538        self.tensor_index
539            .iter()
540            .all(|e| is_aligned_64(data_offset + e.offset as usize))
541    }
542
543    /// Borrow the parsed tensor index (used by the core dequant extension).
544    #[must_use]
545    pub fn tensor_index(&self) -> &[TensorIndexEntry] {
546        &self.tensor_index
547    }
548}
549
550// ============================================================================
551// Shard Manifest
552// ============================================================================
553
554/// Shard manifest for multi-file models
555#[derive(Debug, Clone, Serialize, Deserialize)]
556pub struct ShardManifest {
557    /// Format version
558    pub version: String,
559    /// Total number of shards
560    pub shard_count: usize,
561    /// Total size in bytes
562    pub total_size: u64,
563    /// Total tensor count
564    pub tensor_count: usize,
565    /// Shard files
566    pub shards: Vec<ShardInfo>,
567    /// Tensor to shard mapping
568    pub weight_map: HashMap<String, usize>,
569}
570
571/// Information about a single shard
572#[derive(Debug, Clone, Serialize, Deserialize)]
573pub struct ShardInfo {
574    /// Shard filename
575    pub filename: String,
576    /// Shard index
577    pub index: usize,
578    /// Size in bytes
579    pub size: u64,
580    /// Tensor names in this shard
581    pub tensors: Vec<String>,
582}