test(model-format): cover production split admission precedence

This commit is contained in:
Pavlo Ratushnyi
2026-10-09 14:41:10 +02:00
parent f92cdfdc38
commit dfe8781dfe
2 changed files with 174 additions and 1 deletions
@@ -3,6 +3,8 @@ use crate::gguf::{Summary, TensorIndex, TensorInfo, VerifiedGgufFile};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
fs::OpenOptions,
io::{Seek, SeekFrom, Write},
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
};
@@ -289,6 +291,13 @@ pub struct TinyOwner {
pub tensors: Vec<TensorInfo>,
pub payloads: Vec<Vec<u8>>,
pub bytes: Vec<u8>,
metadata_locations: BTreeMap<String, MetadataLocation>,
}
#[derive(Clone, Copy)]
struct MetadataLocation {
key: usize,
value: usize,
kind: u32,
}
fn string(bytes: &mut Vec<u8>, value: &str) {
bytes.extend((value.len() as u64).to_le_bytes());
@@ -301,7 +310,10 @@ impl TinyOwner {
mut metadata: BTreeMap<String, Meta>,
) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let directory = std::env::temp_dir().join(format!(
let fixture_root =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/stra157-sdet/fixtures");
std::fs::create_dir_all(&fixture_root).unwrap();
let directory = fixture_root.join(format!(
"leleka-sdet143-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
@@ -315,8 +327,11 @@ impl TinyOwner {
bytes.extend(3u32.to_le_bytes());
bytes.extend((rows.len() as u64).to_le_bytes());
bytes.extend((metadata.len() as u64).to_le_bytes());
let mut metadata_locations = BTreeMap::new();
for (key, value) in metadata {
let key_offset = bytes.len() + 8;
string(&mut bytes, &key);
let kind_offset = bytes.len();
match value {
Meta::U16(v) => {
bytes.extend(2u32.to_le_bytes());
@@ -355,6 +370,15 @@ impl TinyOwner {
}
}
}
let kind = u32::from_le_bytes(bytes[kind_offset..kind_offset + 4].try_into().unwrap());
metadata_locations.insert(
key,
MetadataLocation {
key: key_offset,
value: kind_offset + 4,
kind,
},
);
}
let mut tensors = Vec::new();
let mut payloads = Vec::new();
@@ -396,8 +420,41 @@ impl TinyOwner {
tensors,
payloads,
bytes,
metadata_locations,
}
}
/// Mutate only a metadata key's bytes after VerifiedGgufFile::open.
/// This is deliberate same-size test fault injection, not an immutability
/// guarantee for production files.
pub fn replace_metadata_key_after_open(&self, key: &str, replacement: &str) {
assert_eq!(key.len(), replacement.len());
let location = self.metadata_locations.get(key).unwrap();
self.write_same_size(location.key, replacement.as_bytes());
}
pub fn set_metadata_u16_after_open(&self, key: &str, value: u16) {
let location = self.metadata_locations.get(key).unwrap();
assert_eq!(location.kind, 2);
self.write_same_size(location.value, &value.to_le_bytes());
}
pub fn set_metadata_i32_after_open(&self, key: &str, value: i32) {
let location = self.metadata_locations.get(key).unwrap();
assert_eq!(location.kind, 5);
self.write_same_size(location.value, &value.to_le_bytes());
}
fn write_same_size(&self, offset: usize, bytes: &[u8]) {
let before = std::fs::metadata(&self.path).unwrap().len();
let mut file = OpenOptions::new().write(true).open(&self.path).unwrap();
file.seek(SeekFrom::Start(offset as u64)).unwrap();
file.write_all(bytes).unwrap();
file.flush().unwrap();
drop(file);
assert_eq!(std::fs::metadata(&self.path).unwrap().len(), before);
}
pub fn open(&self) -> VerifiedGgufFile {
let digest = Sha256::digest(&self.bytes);
let hex = digest
@@ -546,6 +546,122 @@ fn actual_public_bind_rejects_minis_at_identity_before_split_or_metadata() {
assert_eq!(error.to_string(), "artifact identity rejected for shard 0");
}
fn split_probe_owner(shard: u64, tensor_count: usize, placeholder_key: bool) -> TinyOwner {
let rows = (0..tensor_count)
.map(|number| (format!("fixture.tensor.{number}"), 0, vec![1]))
.collect::<Vec<_>>();
let mut metadata = BTreeMap::from([(
"general.architecture".to_owned(),
Meta::Text("not-qwen4exp".to_owned()),
)]);
if placeholder_key {
// Same byte length as split.no; changed to that key only after open.
metadata.insert("zzzzzzzz".to_owned(), Meta::U16(7));
}
TinyOwner::new(shard, &rows, metadata)
}
fn bind_after_identity_error(owners: [VerifiedGgufFile; 2]) -> BindingError {
match Qwen4ExpArtifact::bind_after_identity(owners) {
Ok(_) => panic!("unexpectedly admitted split-probe owners"),
Err(error) => error,
}
}
#[test]
fn sec_uc143_production_orchestrator_rejects_fresh_split_faults_before_profile() {
// The opened index is valid first. Same-size in-place edits are controlled
// fixture fault injection so split_snapshot observes data different from
// the retained index summary; this is not an immutability guarantee.
for shard in 0..2 {
for (field, expected_error) in [
("split.no", "split.no"),
("split.count", "split.count"),
("split.tensors.count", "split.tensors.count"),
] {
for missing in [false, true] {
let first = split_probe_owner(0, 1223, false);
let second = split_probe_owner(1, 1, false);
let owners = [first.open(), second.open()];
let fixtures = [&first, &second];
let before = std::fs::metadata(&fixtures[shard].path).unwrap().len();
if missing {
fixtures[shard]
.replace_metadata_key_after_open(field, &"x".repeat(field.len()));
} else {
match field {
"split.no" => {
fixtures[shard].set_metadata_u16_after_open(field, (1 - shard) as u16)
}
"split.count" => fixtures[shard].set_metadata_u16_after_open(field, 3),
"split.tensors.count" => {
fixtures[shard].set_metadata_i32_after_open(field, 1225)
}
_ => unreachable!(),
}
}
assert_eq!(
std::fs::metadata(&fixtures[shard].path).unwrap().len(),
before
);
// The open-time index still reports the original valid split.
assert_eq!(owners[shard].index().summary.split_no, Some(shard as u64));
let error = bind_after_identity_error(owners);
assert!(
matches!(error, BindingError::Split(actual) if actual == expected_error),
"shard {shard}, field {field}, missing={missing}: {error}"
);
}
}
}
}
#[test]
fn sec_uc143_production_orchestrator_preserves_index_precedence_and_valid_continuation() {
// A later fresh-metadata defect must not mask the earlier indexed count
// gate, on either shard.
for (counts, invalid_shard) in [((1222, 1), 0usize), ((1223, 2), 1usize)] {
let first = split_probe_owner(0, counts.0, false);
let second = split_probe_owner(1, counts.1, false);
let owners = [first.open(), second.open()];
let fixtures = [&first, &second];
fixtures[invalid_shard].set_metadata_u16_after_open("split.count", 3);
let error = bind_after_identity_error(owners);
assert!(matches!(error, BindingError::Split("indexed_tensor_count")));
}
// Valid fresh split metadata proceeds past split admission to the selected
// later profile failure, rather than being rejected by the split phase.
let first = split_probe_owner(0, 1223, false);
let second = split_probe_owner(1, 1, false);
let error = bind_after_identity_error([first.open(), second.open()]);
assert!(matches!(
error,
BindingError::Metadata("general.architecture")
));
}
#[test]
fn sec_uc143_production_orchestrator_rejects_duplicate_split_key_after_open() {
let first = split_probe_owner(0, 1223, true);
let second = split_probe_owner(1, 1, false);
let owners = [first.open(), second.open()];
let before = std::fs::metadata(&first.path).unwrap().len();
first.replace_metadata_key_after_open("zzzzzzzz", "split.no");
assert_eq!(std::fs::metadata(&first.path).unwrap().len(), before);
let error = bind_after_identity_error(owners);
assert_eq!(error.to_string(), "GGUF stream I/O failed");
match error {
BindingError::Io(source) => assert!(
source
.to_string()
.contains("duplicate GGUF metadata key: split.no")
),
_ => panic!("duplicate split key did not fail in the parser stage"),
}
}
#[test]
fn sec_uc143_both_replaced_paths_preserve_owned_metadata_and_rank2_rank3_ple_bytes() {
// [SEC][UC-143] reopen/substitution attack on BOTH original filenames.