Files
leleka/crates/model-format/src/kar.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 664d434fca feat(model-format): KAR level-decode kernel model and nested record descriptor
Adds KarNestedRecord (section layout of a NESTED record, validated with the
inspector's formulas) and a literal CPU transcription of the planned CUDA
level-decode and F32 row-multiply kernels (window planning, packet layout,
thread/block decomposition, plane word and group scale addressing) for runtime
levels 2..=5. Randomized tests compare it with a transcription of the CPU
decode oracle, including partial last groups, word-unaligned ranges, expert
row windows and overlay-style per-archive dials. Verifies the specification
only; no CUDA build or GPU run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 14:42:42 +02:00

1169 lines
44 KiB
Rust

//! Shared bounded KAR2 persistence, extracted from control-plane/src/kar.rs.
//! Metadata inspection is not serving verification. No CUDA or serving decoder lives here.
//! Archive verification retains one descriptor; the caller guarantees owner-controlled
//! immutable contents from inspection through the complete binding lifetime.
use sha2::{Digest, Sha256};
use std::{
collections::HashSet,
fs::File,
io::{Read, Seek, SeekFrom},
};
#[derive(Debug)]
pub enum KarError {
Format(&'static str),
Range(&'static str),
Integrity(&'static str),
Profile(&'static str),
Allocation,
Io(std::io::Error),
}
impl std::fmt::Display for KarError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Format(s) | Self::Range(s) | Self::Integrity(s) | Self::Profile(s) => {
f.write_str(s)
}
Self::Allocation => f.write_str("KAR allocation failed"),
Self::Io(e) => e.fmt(f),
}
}
}
impl std::error::Error for KarError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
if let Self::Io(e) = self {
Some(e)
} else {
None
}
}
}
fn typed(error: String) -> KarError {
if error == "KAR allocation failed" {
return KarError::Allocation;
}
if error.contains("payload CRC-32 mismatch") {
return KarError::Integrity("KAR payload CRC-32 mismatch");
}
match error.as_str() {
"CPU KAR decoder requires 1..=1,000,000 values within tensor bounds" => {
KarError::Format("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds")
}
"KAR accounted_bpw does not match archive size" => {
KarError::Format("KAR accounted_bpw does not match archive size")
}
"KAR aggregate metadata mismatch" => KarError::Format("KAR aggregate metadata mismatch"),
"KAR archive length mismatch" => KarError::Format("KAR archive length mismatch"),
"KAR book offset overflow" => KarError::Format("KAR book offset overflow"),
"KAR books offset overflow" => KarError::Format("KAR books offset overflow"),
"KAR coded bit count overflow" => KarError::Format("KAR coded bit count overflow"),
"KAR decode base overflow" => KarError::Format("KAR decode base overflow"),
"KAR decode padded size overflow" => KarError::Format("KAR decode padded size overflow"),
"KAR decode range exceeds padded tensor" => {
KarError::Format("KAR decode range exceeds padded tensor")
}
"KAR decode range overflow" => KarError::Format("KAR decode range overflow"),
"KAR directory digest mismatch" => KarError::Format("KAR directory digest mismatch"),
"KAR directory length overflow" => KarError::Format("KAR directory length overflow"),
"KAR directory overflow" => KarError::Format("KAR directory overflow"),
"KAR group is zero" => KarError::Format("KAR group is zero"),
"KAR header CRC-32 mismatch" => KarError::Format("KAR header CRC-32 mismatch"),
"KAR metadata exceeds bounded inspector limits" => {
KarError::Format("KAR metadata exceeds bounded inspector limits")
}
"KAR model element count overflow" => KarError::Format("KAR model element count overflow"),
"KAR name offset overflow" => KarError::Format("KAR name offset overflow"),
"KAR padded count overflow" => KarError::Format("KAR padded count overflow"),
"KAR padded tensor count mismatch" => KarError::Format("KAR padded tensor count mismatch"),
"KAR plane offset overflow" => KarError::Format("KAR plane offset overflow"),
"KAR plane size overflow" => KarError::Format("KAR plane size overflow"),
"KAR plane stride overflow" => KarError::Format("KAR plane stride overflow"),
"KAR planes offset overflow" => KarError::Format("KAR planes offset overflow"),
"KAR raw byte count overflow" => KarError::Format("KAR raw byte count overflow"),
"KAR raw offset overflow" => KarError::Format("KAR raw offset overflow"),
"KAR raw tensor section is too small" => {
KarError::Format("KAR raw tensor section is too small")
}
"KAR raw tensor size overflow" => KarError::Format("KAR raw tensor size overflow"),
"KAR scale byte count overflow" => KarError::Format("KAR scale byte count overflow"),
"KAR scale count overflow" => KarError::Format("KAR scale count overflow"),
"KAR scale offset overflow" => KarError::Format("KAR scale offset overflow"),
"KAR source identity differs from verified manifest shards" => {
KarError::Format("KAR source identity differs from verified manifest shards")
}
"KAR string table overflow" => KarError::Format("KAR string table overflow"),
"KAR tensor bit count overflow" => KarError::Format("KAR tensor bit count overflow"),
"KAR tensor element count mismatch" => {
KarError::Format("KAR tensor element count mismatch")
}
"KAR tensor is too large" => KarError::Format("KAR tensor is too large"),
"KAR tensor name is not UTF-8" => KarError::Format("KAR tensor name is not UTF-8"),
"KAR tensor section overflow" => KarError::Format("KAR tensor section overflow"),
"KAR tensor sections are not contiguous or bounded" => {
KarError::Format("KAR tensor sections are not contiguous or bounded")
}
"KAR tensor shape overflow" => KarError::Format("KAR tensor shape overflow"),
"KARCHIV2" => KarError::Format("KARCHIV2"),
"duplicate KAR tensor name" => KarError::Format("duplicate KAR tensor name"),
"invalid KAR byte order or record size" => {
KarError::Format("invalid KAR byte order or record size")
}
"invalid KAR flags, digest algorithm, or element counts" => {
KarError::Format("invalid KAR flags, digest algorithm, or element counts")
}
"invalid KAR metadata offsets or alignment" => {
KarError::Format("invalid KAR metadata offsets or alignment")
}
"invalid KAR nested tensor parameters" => {
KarError::Format("invalid KAR nested tensor parameters")
}
"invalid KAR nested tensor section layout" => {
KarError::Format("invalid KAR nested tensor section layout")
}
"invalid KAR raw tensor metadata" => KarError::Format("invalid KAR raw tensor metadata"),
"invalid KAR tensor name bounds" => KarError::Format("invalid KAR tensor name bounds"),
"invalid KAR unused dimension" => KarError::Format("invalid KAR unused dimension"),
"source manifest contains an invalid file name" => {
KarError::Format("source manifest contains an invalid file name")
}
"unsupported KAR archive magic or version" => {
KarError::Format("unsupported KAR archive magic or version")
}
"unsupported KAR tensor layout" => KarError::Format("unsupported KAR tensor layout"),
_ => KarError::Io(std::io::Error::other(error)),
}
}
const HEADER_BYTES: usize = 256;
const RECORD_BYTES: usize = 192;
const MAX_TENSORS: usize = 100_000;
const MAX_NAMES: usize = 64 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq)]
pub struct KarSummary {
pub archive_bytes: u64,
pub tensor_count: u32,
pub total_elements: u64,
pub source_total_elements: u64,
pub accounted_bpw: f64,
pub source_digest: [u8; 32],
pub source_bytes: u64,
pub max_planes: u8,
}
#[derive(Clone, Debug)]
pub struct KarTensorSource {
pub name: String,
pub dimensions: Vec<u64>,
pub dtype: u8,
pub digest: [u8; 32],
pub offset: u64,
pub section_bytes: u64,
pub storage_class: u8,
pub n_elements: u64,
pub planes_min: u8,
pub planes_max: u8,
pub section_offset: u64,
pub planes_offset: u64,
pub plane_stride_bytes: u32,
}
impl KarTensorSource {
/// The bytes libkar::kar_reserve stages for this record at the requested
/// level. RAW records have no precision dial and always stage in full.
pub fn gpu_resident_bytes(&self, level: u8) -> Result<u64, KarError> {
if self.storage_class == 1 {
return Ok(self.section_bytes);
}
if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max {
return Err(KarError::Profile("KAR level is outside its supported dial"));
}
self.planes_offset
.checked_sub(self.section_offset)
.and_then(|prefix| {
prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes))
})
.filter(|bytes| *bytes <= self.section_bytes)
.ok_or(KarError::Range("invalid KAR GPU prefix size"))
}
pub fn gpu_decode_bytes(&self) -> Result<u64, KarError> {
self.n_elements
.checked_mul(4)
.ok_or(KarError::Range("KAR F32 decode size overflow"))
}
/// One-row output size for a geometrically addressable NESTED table.
/// Whether the model can consume only selected rows is a separate question.
pub fn gpu_one_row_decode_bytes(&self) -> Option<u64> {
let row_len = *self.dimensions.first()?;
if self.storage_class == 0
&& self.dimensions.len() >= 2
&& row_len.is_multiple_of(32)
&& row_len <= u32::MAX as u64
&& self.n_elements > row_len
&& self.n_elements.is_multiple_of(row_len)
{
row_len.checked_mul(4)
} else {
None
}
}
}
type ScalarDecoder = fn(&[u16], &[u16], &[&[u32]], u16, usize, &mut [f32]) -> Result<(), String>;
pub struct KarInspection {
summary: KarSummary,
file: File,
sections: Vec<Section>,
sources: Vec<KarTensorSource>,
directory: Vec<u8>,
}
pub struct KarImmutableSource {
inspection: KarInspection,
}
impl KarInspection {
pub fn inspect(file: File) -> Result<Self, KarError> {
let Parsed {
summary,
file,
sections,
sources,
directory,
} = inspect_file(file).map_err(typed)?;
Ok(Self {
summary,
file,
sections,
sources,
directory,
})
}
pub fn summary(&self) -> &KarSummary {
&self.summary
}
pub fn tensor_sources(&self) -> &[KarTensorSource] {
&self.sources
}
pub fn verify_payloads(&mut self) -> Result<(), KarError> {
let mut buffer = Vec::new();
buffer
.try_reserve_exact(8 * 1024 * 1024)
.map_err(|_| KarError::Allocation)?;
buffer.resize(8 * 1024 * 1024, 0);
for section in &self.sections {
self.file
.seek(SeekFrom::Start(section.offset))
.map_err(KarError::Io)?;
let mut remaining = section.bytes;
let mut crc = !0u32;
while remaining > 0 {
let n = remaining.min(buffer.len() as u64) as usize;
self.file
.read_exact(&mut buffer[..n])
.map_err(KarError::Io)?;
crc = crc32_step(crc, &buffer[..n]);
remaining -= n as u64;
}
if !crc != section.crc32 {
return Err(KarError::Integrity("KAR payload CRC-32 mismatch"));
}
}
Ok(())
}
fn verify_integrity(&mut self, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> {
let mut buffer = Vec::new();
buffer
.try_reserve_exact(8 * 1024 * 1024)
.map_err(|_| KarError::Allocation)?;
buffer.resize(8 * 1024 * 1024, 0);
self.file.seek(SeekFrom::Start(0)).map_err(KarError::Io)?;
verify_integrity_stream(&mut self.file, &self.sections, bytes, pin, &mut buffer)
}
pub fn decode_range(
&mut self,
name: &str,
level: u8,
start: usize,
count: usize,
decoder: ScalarDecoder,
) -> Result<Vec<f32>, KarError> {
let index = self
.sources
.iter()
.position(|s| s.name == name)
.ok_or(KarError::Range("KAR tensor not found"))?;
let record: [u8; RECORD_BYTES] = self.directory
[index * RECORD_BYTES..(index + 1) * RECORD_BYTES]
.try_into()
.expect("validated directory");
decode_record_range(&mut self.file, &record, level, start, count, decoder).map_err(typed)
}
/// Trusted-owner contract, not an OS/stat check: the caller establishes that
/// the retained inode has been immutable since inspection and remains so
/// for the entire binding lifetime. A read-only descriptor alone is insufficient.
pub fn into_owner_controlled(self) -> KarImmutableSource {
KarImmutableSource { inspection: self }
}
}
fn decode_record_range(
file: &mut File,
record: &[u8; RECORD_BYTES],
level: u8,
start: usize,
count: usize,
decoder: ScalarDecoder,
) -> Result<Vec<f32>, String> {
let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?;
let end = start
.checked_add(count)
.ok_or("KAR decode range overflow")?;
if count == 0 || count > 1_000_000 || end > elements {
return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into());
}
if record[7] == 1 {
if record[41] != 0 {
return Err("CPU quality oracle only supports RAW F32 tensors".into());
}
let offset = u64_at(record, 112)
.checked_add(
(start as u64)
.checked_mul(4)
.ok_or("KAR raw offset overflow")?,
)
.ok_or("KAR raw offset overflow")?;
let bytes = read_region(
file,
offset,
count.checked_mul(4).ok_or("KAR raw byte count overflow")?,
)?;
return Ok(bytes
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word))
.collect());
}
let stored = record[42];
if level == 0 || level > stored {
return Err(format!("KAR tensor stores 1..={stored} levels"));
}
let group = u16_at(record, 46);
let group_size = usize::from(group);
if group_size == 0 {
return Err("KAR group is zero".into());
}
let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?;
let base_group = start / group_size;
let end_group = end.div_ceil(group_size);
let base_element = base_group
.checked_mul(group_size)
.ok_or("KAR decode base overflow")?;
let local_padded = (end_group - base_group)
.checked_mul(group_size)
.ok_or("KAR decode padded size overflow")?;
if base_element
.checked_add(local_padded)
.is_none_or(|end| end > padded)
{
return Err("KAR decode range exceeds padded tensor".into());
}
let scale_bytes = read_region(
file,
u64_at(record, 64)
.checked_add(
(base_group as u64)
.checked_mul(2)
.ok_or("KAR scale offset overflow")?,
)
.ok_or("KAR scale offset overflow")?,
(end_group - base_group)
.checked_mul(2)
.ok_or("KAR scale byte count overflow")?,
)?;
let scales = scale_bytes
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect::<Vec<_>>();
let book_offset = u64_at(record, 80)
.checked_add((1u64 << (u32::from(level) + 1)) - 4)
.ok_or("KAR book offset overflow")?;
let book_bytes = read_region(file, book_offset, (1usize << level) * 2)?;
let book = book_bytes
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect::<Vec<_>>();
let plane_stride = u64::from(u32_at(record, 104));
let plane_bytes = local_padded / 32 * 4;
let plane_base = u64::try_from(
(base_element / 32)
.checked_mul(4)
.ok_or("KAR plane offset overflow")?,
)
.map_err(|_| "KAR plane offset overflow")?;
let mut planes = Vec::with_capacity(usize::from(level));
for plane in 0..u64::from(level) {
let offset = u64_at(record, 96)
.checked_add(
plane
.checked_mul(plane_stride)
.ok_or("KAR plane offset overflow")?,
)
.and_then(|offset| offset.checked_add(plane_base))
.ok_or("KAR plane offset overflow")?;
let bytes = read_region(file, offset, plane_bytes)?;
planes.push(
bytes
.as_chunks::<4>()
.0
.iter()
.map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]]))
.collect::<Vec<_>>(),
);
}
let plane_refs = planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let mut output = Vec::new();
output
.try_reserve_exact(count)
.map_err(|_| "KAR allocation failed")?;
output.resize(count, 0.0);
decoder(
&scales,
&book,
&plane_refs,
group,
start - base_element,
&mut output,
)?;
Ok(output)
}
struct Section {
offset: u64,
bytes: u64,
crc32: u32,
}
struct Parsed {
summary: KarSummary,
file: File,
sections: Vec<Section>,
sources: Vec<KarTensorSource>,
directory: Vec<u8>,
}
fn inspect_file(mut file: File) -> Result<Parsed, String> {
let file_bytes = file.metadata().map_err(|error| error.to_string())?.len();
let header = read_region(&mut file, 0, HEADER_BYTES)?;
if &header[0..8] != b"KARCHIV2" || u32_at(&header, 8) != 2 {
return Err("unsupported KAR archive magic or version".into());
}
if u32_at(&header, 12) != 0x04030201
|| u32_at(&header, 16) != HEADER_BYTES as u32
|| u32_at(&header, 20) != RECORD_BYTES as u32
{
return Err("invalid KAR byte order or record size".into());
}
if crc32(&header[..192]) != u32_at(&header, 192) {
return Err("KAR header CRC-32 mismatch".into());
}
let directory_offset = u64_at(&header, 24);
let tensor_count = u32_at(&header, 32);
let string_offset = u64_at(&header, 40);
let string_bytes = u64_at(&header, 48);
let payload_offset = u64_at(&header, 56);
let archive_bytes = u64_at(&header, 64);
let total_elements = u64_at(&header, 72);
let payload_bits = u64_at(&header, 80);
let source_total_elements = u64_at(&header, 88);
let source_bytes = u64_at(&header, 120);
let accounted_bpw = f64::from_le_bytes(header[96..104].try_into().unwrap());
let mut source_digest = [0; 32];
source_digest.copy_from_slice(&header[128..160]);
if archive_bytes != file_bytes || archive_bytes < HEADER_BYTES as u64 {
return Err("KAR archive length mismatch".into());
}
if tensor_count == 0 || tensor_count as usize > MAX_TENSORS || string_bytes > MAX_NAMES as u64 {
return Err("KAR metadata exceeds bounded inspector limits".into());
}
if u32_at(&header, 36) != 0
|| header[106] != 1
|| total_elements == 0
|| total_elements > source_total_elements
|| source_bytes == 0
{
return Err("invalid KAR flags, digest algorithm, or element counts".into());
}
let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64;
if !accounted_bpw.is_finite()
|| ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40)
{
return Err("KAR accounted_bpw does not match archive size".into());
}
let directory_bytes = (tensor_count as u64)
.checked_mul(RECORD_BYTES as u64)
.ok_or("KAR directory length overflow")?;
let directory_end = directory_offset
.checked_add(directory_bytes)
.ok_or("KAR directory overflow")?;
let string_end = string_offset
.checked_add(string_bytes)
.ok_or("KAR string table overflow")?;
if !directory_offset.is_multiple_of(64)
|| !string_offset.is_multiple_of(64)
|| !payload_offset.is_multiple_of(256)
|| directory_offset < HEADER_BYTES as u64
|| directory_end > string_offset
|| string_end > payload_offset
|| payload_offset > archive_bytes
{
return Err("invalid KAR metadata offsets or alignment".into());
}
let names = read_region(&mut file, string_offset, string_bytes as usize)?;
let directory = read_region(&mut file, directory_offset, directory_bytes as usize)?;
let mut digest = Sha256::new();
digest.update(&names);
digest.update(&directory);
if digest.finalize().as_slice() != &header[160..192] {
return Err("KAR directory digest mismatch".into());
}
let mut seen_names = HashSet::new();
seen_names
.try_reserve(tensor_count as usize)
.map_err(|_| "KAR allocation failed")?;
let mut elements_sum = 0u64;
let mut bits_sum = 0u64;
let mut previous_end = payload_offset;
let mut min_planes = u8::MAX;
let mut max_planes = 0u8;
let mut sections = Vec::new();
sections
.try_reserve_exact(tensor_count as usize)
.map_err(|_| "KAR allocation failed")?;
let mut sources = Vec::new();
sources
.try_reserve_exact(tensor_count as usize)
.map_err(|_| "KAR allocation failed")?;
let (records, remainder) = directory.as_chunks::<RECORD_BYTES>();
debug_assert!(remainder.is_empty());
for record in records {
let name_start = u32_at(record, 0) as usize;
let name_len = u16_at(record, 4) as usize;
let name_end = name_start
.checked_add(name_len)
.ok_or("KAR name offset overflow")?;
if name_end >= names.len() || names[name_end] != 0 {
return Err("invalid KAR tensor name bounds".into());
}
let name = std::str::from_utf8(&names[name_start..name_end])
.map_err(|_| "KAR tensor name is not UTF-8")?;
if !seen_names.insert(name) {
return Err("duplicate KAR tensor name".into());
}
let n_dims = record[6] as usize;
let storage = record[7];
if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 {
return Err("unsupported KAR tensor layout".into());
}
let dims = (0..4)
.map(|index| u64_at(record, 8 + index * 8))
.collect::<Vec<_>>();
if dims[n_dims..].iter().any(|dim| *dim != 1) {
return Err("invalid KAR unused dimension".into());
}
let product = dims[..n_dims]
.iter()
.try_fold(1u64, |acc, dim| acc.checked_mul(*dim))
.ok_or("KAR tensor shape overflow")?;
let n_elements = u64_at(record, 48);
if product != n_elements || n_elements == 0 {
return Err("KAR tensor element count mismatch".into());
}
elements_sum = elements_sum
.checked_add(n_elements)
.ok_or("KAR model element count overflow")?;
let mut source_digest = [0u8; 32];
source_digest.copy_from_slice(&record[128..160]);
sources.push(KarTensorSource {
name: name.to_owned(),
dimensions: dims[..n_dims].to_vec(),
dtype: record[41],
digest: source_digest,
offset: u64_at(record, 160),
section_bytes: u64_at(record, 120),
storage_class: storage,
n_elements,
planes_min: record[43],
planes_max: record[44],
section_offset: u64_at(record, 112),
planes_offset: u64_at(record, 96),
plane_stride_bytes: u32_at(record, 104),
});
let section_offset = u64_at(record, 112);
let section_bytes = u64_at(record, 120);
let section_end = section_offset
.checked_add(section_bytes)
.ok_or("KAR tensor section overflow")?;
if section_offset != previous_end
|| !section_offset.is_multiple_of(256)
|| section_end > archive_bytes
{
return Err("KAR tensor sections are not contiguous or bounded".into());
}
previous_end = section_end;
sections.push(Section {
offset: section_offset,
bytes: section_bytes,
crc32: u32_at(record, 108),
});
if storage == 0 {
let group = u16_at(record, 46) as u64;
let planes = record[42];
let n_padded = u64_at(record, 56);
if group == 0
|| group > 1024
|| !group.is_multiple_of(32)
|| !(1..=16).contains(&planes)
|| record[43] == 0
|| record[43] > record[44]
|| record[44] > planes
|| record[45] > 1
{
return Err("invalid KAR nested tensor parameters".into());
}
let rounded = n_elements
.div_ceil(group)
.checked_mul(group)
.ok_or("KAR padded count overflow")?;
if n_padded != rounded {
return Err("KAR padded tensor count mismatch".into());
}
let scales_offset = u64_at(record, 64);
let scales_bytes = u64_at(record, 72);
let books_offset = u64_at(record, 80);
let books_bytes = u64_at(record, 88);
let planes_offset = u64_at(record, 96);
let stride = u32_at(record, 104) as u64;
let expected_scales = (n_padded / group)
.checked_mul(2)
.ok_or("KAR scale count overflow")?;
let expected_books = (1u64 << (planes as u32 + 2)) - 4;
let plane_words_bytes = (n_padded / 32)
.checked_mul(4)
.ok_or("KAR plane size overflow")?;
let expected_stride =
round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?;
let books_start = scales_offset
.checked_add(scales_bytes)
.and_then(|value| round_up(value, 16))
.ok_or("KAR books offset overflow")?;
let planes_start = books_offset
.checked_add(books_bytes)
.and_then(|value| round_up(value, 16))
.ok_or("KAR planes offset overflow")?;
if scales_offset != section_offset
|| scales_bytes != expected_scales
|| books_offset != books_start
|| books_bytes != expected_books
|| planes_offset != planes_start
|| stride != expected_stride
|| planes_offset
.checked_add(planes as u64 * stride)
.is_none_or(|end| end > section_end)
{
return Err("invalid KAR nested tensor section layout".into());
}
let tensor_bits = (planes as u64)
.checked_mul(n_padded)
.and_then(|bits| {
(n_padded / group)
.checked_mul(16)
.and_then(|scale_bits| bits.checked_add(scale_bits))
})
.ok_or("KAR tensor bit count overflow")?;
bits_sum = bits_sum
.checked_add(tensor_bits)
.ok_or("KAR coded bit count overflow")?;
min_planes = min_planes.min(record[43]);
max_planes = max_planes.max(record[44]);
} else {
if record[42..48].iter().any(|value| *value != 0)
|| u64_at(record, 56) != n_elements
|| record[64..104].iter().any(|value| *value != 0)
|| u32_at(record, 104) != 0
{
return Err("invalid KAR raw tensor metadata".into());
}
let width = if record[41] == 0 { 4 } else { 2 };
if section_bytes
< n_elements
.checked_mul(width)
.ok_or("KAR raw tensor size overflow")?
{
return Err("KAR raw tensor section is too small".into());
}
}
}
if previous_end != archive_bytes
|| elements_sum != total_elements
|| bits_sum != payload_bits
|| header[104] != if min_planes == u8::MAX { 0 } else { min_planes }
|| header[105] != max_planes
{
return Err("KAR aggregate metadata mismatch".into());
}
let summary = KarSummary {
archive_bytes,
tensor_count,
total_elements,
source_total_elements,
accounted_bpw,
source_digest,
source_bytes,
max_planes,
};
Ok(Parsed {
summary,
file,
sections,
sources,
directory,
})
}
fn read_region(file: &mut File, offset: u64, length: usize) -> Result<Vec<u8>, String> {
file.seek(SeekFrom::Start(offset))
.map_err(|error| error.to_string())?;
let mut bytes = Vec::new();
bytes
.try_reserve_exact(length)
.map_err(|_| "KAR allocation failed")?;
bytes.resize(length, 0);
file.read_exact(&mut bytes)
.map_err(|error| error.to_string())?;
Ok(bytes)
}
fn u16_at(bytes: &[u8], offset: usize) -> u16 {
u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap())
}
fn u32_at(bytes: &[u8], offset: usize) -> u32 {
u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap())
}
fn u64_at(bytes: &[u8], offset: usize) -> u64 {
u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap())
}
pub fn crc32(bytes: &[u8]) -> u32 {
!crc32_step(!0u32, bytes)
}
const CRC32_TABLE: [u32; 256] = {
let mut table = [0; 256];
let mut byte = 0;
while byte < table.len() {
let mut crc = byte as u32;
let mut bit = 0;
while bit < 8 {
crc = (crc >> 1) ^ (0xedb88320u32 & (0u32.wrapping_sub(crc & 1)));
bit += 1;
}
table[byte] = crc;
byte += 1;
}
table
};
// Seven additional zero-byte advances of the ORIGINAL reflected IEEE table.
// These are read-only compile-time tables, with no ISA or host-endian dependency.
const CRC32_SLICES: [[u32; 256]; 7] = {
let mut tables = [[0; 256]; 7];
let mut byte = 0;
while byte < 256 {
let mut crc = CRC32_TABLE[byte];
let mut slice = 0;
while slice < tables.len() {
crc = (crc >> 8) ^ CRC32_TABLE[(crc & 255) as usize];
tables[slice][byte] = crc;
slice += 1;
}
byte += 1;
}
tables
};
pub fn crc32_step(mut crc: u32, bytes: &[u8]) -> u32 {
let (blocks, tail) = bytes.as_chunks::<8>();
for block in blocks {
let first = u32::from_le_bytes([block[0], block[1], block[2], block[3]]) ^ crc;
crc = CRC32_SLICES[6][(first & 255) as usize]
^ CRC32_SLICES[5][((first >> 8) & 255) as usize]
^ CRC32_SLICES[4][((first >> 16) & 255) as usize]
^ CRC32_SLICES[3][(first >> 24) as usize]
^ CRC32_SLICES[2][usize::from(block[4])]
^ CRC32_SLICES[1][usize::from(block[5])]
^ CRC32_SLICES[0][usize::from(block[6])]
^ CRC32_TABLE[usize::from(block[7])];
}
// Preserve the original scalar transition for all remaining zero to seven bytes.
for &byte in tail {
crc = (crc >> 8) ^ CRC32_TABLE[((crc ^ u32::from(byte)) & 255) as usize];
}
crc
}
/// Inspect has already admitted contiguous sections. Recheck their bounds here
/// before consuming bytes, including in the small streaming regression seam.
fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), KarError> {
let mut end = sections.first().map_or(bytes, |s| s.offset);
for section in sections {
if section.offset != end || section.bytes == 0 {
return Err(KarError::Range("KAR integrity section bounds"));
}
end = end
.checked_add(section.bytes)
.filter(|end| *end <= bytes)
.ok_or(KarError::Range("KAR integrity section bounds"))?;
}
if sections.is_empty() || end != bytes {
return Err(KarError::Range("KAR integrity section bounds"));
}
Ok(())
}
fn verify_integrity_stream(
file: &mut impl Read,
sections: &[Section],
bytes: u64,
pin: &[u8; 32],
buffer: &mut [u8],
) -> Result<(), KarError> {
integrity_sections(sections, bytes)?;
if buffer.is_empty() {
return Err(KarError::Range("KAR integrity buffer is empty"));
}
let mut digest = Sha256::new();
let mut total = 0u64;
let mut index = 0;
let mut crc = !0u32;
let mut crc_failed = false;
loop {
let n = file.read(buffer).map_err(KarError::Io)?;
if n == 0 {
break;
}
let end = total
.checked_add(n as u64)
.ok_or(KarError::Range("KAR hash length overflow"))?;
digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too.
while let Some(section) = sections.get(index) {
if section.offset >= end {
break;
}
let section_end = section.offset + section.bytes; // Checked above.
let start = total.max(section.offset);
let stop = end.min(section_end);
crc = crc32_step(
crc,
&buffer[(start - total) as usize..(stop - total) as usize],
);
if stop != section_end {
break;
}
crc_failed |= !crc != section.crc32;
crc = !0u32;
index += 1;
}
total = end;
}
// A CRC failure never shortcuts the full hash or changes SHA-first precedence.
if total != bytes || digest.finalize().as_slice() != pin {
return Err(KarError::Integrity("KAR full archive SHA-256 mismatch"));
}
if crc_failed || index != sections.len() {
return Err(KarError::Integrity("KAR payload CRC-32 mismatch"));
}
Ok(())
}
fn round_up(value: u64, alignment: u64) -> Option<u64> {
value.div_ceil(alignment).checked_mul(alignment)
}
/// Values from a trusted, pinned provenance manifest, not an archive header.
pub struct KarPlePartProvenance {
pub name: String,
pub row_base: u64,
pub row_count: u64,
pub derived_f32_offset: u64,
pub derived_f32_sha256: [u8; 32],
}
pub struct KarPleProfileSpec {
pub archive_bytes: u64,
pub archive_sha256: [u8; 32],
pub provenance_sha256: [u8; 32],
pub virtual_f32_bytes: u64,
pub virtual_f32_sha256: [u8; 32],
pub native_shard_sha256: [[u8; 32]; 2],
pub parts: Vec<KarPlePartProvenance>,
}
pub struct KarPleProfile {
spec: KarPleProfileSpec,
}
const PLE_ROWS: u64 = 320_001_536;
impl KarPleProfile {
/// Bounds validation does not authenticate the manifest's origin. Only the
/// admitted model-binding loader may supply its trusted pinned expectations.
pub fn new(spec: KarPleProfileSpec) -> Result<Self, KarError> {
if spec.archive_bytes < 256
|| spec.virtual_f32_bytes == 0
|| spec.parts.is_empty()
|| spec.parts.len() > 65535
|| spec.archive_sha256 == [0; 32]
|| spec.provenance_sha256 == [0; 32]
|| spec.virtual_f32_sha256 == [0; 32]
|| spec.native_shard_sha256.contains(&[0; 32])
{
return Err(KarError::Profile("invalid KAR PLE profile"));
}
let mut next = 0u64;
let mut names = HashSet::new();
names
.try_reserve(spec.parts.len())
.map_err(|_| KarError::Allocation)?;
for p in &spec.parts {
if p.name.is_empty()
|| p.name.len() > 1024
|| p.name.bytes().any(|b| b < 32 || b == 127)
|| !names.insert(p.name.as_str())
|| p.row_base != next
|| p.row_count == 0
|| p.derived_f32_sha256 == [0; 32]
{
return Err(KarError::Profile("invalid KAR PLE partition provenance"));
}
next = next
.checked_add(p.row_count)
.filter(|n| *n <= PLE_ROWS)
.ok_or(KarError::Range("KAR PLE row count overflow"))?;
p.row_count
.checked_mul(640)
.and_then(|n| p.derived_f32_offset.checked_add(n))
.filter(|n| *n <= spec.virtual_f32_bytes)
.ok_or(KarError::Range("KAR PLE virtual source range"))?;
}
if next != PLE_ROWS {
return Err(KarError::Profile("KAR PLE table extent mismatch"));
}
Ok(Self { spec })
}
pub fn native_shard_sha256(&self) -> &[[u8; 32]; 2] {
&self.spec.native_shard_sha256
}
}
#[derive(Clone, Copy)]
pub struct KarPleRowPacket {
payload: [u8; 50],
partition: u16,
}
impl KarPleRowPacket {
pub fn payload(&self) -> &[u8; 50] {
&self.payload
}
pub fn partition(&self) -> u16 {
self.partition
}
}
struct VerifiedPart {
row_base: u64,
row_count: u64,
scales: u64,
planes: u64,
stride: u64,
}
pub struct VerifiedKarPleArtifact {
reader: KarInspection,
profile: KarPleProfile,
parts: Vec<VerifiedPart>,
books: Vec<[u16; 4]>,
}
impl VerifiedKarPleArtifact {
pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result<Self, KarError> {
let mut reader = source.inspection;
if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes
|| reader.summary.archive_bytes != profile.spec.archive_bytes
|| reader.summary.source_bytes != profile.spec.virtual_f32_bytes
|| reader.summary.source_digest != profile.spec.virtual_f32_sha256
{
return Err(KarError::Integrity(
"KAR archive/provenance identity mismatch",
));
}
reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?;
let mut parts = Vec::new();
let mut books = Vec::new();
parts
.try_reserve_exact(profile.spec.parts.len())
.map_err(|_| KarError::Allocation)?;
books
.try_reserve_exact(profile.spec.parts.len())
.map_err(|_| KarError::Allocation)?;
for p in &profile.spec.parts {
let index = reader
.sources
.iter()
.position(|s| s.name == p.name)
.ok_or(KarError::Profile("KAR PLE partition missing"))?;
let s = &reader.sources[index];
let record = &reader.directory[index * 192..(index + 1) * 192];
if s.dimensions != [160, p.row_count]
|| s.dtype != 0
|| s.storage_class != 0
|| record[45] != 0
|| u16_at(record, 46) != 32
|| s.planes_min > 2
|| s.planes_max < 2
|| s.digest != p.derived_f32_sha256
|| s.offset != p.derived_f32_offset
{
return Err(KarError::Profile(
"KAR PLE partition/source mapping mismatch",
));
}
let scales = u64_at(record, 64);
let planes = s.planes_offset;
let stride = u64::from(s.plane_stride_bytes);
let book_at = u64_at(record, 80)
.checked_add(4)
.ok_or(KarError::Range("KAR PLE book overflow"))?;
let bytes = read_region(&mut reader.file, book_at, 8).map_err(typed)?;
let book = std::array::from_fn(|i| u16_at(&bytes, i * 2));
if book.iter().any(|b| b & 0x7c00 == 0x7c00) {
return Err(KarError::Profile("KAR PLE nonfinite book"));
}
parts.push(VerifiedPart {
row_base: p.row_base,
row_count: p.row_count,
scales,
planes,
stride,
});
books.push(book);
}
if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes {
return Err(KarError::Integrity("KAR archive length changed"));
}
Ok(Self {
reader,
profile,
parts,
books,
})
}
pub fn archive_sha256(&self) -> &[u8; 32] {
&self.profile.spec.archive_sha256
}
pub fn archive_bytes(&self) -> u64 {
self.profile.spec.archive_bytes
}
/// Digest of the trusted provenance manifest; never the archive/source digest.
pub fn profile_sha256(&self) -> &[u8; 32] {
&self.profile.spec.provenance_sha256
}
pub fn native_shard_sha256(&self) -> &[[u8; 32]; 2] {
&self.profile.spec.native_shard_sha256
}
pub fn row_count(&self) -> u64 {
PLE_ROWS
}
pub fn partition_books(&self) -> &[[u16; 4]] {
&self.books
}
pub fn read_rows(&mut self, rows: &[u64; 16]) -> Result<[KarPleRowPacket; 16], KarError> {
if rows.iter().any(|r| *r >= PLE_ROWS) {
return Err(KarError::Range("KAR PLE row outside table"));
}
if self.reader.file.metadata().map_err(KarError::Io)?.len() != self.archive_bytes() {
return Err(KarError::Integrity("KAR archive length changed"));
}
let mut packets = [KarPleRowPacket {
payload: [0; 50],
partition: 0,
}; 16];
for (row, packet) in rows.iter().zip(&mut packets) {
let index = self
.parts
.partition_point(|p| p.row_base <= *row)
.checked_sub(1)
.ok_or(KarError::Range("KAR PLE partition range"))?;
let p = &self.parts[index];
let local = row - p.row_base;
if local >= p.row_count {
return Err(KarError::Range("KAR PLE local row range"));
}
let scale = p
.scales
.checked_add(
local
.checked_mul(10)
.ok_or(KarError::Range("KAR PLE scale overflow"))?,
)
.ok_or(KarError::Range("KAR PLE scale overflow"))?;
self.reader
.file
.seek(SeekFrom::Start(scale))
.map_err(KarError::Io)?;
self.reader
.file
.read_exact(&mut packet.payload[..10])
.map_err(KarError::Io)?;
for plane in 0..2usize {
let at = p
.planes
.checked_add(
(plane as u64)
.checked_mul(p.stride)
.ok_or(KarError::Range("KAR PLE plane overflow"))?,
)
.and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n)))
.ok_or(KarError::Range("KAR PLE plane overflow"))?;
self.reader
.file
.seek(SeekFrom::Start(at))
.map_err(KarError::Io)?;
self.reader
.file
.read_exact(&mut packet.payload[10 + plane * 20..30 + plane * 20])
.map_err(KarError::Io)?;
}
if packet.payload[..10]
.as_chunks::<2>()
.0
.iter()
.any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00)
{
return Err(KarError::Profile("KAR PLE nonfinite scale"));
}
packet.partition =
u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?;
}
Ok(packets)
}
}
#[path = "kar_nested.rs"]
mod nested;
pub use nested::{KarNestedRecord, NESTING_TOPDOWN};
#[cfg(test)]
#[path = "../tests/kar_ple/mod.rs"]
mod tests;
#[cfg(test)]
#[path = "../tests/kar_crc_slicing.rs"]
mod crc_slicing_tests;