Files
leleka/crates/model-format/tests/kar_ple/mod.rs
T

766 lines
26 KiB
Rust

//! Independent SDET161 KAR2 bytes. These miniature archives never qualify a
//! serving capability, an immutable deployment source, or a physical model.
use super::*;
use std::{
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
};
const NAMES: &[u8] = b"fixture.part0\0fixture.part1\0";
const SCALES: [u16; 5] = [0x3c00, 0x4000, 0x3800, 0xbc00, 0x0001];
const BOOKS: [[u16; 4]; 2] = [
[0xc000, 0xb800, 0x3800, 0x4000],
[0xc400, 0xbc00, 0x3c00, 0x4400],
];
// Literal expected binary32 products, fixed before candidate implementation.
const EXPECTED: [[u32; 4]; 5] = [
[0xc0000000, 0xbf000000, 0x3f000000, 0x40000000],
[0xc0800000, 0xbf800000, 0x3f800000, 0x40800000],
[0xbf800000, 0xbe800000, 0x3e800000, 0x3f800000],
[0x40000000, 0x3f000000, 0xbf000000, 0xc0000000],
[0xb4000000, 0xb3000000, 0x33000000, 0x34000000],
];
fn put16(b: &mut [u8], at: usize, value: u16) {
b[at..at + 2].copy_from_slice(&value.to_le_bytes());
}
fn put32(b: &mut [u8], at: usize, value: u32) {
b[at..at + 4].copy_from_slice(&value.to_le_bytes());
}
fn put64(b: &mut [u8], at: usize, value: u64) {
b[at..at + 8].copy_from_slice(&value.to_le_bytes());
}
fn oracle_crc(bytes: &[u8]) -> u32 {
let mut remainder = 0xffff_ffffu32;
for byte in bytes {
remainder ^= u32::from(*byte);
for _ in 0..8 {
remainder = (remainder >> 1) ^ if remainder & 1 == 0 { 0 } else { 0xedb8_8320 };
}
}
!remainder
}
fn header_crc(b: &mut [u8]) {
put32(b, 192, oracle_crc(&b[..192]));
}
fn directory_digest(b: &mut [u8]) {
let mut hash = Sha256::new();
hash.update(&b[640..640 + NAMES.len()]);
hash.update(&b[256..640]);
b[160..192].copy_from_slice(&hash.finalize());
header_crc(b);
}
fn payload_integrity(b: &mut [u8]) {
put32(b, 256 + 108, oracle_crc(&b[768..1024]));
put32(b, 448 + 108, oracle_crc(&b[1024..1280]));
directory_digest(b);
}
fn tiny_archive() -> Vec<u8> {
let mut b = vec![0u8; 1280];
b[..8].copy_from_slice(b"KARCHIV2");
for (at, v) in [(8, 2), (12, 0x04030201), (16, 256), (20, 192), (32, 2)] {
put32(&mut b, at, v);
}
for (at, v) in [
(24, 256),
(40, 640),
(48, NAMES.len() as u64),
(56, 768),
(64, 1280),
(72, 480),
(80, 1200),
(88, 480),
(120, 320_001_536 * 640),
] {
put64(&mut b, at, v);
}
b[96..104].copy_from_slice(&(1280f64 * 8.0 / 480.0).to_le_bytes());
b[104..107].copy_from_slice(&[1, 2, 1]);
b[128..160].fill(0x11);
b[640..640 + NAMES.len()].copy_from_slice(NAMES);
for (part, record, rows, section, books, planes, stride) in [
(0, 256, 2u64, 768, 800, 816, 48),
(1, 448, 1, 1024, 1040, 1056, 32),
] {
put32(&mut b, record, part as u32 * 14);
put16(&mut b, record + 4, 13);
b[record + 6] = 2;
for (at, v) in [
(8, 160),
(16, rows),
(24, 1),
(32, 1),
(48, rows * 160),
(56, rows * 160),
(64, section),
(72, rows * 10),
(80, books),
(88, 12),
(96, planes),
(112, section),
(120, 256),
(160, part as u64 * 1280),
] {
put64(&mut b, record + at, v);
}
b[record + 42..record + 45].copy_from_slice(&[2, 1, 2]);
put16(&mut b, record + 46, 32);
put32(&mut b, record + 104, stride as u32);
b[record + 128..record + 160].fill(0x22 + part as u8);
put16(&mut b, books as usize, 0xbc00);
put16(&mut b, books as usize + 2, 0x3c00);
for (i, word) in BOOKS[part].iter().enumerate() {
put16(&mut b, books as usize + 4 + i * 2, *word);
}
for row in 0..rows as usize {
for (i, scale) in SCALES.iter().enumerate() {
put16(&mut b, section as usize + row * 10 + i * 2, *scale);
}
for group in 0..5 {
put32(&mut b, planes as usize + row * 20 + group * 4, 0xcccc_cccc);
put32(
&mut b,
planes as usize + stride + row * 20 + group * 4,
0xaaaa_aaaa,
);
}
}
}
payload_integrity(&mut b);
b
}
struct Fixture {
directory: PathBuf,
path: PathBuf,
}
impl Fixture {
fn new(bytes: &[u8]) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let base = std::env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-kar-sdet")
});
let directory = base.join(format!(
"kar-ple-fixture-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&directory).unwrap();
let path = directory.join("synthetic.kar");
std::fs::write(&path, bytes).unwrap();
Self { directory, path }
}
fn inspect(&self) -> KarInspection {
KarInspection::inspect(File::open(&self.path).unwrap()).unwrap()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.directory).unwrap();
}
}
fn f16(bits: u16) -> f32 {
let sign = u32::from(bits & 0x8000) << 16;
let exponent = (bits >> 10) & 31;
let fraction = u32::from(bits & 1023);
if exponent == 0 {
let value = (fraction as f32) * 2f32.powi(-24);
return if sign == 0 { value } else { -value };
}
if exponent == 31 {
return f32::from_bits(sign | 0x7f80_0000 | (fraction << 13));
}
f32::from_bits(sign | ((u32::from(exponent) + 112) << 23) | (fraction << 13))
}
fn scalar(
scales: &[u16],
book: &[u16],
planes: &[&[u32]],
group: u16,
start: usize,
out: &mut [f32],
) -> Result<(), String> {
if group != 32
|| planes.len() != 2
|| book.len() != 4
|| scales.iter().chain(book).any(|w| w & 0x7c00 == 0x7c00)
{
return Err("independent finite L2 oracle domain".into());
}
for (i, value) in out.iter_mut().enumerate() {
let at = start + i;
let low = (planes[1][at / 32] >> (at % 32)) & 1;
let high = (planes[0][at / 32] >> (at % 32)) & 1;
*value = f16(book[(2 * high + low) as usize]) * f16(scales[at / 32]);
}
Ok(())
}
fn unexpected_decoder(
_: &[u16],
_: &[u16],
_: &[&[u32]],
_: u16,
_: usize,
_: &mut [f32],
) -> Result<(), String> {
panic!("invalid range reached scalar decoder")
}
fn profile(bytes: &[u8]) -> KarPleProfileSpec {
KarPleProfileSpec {
archive_bytes: bytes.len() as u64,
archive_sha256: Sha256::digest(bytes).into(),
provenance_sha256: [0x33; 32],
virtual_f32_bytes: 320_001_536 * 640,
virtual_f32_sha256: [0x11; 32],
native_shard_sha256: [[0x44; 32], [0x55; 32]],
parts: vec![KarPlePartProvenance {
name: "fixture.part0".into(),
row_base: 0,
row_count: 320_001_536,
derived_f32_offset: 0,
derived_f32_sha256: [0x22; 32],
}],
}
}
fn refused(bytes: &[u8]) -> String {
let f = Fixture::new(bytes);
match KarInspection::inspect(File::open(&f.path).unwrap()) {
Ok(_) => panic!("malformed bytes admitted"),
Err(e) => e.to_string(),
}
}
#[test]
fn literal_rows_and_partition_books_decode_exactly_in_requested_order() {
assert_eq!(oracle_crc(b"123456789"), 0xcbf4_3926);
let f = Fixture::new(&tiny_archive());
let mut inspected = f.inspect();
inspected.verify_payloads().unwrap();
assert_eq!(inspected.summary().archive_bytes, 1280);
assert_eq!(inspected.tensor_sources()[0].dimensions, [160, 2]);
for part in [1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1] {
let row = inspected
.decode_range(&format!("fixture.part{part}"), 2, 0, 160, scalar)
.unwrap();
let expected: Vec<u32> = (0..160)
.map(|i| {
let bits = EXPECTED[i / 32][i % 4];
if part == 0 {
bits
} else {
(f32::from_bits(bits) * 2.0).to_bits()
}
})
.collect();
assert_eq!(
row.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
expected
);
}
}
#[test]
fn literal_scale_plane_packet_fields_and_cross_group_range_are_preserved() {
fn fields(
s: &[u16],
b: &[u16],
p: &[&[u32]],
g: u16,
start: usize,
o: &mut [f32],
) -> Result<(), String> {
assert_eq!(s, SCALES);
assert_eq!(b, BOOKS[0]);
assert_eq!(p[0], [0xcccc_cccc; 5]);
assert_eq!(p[1], [0xaaaa_aaaa; 5]);
scalar(s, b, p, g, start, o)
}
let f = Fixture::new(&tiny_archive());
let mut reader = f.inspect();
reader
.decode_range("fixture.part0", 2, 0, 160, fields)
.unwrap();
let got = reader
.decode_range("fixture.part0", 2, 31, 3, scalar)
.unwrap();
assert_eq!(
got.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
[0x40000000, 0xc0800000, 0xbf800000]
);
}
#[test]
fn asymmetric_plane_bytes_low_high_bits_and_negative_zero_scale_are_exact() {
let mut b = tiny_archive();
put32(&mut b, 816, 0x8000_0001);
put32(&mut b, 864, 0x0000_8000);
put16(&mut b, 770, 0x8000);
payload_integrity(&mut b);
let fixture = Fixture::new(&b);
let got = fixture
.inspect()
.decode_range("fixture.part0", 2, 0, 64, scalar)
.unwrap();
let mut wanted = [0xc000_0000u32; 64];
wanted[0] = 0x3f00_0000;
wanted[15] = 0xbf00_0000;
wanted[31] = 0x3f00_0000;
for i in 32..64 {
wanted[i] = [0, 0, 0x8000_0000, 0x8000_0000][i % 4];
}
assert_eq!(got.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), wanted);
}
#[test]
fn range_overflow_empty_huge_unknown_and_unstored_level_refuse_before_decoder() {
let f = Fixture::new(&tiny_archive());
let mut r = f.inspect();
for (name, level, start, count) in [
("fixture.part0", 2, usize::MAX, 2),
("fixture.part0", 2, 320, 1),
("fixture.part0", 2, 0, 0),
("fixture.part0", 2, 0, 1_000_001),
("absent", 2, 0, 1),
("fixture.part0", 0, 0, 1),
("fixture.part0", 3, 0, 1),
] {
assert!(
r.decode_range(name, level, start, count, unexpected_decoder)
.is_err()
);
}
}
#[test]
fn retained_descriptor_reads_original_after_path_replacement() {
let original = tiny_archive();
let f = Fixture::new(&original);
let mut r = f.inspect();
std::fs::rename(&f.path, f.directory.join("retained.kar")).unwrap();
std::fs::write(&f.path, b"different object").unwrap();
r.verify_payloads().unwrap();
let got = r.decode_range("fixture.part0", 2, 0, 4, scalar).unwrap();
assert_eq!(
got.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
EXPECTED[0]
);
// This proves same-descriptor reads, not protection against same-inode writes.
}
#[test]
fn inspect_is_not_payload_verification() {
let mut bytes = tiny_archive();
bytes[816] ^= 1;
let f = Fixture::new(&bytes);
let mut r = f.inspect();
assert!(matches!(r.verify_payloads(), Err(KarError::Integrity(_))));
}
#[test]
fn malformed_header_directory_names_and_checked_offsets_refuse() {
let base = tiny_archive();
let mut b = base.clone();
put32(&mut b, 8, 3);
header_crc(&mut b);
assert!(refused(&b).contains("version"));
let mut b = base.clone();
b[120] ^= 1;
assert!(refused(&b).contains("header CRC"));
let mut b = base.clone();
b[640] ^= 1;
assert!(refused(&b).contains("directory digest"));
let mut b = base.clone();
put64(&mut b, 24, u64::MAX - 127);
header_crc(&mut b);
assert!(refused(&b).contains("overflow"));
let mut b = base.clone();
put32(&mut b, 448, 0);
directory_digest(&mut b);
assert!(refused(&b).contains("duplicate"));
let mut b = base.clone();
put16(&mut b, 256 + 4, 100);
directory_digest(&mut b);
assert!(refused(&b).contains("name bounds"));
let mut b = base.clone();
put64(&mut b, 256 + 96, u64::MAX);
directory_digest(&mut b);
assert!(refused(&b).contains("layout"));
let mut b = base;
put64(&mut b, 256 + 8, u64::MAX);
directory_digest(&mut b);
assert!(refused(&b).contains("shape overflow"));
}
#[test]
fn selected_nonfinite_scale_and_any_book_entry_refuse_scalar_publication() {
for at in [768, 804, 810] {
for word in [0x7c00, 0xfc00, 0x7e01] {
let mut b = tiny_archive();
put16(&mut b, at, word);
payload_integrity(&mut b);
let f = Fixture::new(&b);
let mut r = f.inspect();
r.verify_payloads().unwrap();
assert!(r.decode_range("fixture.part0", 2, 0, 160, scalar).is_err());
}
}
}
#[test]
fn genuine_profile_bounds_reject_zero_identity_gaps_overflow_and_wrong_extent() {
let b = tiny_archive();
let mut p = profile(&b);
p.archive_sha256 = [0; 32];
assert!(KarPleProfile::new(p).is_err());
let mut p = profile(&b);
p.provenance_sha256 = [0; 32];
assert!(KarPleProfile::new(p).is_err());
let mut p = profile(&b);
p.native_shard_sha256[1] = [0; 32];
assert!(KarPleProfile::new(p).is_err());
let mut p = profile(&b);
p.parts[0].row_base = 1;
assert!(KarPleProfile::new(p).is_err());
let mut p = profile(&b);
p.parts[0].row_count = 320_001_535;
assert!(KarPleProfile::new(p).is_err());
let mut p = profile(&b);
p.parts[0].derived_f32_offset = u64::MAX;
assert!(KarPleProfile::new(p).is_err());
let p = KarPleProfile::new(profile(&b)).unwrap();
assert_eq!(p.native_shard_sha256(), &[[0x44; 32], [0x55; 32]]);
}
#[test]
fn verifier_rejects_full_archive_digest_virtual_provenance_and_tiny_mapping() {
let b = tiny_archive();
let f = Fixture::new(&b);
let mut p = profile(&b);
p.archive_sha256 = [0x66; 32];
let error = VerifiedKarPleArtifact::verify(
f.inspect().into_owner_controlled(),
KarPleProfile::new(p).unwrap(),
)
.err()
.unwrap();
assert!(error.to_string().contains("full archive SHA"));
let mut p = profile(&b);
p.virtual_f32_sha256 = [0x77; 32];
let error = VerifiedKarPleArtifact::verify(
f.inspect().into_owner_controlled(),
KarPleProfile::new(p).unwrap(),
)
.err()
.unwrap();
assert!(error.to_string().contains("provenance identity"));
let error = VerifiedKarPleArtifact::verify(
f.inspect().into_owner_controlled(),
KarPleProfile::new(profile(&b)).unwrap(),
)
.err()
.unwrap();
assert!(error.to_string().contains("partition/source mapping"));
// Full serving geometry deliberately remains impossible for this tiny file.
}
#[test]
fn serving_verifier_refuses_nonfinite_partition_book_before_later_mapping() {
let mut bytes = tiny_archive();
put16(&mut bytes, 804, 0x7e01);
payload_integrity(&mut bytes);
let fixture = Fixture::new(&bytes);
let mut spec = profile(&bytes);
spec.parts[0].row_count = 2;
spec.parts.push(KarPlePartProvenance {
name: "fixture.part1".into(),
row_base: 2,
row_count: 320_001_534,
derived_f32_offset: 1280,
derived_f32_sha256: [0x23; 32],
});
let result = VerifiedKarPleArtifact::verify(
fixture.inspect().into_owner_controlled(),
KarPleProfile::new(spec).unwrap(),
);
assert!(result.err().unwrap().to_string().contains("nonfinite book"));
// There is still no successful tiny serving verification or fake capability.
}
#[test]
fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() {
fn bit_step(mut crc: u32, bytes: &[u8]) -> u32 {
for &byte in bytes {
crc ^= u32::from(byte);
for _ in 0..8 {
crc = (crc >> 1) ^ if crc & 1 == 0 { 0 } else { 0xedb8_8320 };
}
}
crc
}
struct Counted<'a> {
bytes: &'a [u8],
read: usize,
eof: usize,
}
impl Read for Counted<'_> {
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
let n = out.len().min(self.bytes.len());
out[..n].copy_from_slice(&self.bytes[..n]);
self.bytes = &self.bytes[n..];
self.read += n;
self.eof += usize::from(n == 0);
Ok(n)
}
}
let mut domain: Vec<u8> = (0..=255).collect();
domain.extend((0..4097).map(|i| ((i * 29 + i / 7) & 255) as u8));
assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
assert_eq!(crc32(&[]), 0);
for initial in [0, !0, 0x1234_5678, 0x8000_0001] {
for chunk in [1, 7, 256, 1025] {
let folded = domain.chunks(chunk).fold(initial, crc32_step);
assert_eq!(folded, bit_step(initial, &domain));
}
}
let bytes = tiny_archive();
let fixture = Fixture::new(&bytes);
let mut inspection = fixture.inspect();
let pin: [u8; 32] = Sha256::digest(&bytes).into();
for chunk in [1, 17, 255, 257, 1025, 2048] {
let mut input = Counted {
bytes: &bytes,
read: 0,
eof: 0,
};
verify_integrity_stream(
&mut input,
&inspection.sections,
bytes.len() as u64,
&pin,
&mut vec![0; chunk],
)
.unwrap();
assert_eq!(input.read, bytes.len()); // No separate payload reread.
assert_eq!(input.eof, 1);
}
inspection
.verify_integrity(bytes.len() as u64, &pin)
.unwrap();
let row = inspection
.decode_range("fixture.part0", 2, 0, 160, scalar)
.unwrap();
for (i, value) in row.iter().enumerate() {
assert_eq!(value.to_bits(), EXPECTED[i / 32][i % 4]);
}
// Metadata/padding and both payload sections remain covered by the SHA.
for at in [700, 800, 1100] {
let mut changed = bytes.clone();
changed[at] ^= 1;
let error = verify_integrity_stream(
&mut &changed[..],
&inspection.sections,
bytes.len() as u64,
&pin,
&mut [0; 257],
)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR full archive SHA-256 mismatch")
));
}
// An admitted header can contain a wrong stored CRC while its whole-file
// SHA is correct. Preserve CRC failure, including after the first section.
let mut bad_crc = bytes.clone();
put32(&mut bad_crc, 448 + 108, 0);
directory_digest(&mut bad_crc);
let bad_fixture = Fixture::new(&bad_crc);
let bad_inspection = bad_fixture.inspect();
let bad_pin: [u8; 32] = Sha256::digest(&bad_crc).into();
let error = verify_integrity_stream(
&mut &bad_crc[..],
&bad_inspection.sections,
bad_crc.len() as u64,
&bad_pin,
&mut [0; 1025],
)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR payload CRC-32 mismatch")
));
let error = verify_integrity_stream(
&mut &bad_crc[..],
&bad_inspection.sections,
bad_crc.len() as u64,
&pin,
&mut [0; 257],
)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR full archive SHA-256 mismatch")
));
for length in [bytes.len() - 1, bytes.len() + 1] {
let mut altered = bytes.clone();
altered.resize(length, 0);
let error = verify_integrity_stream(
&mut &altered[..],
&inspection.sections,
bytes.len() as u64,
&pin,
&mut [0; 257],
)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR full archive SHA-256 mismatch")
));
}
// The file-backed (read-ahead) scan agrees with the stream scan on every verdict: a changed payload byte
// is a SHA mismatch even though the section CRC fails too, and a longer or shorter file is refused.
for at in [800usize, 1100] {
let mut changed = bytes.clone();
changed[at] ^= 1;
let changed_fixture = Fixture::new(&changed);
let mut changed_inspection = changed_fixture.inspect();
let error = changed_inspection
.verify_integrity(bytes.len() as u64, &pin)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR full archive SHA-256 mismatch")
));
}
let mut short_inspection = Fixture::new(&bytes).inspect();
let error = short_inspection
.verify_integrity(bytes.len() as u64 + 1, &pin)
.unwrap_err();
assert!(
matches!(error, KarError::Io(_) | KarError::Range(_)),
"{error:?}"
);
let mut bad_crc_inspection = bad_fixture.inspect();
let error = bad_crc_inspection
.verify_integrity(bad_crc.len() as u64, &bad_pin)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR payload CRC-32 mismatch")
));
// The public verifier still goes through the combined scan before mapping;
// no successful serving capability can be minted from this miniature file.
let error = VerifiedKarPleArtifact::verify(
bad_inspection.into_owner_controlled(),
KarPleProfile::new(profile(&bad_crc)).unwrap(),
)
.err()
.unwrap();
assert!(matches!(
error,
KarError::Integrity("KAR payload CRC-32 mismatch")
));
}
/// Directory/header fuzz with the digest and CRC recomputed, so the mutation
/// reaches the structural validators instead of the integrity checks. Whatever
/// the inspector admits must be fully consistent for the GPU path: the nested
/// descriptor validator agrees, every planned byte range stays inside the
/// record's own section, staging succeeds and the kernel model never panics or
/// reports anything but a clean/non-finite status. Level-2 windows must also
/// equal the file-backed CPU oracle bit for bit.
#[test]
fn recomputed_integrity_fuzz_admits_only_gpu_consistent_records() {
use crate::kar_kernel_model::{kernel_decode, plan_window};
use crate::kar_levels::stage_window;
let base = tiny_archive();
let mut seed = 0x0bad_c0de_dead_beefu64;
let mut next = move || {
seed ^= seed >> 12;
seed ^= seed << 25;
seed ^= seed >> 27;
seed.wrapping_mul(0x2545_f491_4f6c_dd1d)
};
let directory = std::env::temp_dir().join(format!("kar-fuzz-{}", std::process::id()));
std::fs::create_dir_all(&directory).unwrap();
let path = directory.join("fuzz.kar");
let (mut admitted, mut windows) = (0usize, 0usize);
// Every header field byte and every directory byte, several values each.
let positions: Vec<usize> = (24..160).chain(256..640).collect();
for &at in &positions {
for round in 0..10 {
let mut b = base.clone();
let old = b[at];
b[at] = match round {
0 => old ^ 1,
1 => old.wrapping_add(1),
2 => old.wrapping_sub(1),
3 => 0,
4 => 0xff,
5 => old ^ 0x80,
_ => next() as u8,
};
if b[at] == old {
continue;
}
directory_digest(&mut b);
std::fs::write(&path, &b).unwrap();
let Ok(inspection) = KarInspection::inspect(File::open(&path).unwrap()) else {
continue;
};
admitted += 1;
let records = inspection
.nested_records()
.unwrap_or_else(|e| panic!("inspector admitted what the descriptor rejects: byte {at} -> {e}"));
for record in &records {
let section_end = record.section_offset + record.section_bytes;
for _ in 0..24 {
let level = 2 + (next() % 4) as u8;
let start = next() % record.n_elements;
let count = 1 + next() % (record.n_elements - start).min(400);
let Ok(plan) = plan_window(record, level, start, count) else {
continue;
};
for range in plan.ranges() {
assert!(
range.archive_offset >= record.section_offset
&& range.archive_offset + range.len <= section_end
&& section_end <= b.len() as u64,
"byte {at}: range {range:?} escapes section"
);
}
let packet = stage_window(&inspection, &plan).unwrap();
let mut out = vec![0f32; count as usize];
let status = kernel_decode(&plan.params, &packet, &mut out);
assert!(status == 0 || status == 2, "byte {at}: status {status}");
if status == 0 && level == 2 && record.group == 32 && record.planes_stored == 2
{
let want = inspection
.clone_decode_for_fuzz(&record.name, 2, start as usize, count as usize);
if let Some(want) = want {
assert_eq!(
out.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
want.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
"byte {at} window {start}+{count}"
);
}
}
windows += 1;
}
}
}
}
std::fs::remove_dir_all(&directory).unwrap();
assert!(admitted > 100 && windows > 100, "{admitted} {windows}");
}
impl KarInspection {
/// Fuzz helper: the file-backed CPU oracle with the test's L2 decoder, or
/// `None` when that decoder's finite-domain refuses the window.
fn clone_decode_for_fuzz(
&self,
name: &str,
level: u8,
start: usize,
count: usize,
) -> Option<Vec<f32>> {
let index = self.sources.iter().position(|s| s.name == name)?;
let record: [u8; RECORD_BYTES] = self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES]
.try_into()
.ok()?;
let mut file = self.file.try_clone().ok()?;
decode_record_range(&mut file, &record, level, start, count, scalar).ok()
}
}