From 276f662d564c1580455d29bf792bdbf4fcf33647 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 20:07:12 +0200 Subject: [PATCH 01/58] STRA-104: add standalone GGUF tokenizer reader --- README.md | 15 +- control-plane/src/gguf.rs | 130 +------ crates/tokenizer/src/lib.rs | 661 +++++++++++++++++++++++++++++++++++- docs/model-assets.md | 9 + 4 files changed, 680 insertions(+), 135 deletions(-) diff --git a/README.md b/README.md index 3e107e42..b0e3269b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,8 @@ performance gain is claimed for Leleka until its real-model gates pass. - `crates/backend-api/` — Leleka's versioned Rust backend contract. - `crates/tokenizer/` — the Qwen35 byte-level BPE tokenizer extracted as a - backend-independent Rust crate. + backend-independent Rust crate, including a bounded GGUF v3 reader for its + tokenizer metadata. - `desktop/`, `desktop-core/` — current desktop application and its Rust core. - `control-plane/` — current Rust API, Responses handling, and worker supervisor. - `engine/strata/` — pinned upstream Strata reference; retained during migration. @@ -34,11 +35,13 @@ artifacts remain outside Git or under ignored paths. Leleka currently has a versioned backend contract and a standalone Qwen35 BPE tokenizer crate. The existing Rust control plane now consumes that shared -tokenizer crate instead of maintaining a second copy; its oracle-parity tests -remain in the workspace. Leleka still has no independent inference backend or -CUDA integration, so this does not yet serve a model independently. The -desktop app and the rest of the control plane remain available as migration -source in this repository. +tokenizer crate for both encoding and GGUF tokenizer metadata rather than +maintaining a second parser; its oracle-parity and malformed-header tests remain +in the workspace. The GGUF reader only supports the current Qwen35 GPT-2 BPE +metadata shape and does not inspect tensor payloads. Leleka still has no +independent inference backend or CUDA integration, so this does not yet serve a +model independently. The desktop app and the rest of the control plane remain +available as migration source in this repository. ## Development diff --git a/control-plane/src/gguf.rs b/control-plane/src/gguf.rs index ec052e4b..7664719e 100644 --- a/control-plane/src/gguf.rs +++ b/control-plane/src/gguf.rs @@ -41,16 +41,7 @@ pub struct TensorIndex { pub tensors: Vec, } -#[derive(Debug)] -pub struct TokenizerMetadata { - pub model: String, - pub pre: String, - pub tokens: Vec, - pub merges: Vec, - pub token_types: Option>, - pub special_ids: BTreeMap, - pub chat_template: String, -} +pub use leleka_tokenizer::GgufTokenizerMetadata as TokenizerMetadata; /// Metadata admission for the specialised engine, before expensive preparation. /// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. @@ -109,86 +100,10 @@ pub fn check_flash_next_profile(path: &Path) -> Result<()> { Ok(()) } -/// Read only tokenizer fields after the complete GGUF header has passed inspection. +/// Read tokenizer fields after complete model-header inspection, using the shared Leleka parser. pub fn tokenizer_metadata(path: &Path) -> Result { inspect(path)?; - let file = File::open(path)?; - let size = file.metadata()?.len(); - let mut cursor = Cursor { file, size }; - cursor.skip(16)?; // magic, version, tensor count - let count = cursor.u64()?; - let mut model = None; - let mut pre = None; - let mut tokens = None; - let mut merges = None; - let mut token_types = None; - let mut special_ids = BTreeMap::new(); - let mut chat_template = None; - for _ in 0..count { - let key = cursor.string()?; - let kind = cursor.u32()?; - match key.as_str() { - "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), - "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), - "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), - "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), - "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), - _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { - special_ids.insert(key, cursor.integer(kind)?); - } - _ => cursor.skip_value(kind)?, - } - } - let model = model.ok_or("GGUF is missing tokenizer.ggml.model")?; - let tokens = tokens.ok_or("GGUF is missing tokenizer.ggml.tokens")?; - let merges = merges.ok_or("GGUF is missing tokenizer.ggml.merges")?; - let chat_template = chat_template.ok_or("GGUF is missing tokenizer.chat_template")?; - if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { - return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); - } - if tokens.is_empty() || chat_template.is_empty() { - return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); - } - if token_types - .as_ref() - .is_some_and(|types| types.len() != tokens.len()) - { - return Err("token_type length differs from vocabulary length".into()); - } - let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); - if vocab.len() != tokens.len() { - return Err("GGUF tokenizer has duplicate vocabulary entries".into()); - } - let mut seen_merges = HashSet::new(); - for merge in &merges { - let Some((left, right)) = merge.split_once(' ') else { - return Err("GGUF BPE merge is not a pair".into()); - }; - if left.is_empty() - || right.is_empty() - || right.contains(' ') - || !vocab.contains(left) - || !vocab.contains(right) - || !seen_merges.insert(merge) - { - return Err("GGUF BPE merge is invalid or duplicated".into()); - } - } - for &id in special_ids.values() { - if id as usize >= tokens.len() { - return Err("special token ID exceeds vocabulary".into()); - } - } - Ok(TokenizerMetadata { - model, - pre: pre.unwrap_or_else(|| "qwen35".to_owned()), - tokens, - merges, - token_types, - special_ids, - chat_template, - }) + Ok(leleka_tokenizer::read_gguf_tokenizer_metadata(path)?) } pub fn inspect(path: &Path) -> Result { @@ -495,45 +410,6 @@ impl Cursor { Ok(String::from_utf8(self.take(size as usize)?)?) } - fn string_array(&mut self, kind: u32) -> Result> { - if kind != 9 || self.u32()? != 8 { - return Err("expected a GGUF string array".into()); - } - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } - let mut total = 0u64; - let mut values = Vec::with_capacity(count as usize); - for _ in 0..count { - let value = self.string()?; - total = total - .checked_add(value.len() as u64) - .ok_or("GGUF tokenizer array size overflow")?; - if total > 512 * 1024 * 1024 { - return Err("GGUF tokenizer array exceeds 512 MiB".into()); - } - values.push(value); - } - Ok(values) - } - - fn integer_array(&mut self, kind: u32) -> Result> { - if kind != 9 { - return Err("expected a GGUF integer array".into()); - } - let element = self.u32()?; - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } - let mut values = Vec::with_capacity(count as usize); - for _ in 0..count { - values.push(self.integer(element)?); - } - Ok(values) - } - fn integer(&mut self, kind: u32) -> Result { match kind { 0 | 7 => Ok(u32::from(self.u8()?)), diff --git a/crates/tokenizer/src/lib.rs b/crates/tokenizer/src/lib.rs index 2f7ff08c..89abe67b 100644 --- a/crates/tokenizer/src/lib.rs +++ b/crates/tokenizer/src/lib.rs @@ -2,9 +2,10 @@ use std::{ cmp::Reverse, - collections::{BinaryHeap, HashMap}, + collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, error::Error, - fs, + fs::{self, File}, + io::{Read, Seek, SeekFrom}, path::Path, }; @@ -303,6 +304,391 @@ impl Tokenizer { } } +/// The Qwen35 tokenizer fields read from a GGUF v3 metadata header. +#[derive(Debug, PartialEq, Eq)] +pub struct GgufTokenizerMetadata { + pub model: String, + pub pre: String, + pub tokens: Vec, + pub merges: Vec, + pub token_types: Option>, + pub special_ids: BTreeMap, + pub chat_template: String, +} + +/// A bounded GGUF tokenizer metadata parsing error. +#[derive(Debug)] +pub struct GgufTokenizerError(String); + +impl std::fmt::Display for GgufTokenizerError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +impl Error for GgufTokenizerError {} + +type GgufResult = std::result::Result; + +const MAX_GGUF_HEADER_BYTES: u64 = 1024 * 1024 * 1024; +const MAX_GGUF_METADATA_ENTRIES: u64 = 1_000_000; +const MAX_GGUF_STRING_BYTES: u64 = 1024 * 1024; +const MAX_TOKENIZER_ARRAY_ITEMS: u64 = 1_000_000; +const MAX_TOKENIZER_ARRAY_BYTES: u64 = 512 * 1024 * 1024; +const MAX_RELEVANT_TOKENIZER_FIELDS: usize = 128; + +/// Read Qwen35 GPT-2 BPE tokenizer metadata from a GGUF v3 file. +/// +/// This reads at most the first 1 GiB of the file as a metadata header, caps +/// each header string at 1 MiB, and caps tokenizer string arrays at 1,000,000 +/// elements and 512 MiB of aggregate string bytes. It never reads tensor +/// payloads. Callers that also require model/tensor validation must perform +/// that separately before using these tokenizer assets. +pub fn read_gguf_tokenizer_metadata(path: &Path) -> GgufResult { + let mut cursor = GgufCursor::open(path)?; + if cursor.take(4)? != b"GGUF" { + return Err(gguf_error("not a GGUF file")); + } + if cursor.u32()? != 3 { + return Err(gguf_error("only GGUF v3 is supported")); + } + cursor.skip(8)?; // tensor count; tensor inspection belongs to the model loader. + let count = cursor.u64()?; + if count > MAX_GGUF_METADATA_ENTRIES { + return Err(gguf_error("unreasonable GGUF metadata entry count")); + } + let minimum_bytes = count + .checked_mul(13) + .ok_or_else(|| gguf_error("GGUF metadata entry count overflow"))?; + if minimum_bytes > cursor.remaining()? { + return Err(gguf_error("GGUF metadata count exceeds bounded header")); + } + + let mut model = None; + let mut pre = None; + let mut tokens = None; + let mut merges = None; + let mut token_types = None; + let mut special_ids = BTreeMap::new(); + let mut chat_template = None; + let mut seen_fields = HashSet::new(); + for _ in 0..count { + let key = cursor.string()?; + let kind = cursor.u32()?; + let relevant = matches!( + key.as_str(), + "tokenizer.ggml.model" + | "tokenizer.ggml.pre" + | "tokenizer.ggml.tokens" + | "tokenizer.ggml.merges" + | "tokenizer.ggml.token_type" + | "tokenizer.chat_template" + ) || (key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id")); + if relevant { + if seen_fields.len() >= MAX_RELEVANT_TOKENIZER_FIELDS { + return Err(gguf_error("too many tokenizer metadata fields")); + } + if !seen_fields.insert(key.clone()) { + return Err(gguf_error("duplicate tokenizer metadata field")); + } + } + match key.as_str() { + "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), + "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), + "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), + "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), + _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { + special_ids.insert(key, cursor.integer(kind)?); + } + _ => cursor.skip_value(kind)?, + } + } + + let model = model.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?; + let tokens = tokens.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?; + let merges = merges.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?; + let chat_template = + chat_template.ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?; + if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { + return Err(gguf_error( + "only the qwen35 byte-level BPE tokenizer is supported", + )); + } + if tokens.is_empty() || chat_template.is_empty() { + return Err(gguf_error( + "GGUF tokenizer has an empty vocabulary or chat template", + )); + } + if token_types + .as_ref() + .is_some_and(|types| types.len() != tokens.len()) + { + return Err(gguf_error( + "token_type length differs from vocabulary length", + )); + } + let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); + if vocab.len() != tokens.len() { + return Err(gguf_error( + "GGUF tokenizer has duplicate vocabulary entries", + )); + } + let mut seen_merges = HashSet::new(); + for merge in &merges { + let Some((left, right)) = merge.split_once(' ') else { + return Err(gguf_error("GGUF BPE merge is not a pair")); + }; + if left.is_empty() + || right.is_empty() + || right.contains(' ') + || !vocab.contains(left) + || !vocab.contains(right) + || !seen_merges.insert(merge) + { + return Err(gguf_error("GGUF BPE merge is invalid or duplicated")); + } + } + for &id in special_ids.values() { + if id as usize >= tokens.len() { + return Err(gguf_error("special token ID exceeds vocabulary")); + } + } + Ok(GgufTokenizerMetadata { + model, + pre: pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types, + special_ids, + chat_template, + }) +} + +fn gguf_error(message: impl Into) -> GgufTokenizerError { + GgufTokenizerError(message.into()) +} + +struct GgufCursor { + file: File, + size: u64, +} + +impl GgufCursor { + fn open(path: &Path) -> GgufResult { + let file = File::open(path).map_err(|error| gguf_error(error.to_string()))?; + let size = file + .metadata() + .map_err(|error| gguf_error(error.to_string()))? + .len() + .min(MAX_GGUF_HEADER_BYTES); + Ok(Self { file, size }) + } + + fn position(&mut self) -> GgufResult { + self.file + .stream_position() + .map_err(|error| gguf_error(error.to_string())) + } + + fn remaining(&mut self) -> GgufResult { + Ok(self.size.saturating_sub(self.position()?)) + } + + fn skip(&mut self, bytes: u64) -> GgufResult<()> { + let end = self + .position()? + .checked_add(bytes) + .ok_or_else(|| gguf_error("GGUF offset overflow"))?; + if end > self.size { + return Err(gguf_error("truncated or oversized GGUF metadata header")); + } + self.file + .seek(SeekFrom::Start(end)) + .map_err(|error| gguf_error(error.to_string()))?; + Ok(()) + } + + fn take(&mut self, size: usize) -> GgufResult> { + if self + .position()? + .checked_add(size as u64) + .is_none_or(|end| end > self.size) + { + return Err(gguf_error("truncated or oversized GGUF metadata header")); + } + let mut data = vec![0; size]; + self.file + .read_exact(&mut data) + .map_err(|error| gguf_error(error.to_string()))?; + Ok(data) + } + + fn u8(&mut self) -> GgufResult { + Ok(self.take(1)?[0]) + } + + fn u16(&mut self) -> GgufResult { + let bytes = self.take(2)?; + Ok(u16::from_le_bytes([bytes[0], bytes[1]])) + } + + fn u32(&mut self) -> GgufResult { + let bytes = self.take(4)?; + Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + fn u64(&mut self) -> GgufResult { + let bytes = self.take(8)?; + Ok(u64::from_le_bytes([ + bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], + ])) + } + + fn string(&mut self) -> GgufResult { + let size = self.u64()?; + if size > MAX_GGUF_STRING_BYTES { + return Err(gguf_error("GGUF header string is too large")); + } + String::from_utf8(self.take(size as usize)?) + .map_err(|error| gguf_error(format!("GGUF header string is not UTF-8: {error}"))) + } + + fn string_array(&mut self, kind: u32) -> GgufResult> { + if kind != 9 || self.u32()? != 8 { + return Err(gguf_error("expected a GGUF string array")); + } + let count = self.u64()?; + self.check_tokenizer_array(count, 8)?; + let capacity = usize::try_from(count) + .map_err(|_| gguf_error("GGUF tokenizer array count exceeds platform limits"))?; + let mut total = 0u64; + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + let value = self.string()?; + total = total + .checked_add(value.len() as u64) + .ok_or_else(|| gguf_error("GGUF tokenizer array size overflow"))?; + if total > MAX_TOKENIZER_ARRAY_BYTES { + return Err(gguf_error("GGUF tokenizer array exceeds 512 MiB")); + } + values.push(value); + } + Ok(values) + } + + fn integer_array(&mut self, kind: u32) -> GgufResult> { + if kind != 9 { + return Err(gguf_error("expected a GGUF integer array")); + } + let element = self.u32()?; + let count = self.u64()?; + let width = value_width(element)?; + self.check_tokenizer_array(count, width)?; + let capacity = usize::try_from(count) + .map_err(|_| gguf_error("GGUF tokenizer array count exceeds platform limits"))?; + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(self.integer(element)?); + } + Ok(values) + } + + fn check_tokenizer_array(&mut self, count: u64, minimum_item_bytes: u64) -> GgufResult<()> { + if count > MAX_TOKENIZER_ARRAY_ITEMS { + return Err(gguf_error("unreasonable GGUF tokenizer array count")); + } + let minimum_bytes = count + .checked_mul(minimum_item_bytes) + .ok_or_else(|| gguf_error("GGUF tokenizer array size overflow"))?; + if minimum_bytes > self.remaining()? { + return Err(gguf_error("GGUF tokenizer array exceeds remaining header")); + } + Ok(()) + } + + fn integer(&mut self, kind: u32) -> GgufResult { + match kind { + 0 | 7 => Ok(u32::from(self.u8()?)), + 1 => u32::try_from(self.u8()? as i8) + .map_err(|_| gguf_error("negative GGUF integer is unsupported")), + 2 => Ok(u32::from(self.u16()?)), + 3 => u32::try_from(self.u16()? as i16) + .map_err(|_| gguf_error("negative GGUF integer is unsupported")), + 4 => self.u32(), + 5 => u32::try_from(self.u32()? as i32) + .map_err(|_| gguf_error("negative GGUF integer is unsupported")), + 10 => u32::try_from(self.u64()?) + .map_err(|_| gguf_error("GGUF integer exceeds 32-bit range")), + 11 => u32::try_from(self.u64()? as i64) + .map_err(|_| gguf_error("negative or oversized GGUF integer is unsupported")), + _ => Err(gguf_error(format!( + "GGUF metadata type {kind} is not an integer" + ))), + } + } + + fn skip_value(&mut self, kind: u32) -> GgufResult<()> { + match kind { + 0 | 1 | 7 => self.skip(1), + 2 | 3 => self.skip(2), + 4..=6 => self.skip(4), + 8 => { + let size = self.u64()?; + self.skip(size) + } + 9 => { + let element = self.u32()?; + let count = self.u64()?; + match element { + 8 => { + if count > MAX_GGUF_METADATA_ENTRIES { + return Err(gguf_error("unreasonable GGUF string array count")); + } + let minimum_bytes = count + .checked_mul(8) + .ok_or_else(|| gguf_error("GGUF string array size overflow"))?; + if minimum_bytes > self.remaining()? { + return Err(gguf_error("GGUF string array exceeds remaining header")); + } + for _ in 0..count { + let size = self.u64()?; + if size > MAX_GGUF_HEADER_BYTES { + return Err(gguf_error("GGUF string array element is too large")); + } + self.skip(size)?; + } + Ok(()) + } + 9 => Err(gguf_error("nested GGUF arrays are unsupported")), + _ => { + let width = value_width(element)?; + let bytes = count + .checked_mul(width) + .ok_or_else(|| gguf_error("GGUF array size overflow"))?; + self.skip(bytes) + } + } + } + 10..=12 => self.skip(8), + _ => Err(gguf_error(format!("unknown GGUF metadata type {kind}"))), + } + } +} + +fn value_width(kind: u32) -> GgufResult { + match kind { + 0 | 1 | 7 => Ok(1), + 2 | 3 => Ok(2), + 4..=6 => Ok(4), + 10..=12 => Ok(8), + _ => Err(gguf_error(format!( + "invalid GGUF array element type {kind}" + ))), + } +} + type HeapEntry = (usize, usize, usize, u64, u64); struct Node { @@ -494,3 +880,274 @@ mod tests { fs::remove_dir_all(root).unwrap(); } } + +#[cfg(test)] +mod gguf_metadata_tests { + use super::*; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + + fn fixture_path() -> PathBuf { + std::env::temp_dir().join(format!( + "leleka-tokenizer-gguf-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )) + } + + fn gguf_string(bytes: &mut Vec, value: &str) { + bytes.extend_from_slice(&(value.len() as u64).to_le_bytes()); + bytes.extend_from_slice(value.as_bytes()); + } + + fn string_field(bytes: &mut Vec, key: &str, value: &str) { + gguf_string(bytes, key); + bytes.extend_from_slice(&8u32.to_le_bytes()); + gguf_string(bytes, value); + } + + fn string_array(bytes: &mut Vec, key: &str, values: &[&str]) { + gguf_string(bytes, key); + bytes.extend_from_slice(&9u32.to_le_bytes()); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&(values.len() as u64).to_le_bytes()); + for value in values { + gguf_string(bytes, value); + } + } + + fn base() -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); // no tensors: metadata reader only. + bytes.extend_from_slice(&7u64.to_le_bytes()); + string_field(&mut bytes, "tokenizer.ggml.model", "gpt2"); + string_field(&mut bytes, "tokenizer.ggml.pre", "qwen35"); + string_array( + &mut bytes, + "tokenizer.ggml.tokens", + &["a", "b", "ab", "<|eos|>"], + ); + string_array(&mut bytes, "tokenizer.ggml.merges", &["a b"]); + gguf_string(&mut bytes, "tokenizer.ggml.token_type"); + bytes.extend_from_slice(&9u32.to_le_bytes()); + bytes.extend_from_slice(&4u32.to_le_bytes()); + bytes.extend_from_slice(&4u64.to_le_bytes()); + for value in [1u32, 1, 1, 3] { + bytes.extend_from_slice(&value.to_le_bytes()); + } + gguf_string(&mut bytes, "tokenizer.ggml.eos_token_id"); + bytes.extend_from_slice(&4u32.to_le_bytes()); + bytes.extend_from_slice(&3u32.to_le_bytes()); + string_field(&mut bytes, "tokenizer.chat_template", "{{ messages }}"); + bytes + } + + fn with_bytes(bytes: &[u8], check: impl FnOnce(&Path)) { + let path = fixture_path(); + fs::write(&path, bytes).unwrap(); + check(&path); + fs::remove_file(path).unwrap(); + } + + #[test] + fn reads_qwen35_tokenizer_metadata_with_control_plane_parity() { + with_bytes(&base(), |path| { + let metadata = read_gguf_tokenizer_metadata(path).unwrap(); + assert_eq!(metadata.model, "gpt2"); + assert_eq!(metadata.pre, "qwen35"); + assert_eq!(metadata.tokens, ["a", "b", "ab", "<|eos|>"]); + assert_eq!(metadata.merges, ["a b"]); + assert_eq!(metadata.token_types, Some(vec![1, 1, 1, 3])); + assert_eq!(metadata.special_ids["tokenizer.ggml.eos_token_id"], 3); + assert_eq!(metadata.chat_template, "{{ messages }}"); + }); + } + + #[test] + fn rejects_wrong_magic_version_truncation_and_excessive_metadata_count() { + let mut bytes = base(); + bytes[0] = b'X'; + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("GGUF") + ); + }); + + let mut bytes = base(); + bytes[4..8].copy_from_slice(&2u32.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("v3") + ); + }); + + let bytes = base(); + with_bytes(&bytes[..bytes.len() - 2], |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.extend_from_slice(&u64::MAX.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("entry count") + ); + }); + } + + #[test] + fn rejects_oversized_string_and_truncated_or_excessive_arrays_before_allocation() { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&(MAX_GGUF_STRING_BYTES + 1).to_le_bytes()); + bytes.extend_from_slice(&[0; 5]); // Keep the minimum metadata entry envelope intact. + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("too large") + ); + }); + + let mut bytes = base(); + bytes.extend_from_slice(&[0; 0]); + // Replace the token array's count with a value above the explicit cap. + let marker = b"tokenizer.ggml.tokens"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let count_at = at + 8 + marker.len() + 4 + 4; + bytes[count_at..count_at + 8] + .copy_from_slice(&(MAX_TOKENIZER_ARRAY_ITEMS + 1).to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + + let mut bytes = base(); + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let count_at = at + 8 + marker.len() + 4 + 4; + bytes[count_at..count_at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + } + + #[test] + fn rejects_duplicate_tokenizer_metadata_and_duplicate_vocabulary_tokens() { + let mut bytes = base(); + string_field(&mut bytes, "tokenizer.ggml.model", "gpt2"); + bytes[16..24].copy_from_slice(&8u64.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("duplicate tokenizer metadata") + ); + }); + + let mut bytes = base(); + // Rewrite the third token "ab" to "a", preserving all offsets. + let marker = b"tokenizer.ggml.tokens"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let third_token_len_at = at + 8 + marker.len() + 4 + 4 + 8 + 8 + 1 + 8 + 1; + bytes[third_token_len_at..third_token_len_at + 8].copy_from_slice(&1u64.to_le_bytes()); + bytes.copy_within(third_token_len_at + 8 + 2.., third_token_len_at + 8 + 1); + bytes.truncate(bytes.len() - 1); + with_bytes(&bytes, |path| { + let result = read_gguf_tokenizer_metadata(path); + assert!(result.is_err(), "unexpected parse result: {result:?}"); + }); + } + + #[test] + fn rejects_invalid_tokenizer_types_ids_merges_and_unknown_metadata_types() { + let mut bytes = base(); + let marker = b"tokenizer.ggml.eos_token_id"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let value_at = at + 8 + marker.len() + 4; + bytes[value_at..value_at + 4].copy_from_slice(&99u32.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + + let mut bytes = base(); + let marker = b"tokenizer.ggml.merges"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let value_at = at + 8 + marker.len() + 4 + 4 + 8 + 8; + bytes[value_at..value_at + 3].copy_from_slice(b"x y"); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + + let mut bytes = base(); + let marker = b"tokenizer.ggml.token_type"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let count_at = at + 8 + marker.len() + 4 + 4; + bytes[count_at..count_at + 8].copy_from_slice(&3u64.to_le_bytes()); + bytes.drain(count_at + 8 + 4 * 3..count_at + 8 + 4 * 4); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + + let mut bytes = base(); + bytes.extend_from_slice(&("x".len() as u64).to_le_bytes()); + bytes.extend_from_slice(b"x"); + bytes.extend_from_slice(&99u32.to_le_bytes()); + bytes.extend_from_slice(&8u64.to_le_bytes()); + bytes[16..24].copy_from_slice(&8u64.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + } + + #[test] + fn missing_pre_tokenizer_uses_the_existing_qwen_default() { + let mut bytes = base(); + let marker = b"tokenizer.ggml.pre"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let start = at - 8; + let end = at + marker.len() + 4 + 8 + b"qwen35".len(); + bytes.drain(start..end); + bytes[16..24].copy_from_slice(&6u64.to_le_bytes()); + with_bytes(&bytes, |path| { + assert_eq!(read_gguf_tokenizer_metadata(path).unwrap().pre, "qwen35"); + }); + } +} diff --git a/docs/model-assets.md b/docs/model-assets.md index 373a3c59..0a631219 100644 --- a/docs/model-assets.md +++ b/docs/model-assets.md @@ -39,6 +39,15 @@ The acquisition stage downloads GGUF files; the native tokenizer stage extracts `model inspect` reads the GGUF v3 header and tensor directory without mapping weight data. It checks metadata types, counts, alignment, duplicate keys/tensors, split numbering, and whether tensor start offsets fit the file. This is a structural check, not proof that all tensor bytes or quantization geometry are valid. +The public `leleka-tokenizer::read_gguf_tokenizer_metadata` API reads the +current Qwen35 GPT-2 BPE tokenizer fields directly from a GGUF v3 file. It +accepts a missing `tokenizer.ggml.pre` as `qwen35`, returns optional token +types and special-token IDs, and requires the vocabulary, merges, and chat +template. It bounds header reads to 1 GiB, individual strings to 1 MiB, and +tokenizer string arrays to 1,000,000 entries and 512 MiB of aggregate string +bytes. It reads no tensor payload; callers needing model structure or tensor +validation must separately use the GGUF inspector. + `model extract-tokenizer` validates the Qwen byte-level BPE metadata, then writes `tokenizer/` under the output directory through a staging directory. It requires a nonempty chat template and refuses to overwrite an existing tokenizer directory. The dense/expert pack is still pending. The extracted directory is accepted by the native `model tokenize` and `model detokenize` commands. `model tokenize TOKENIZER_DIR --stdin --special` reads UTF-8 text from standard input and prints a JSON array of token IDs; `--special` enables control tokens such as `<|im_end|>`. User-defined tokens remain literal in both modes. `model detokenize TOKENIZER_DIR 1,2,3` prints a JSON string. The native BPE path matched the pinned upstream tokenizer on 20 cases from the real verified first shard. The dense/expert pack and model startup remain pending. -- 2.54.0 From 684f4cb191fa187b170343ca96e766e6c3c72ae5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:09:53 +0200 Subject: [PATCH 02/58] ci: target configured Linux runners --- .github/workflows/linux.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index bff86839..dc385ce3 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -25,7 +25,7 @@ permissions: jobs: verify: - runs-on: ubuntu-24.04 + runs-on: linux steps: - uses: actions/checkout@v4 - name: Install build tools @@ -103,7 +103,7 @@ jobs: hosted-cuda-package: if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private needs: verify - runs-on: ubuntu-24.04 + runs-on: linux timeout-minutes: 150 env: CUDA_VISIBLE_DEVICES: '' @@ -191,7 +191,7 @@ jobs: linux-static-cli: needs: verify - runs-on: ubuntu-24.04 + runs-on: linux steps: - uses: actions/checkout@v4 - name: Install musl toolchain @@ -327,7 +327,7 @@ jobs: linux-cli-container: needs: verify - runs-on: ubuntu-24.04 + runs-on: linux steps: - uses: actions/checkout@v4 - name: Build actual CLI-only scratch image @@ -341,7 +341,7 @@ jobs: release-cli: if: startsWith(github.ref, 'refs/tags/v') needs: [linux-static-cli, linux-cli-container] - runs-on: ubuntu-24.04 + runs-on: linux permissions: contents: write steps: -- 2.54.0 From d07df86a12cf5a3c3f915ef41d2c11325bad72eb Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:10:38 +0200 Subject: [PATCH 03/58] ci: use configured ubuntu-latest runner label --- .github/workflows/linux.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index dc385ce3..4711d38d 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -25,7 +25,7 @@ permissions: jobs: verify: - runs-on: linux + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install build tools @@ -103,7 +103,7 @@ jobs: hosted-cuda-package: if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private needs: verify - runs-on: linux + runs-on: ubuntu-latest timeout-minutes: 150 env: CUDA_VISIBLE_DEVICES: '' @@ -191,7 +191,7 @@ jobs: linux-static-cli: needs: verify - runs-on: linux + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install musl toolchain @@ -327,7 +327,7 @@ jobs: linux-cli-container: needs: verify - runs-on: linux + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build actual CLI-only scratch image @@ -341,7 +341,7 @@ jobs: release-cli: if: startsWith(github.ref, 'refs/tags/v') needs: [linux-static-cli, linux-cli-container] - runs-on: linux + runs-on: ubuntu-latest permissions: contents: write steps: -- 2.54.0 From f0d4814649777c4d2ad355ccf826d822df1cb468 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:13:34 +0200 Subject: [PATCH 04/58] ci: install packages in root job containers --- .github/workflows/linux.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 4711d38d..0313596b 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -28,8 +28,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + # The configured Gitea ubuntu-latest label runs a root node:24-bookworm job container; + # sudo is not installed there, so install packages directly. - name: Install build tools - run: sudo apt-get update && sudo apt-get install -y cmake ninja-build g++ python3-numpy + run: apt-get update && apt-get install -y cmake ninja-build g++ python3-numpy - name: Install pinned Rust run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Local checks @@ -117,7 +119,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - sudo apt-get update && sudo apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils + apt-get update && apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Record actual toolchain @@ -195,7 +197,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: sudo apt-get update && sudo apt-get install -y musl-tools cmake binutils python3-numpy + run: apt-get update && apt-get install -y musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | rustup toolchain install 1.99.0 --profile minimal -- 2.54.0 From 39a0fe00daa72318575b16dfd072e6b2d6692a2b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:16:52 +0200 Subject: [PATCH 05/58] ci: bootstrap pinned Rust in Linux containers --- .github/workflows/linux.yml | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 0313596b..415d0d24 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -31,14 +31,18 @@ jobs: # The configured Gitea ubuntu-latest label runs a root node:24-bookworm job container; # sudo is not installed there, so install packages directly. - name: Install build tools - run: apt-get update && apt-get install -y cmake ninja-build g++ python3-numpy + run: apt-get update && apt-get install -y ca-certificates curl cmake ninja-build g++ python3-numpy - name: Install pinned Rust - run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" + rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Local checks run: scripts/check-local.sh keyless-cuda: - if: github.event_name == 'workflow_dispatch' && inputs.keyless_gpu + if: github.event_name == 'workflow_dispatch' && github.event.inputs.keyless_gpu == 'true' runs-on: [self-hosted, linux, x64, strata-gpu] steps: - uses: actions/checkout@v4 @@ -61,6 +65,9 @@ jobs: run: nice -n 10 scripts/build-static-cuda.sh - name: Install pinned Rust and musl target run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" rustup toolchain install 1.99.0 --profile minimal rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl command -v musl-gcc @@ -119,7 +126,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils + apt-get update && apt-get install -y ca-certificates curl gcc-13 g++-13 cmake ninja-build musl-tools binutils - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Record actual toolchain @@ -146,6 +153,9 @@ jobs: run: scripts/build-static-cuda.sh - name: Install pinned Rust and musl target run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" rustup toolchain install 1.99.0 --profile minimal rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl - name: Assemble actual combined executable and runtime image @@ -197,9 +207,12 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: apt-get update && apt-get install -y musl-tools cmake binutils python3-numpy + run: apt-get update && apt-get install -y ca-certificates curl musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" rustup toolchain install 1.99.0 --profile minimal rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl - name: Build static CLI -- 2.54.0 From e5d934a8509d0760293a9429b2f31c82aa55b35d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:21:01 +0200 Subject: [PATCH 06/58] ci: support safe CUDA archive extraction on Python 3.11 --- .github/workflows/linux.yml | 1 + scripts/bootstrap-cuda-toolkit.py | 27 ++++++++++++++++++++++++++- scripts/test-cuda-bootstrap.py | 19 +++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 415d0d24..9c25b120 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -43,6 +43,7 @@ jobs: keyless-cuda: if: github.event_name == 'workflow_dispatch' && github.event.inputs.keyless_gpu == 'true' + needs: verify runs-on: [self-hosted, linux, x64, strata-gpu] steps: - uses: actions/checkout@v4 diff --git a/scripts/bootstrap-cuda-toolkit.py b/scripts/bootstrap-cuda-toolkit.py index 4324ca71..9574eea6 100644 --- a/scripts/bootstrap-cuda-toolkit.py +++ b/scripts/bootstrap-cuda-toolkit.py @@ -6,6 +6,7 @@ redistrib archives are assembly inputs, not a general-purpose CUDA installer. """ import argparse import hashlib +import inspect import json import os from pathlib import Path, PurePosixPath @@ -53,6 +54,30 @@ def validate_lock(lock, manifest): raise ValueError('component exceeds download budget') +def extract_members(source, destination, members, *, supports_filter=None): + """Use tarfile's data policy on both new and older Python runtimes. + + Python 3.11 includes ``tarfile.data_filter`` but its ``extractall`` does + not accept the ``filter`` keyword. Pre-filtering every member preserves + the same path, link, mode, and ownership checks there. Fail closed if a + Python runtime has neither API rather than extracting unfiltered data. + """ + if supports_filter is None: + supports_filter = 'filter' in inspect.signature(source.extractall).parameters + if supports_filter: + source.extractall(destination, members=members, filter='data') + return + data_filter = getattr(tarfile, 'data_filter', None) + if data_filter is None: + raise RuntimeError('safe tar extraction requires Python tarfile data_filter support') + safe_members = [] + for member in members: + safe_member = data_filter(member, str(destination)) + if safe_member is not None: + safe_members.append(safe_member) + source.extractall(destination, members=safe_members) + + def extract(archive, destination, root_name): with tarfile.open(archive, 'r:xz') as source: members=source.getmembers() @@ -68,7 +93,7 @@ def extract(archive, destination, root_name): seen.add(item.name) if not (item.isdir() or item.isfile() or item.issym() or item.islnk()): raise ValueError('unsupported archive member') - source.extractall(destination, members=members, filter='data') + extract_members(source, destination, members) return destination/root_name diff --git a/scripts/test-cuda-bootstrap.py b/scripts/test-cuda-bootstrap.py index 8e5b21d2..fd371aeb 100644 --- a/scripts/test-cuda-bootstrap.py +++ b/scripts/test-cuda-bootstrap.py @@ -20,6 +20,25 @@ class Tests(unittest.TestCase): item=tarfile.TarInfo('component/lib/b');item.type=tarfile.SYMTYPE;item.linkname='a';t.addfile(item) out=m.extract(archive,root/'out','component') self.assertEqual((out/'lib/b').read_bytes(),b'a') + def test_python311_style_data_filter_fallback(self): + # Python 3.11 has data_filter but extractall(filter=...) is unavailable. + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo('component/lib/a');item.size=1;t.addfile(item,io.BytesIO(b'a')) + item=tarfile.TarInfo('component/lib/b');item.type=tarfile.SYMTYPE;item.linkname='a';t.addfile(item) + with tarfile.open(archive,'r:xz') as source: + m.extract_members(source,dest,source.getmembers(),supports_filter=False) + self.assertEqual((dest/'component/lib/b').read_bytes(),b'a') + def test_python311_style_fallback_rejects_escaping_link(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo('component/b');item.type=tarfile.SYMTYPE;item.linkname='../../escape';t.addfile(item) + with tarfile.open(archive,'r:xz') as source: + with self.assertRaises(tarfile.FilterError): + m.extract_members(source,dest,source.getmembers(),supports_filter=False) + self.assertFalse((root/'escape').exists()) def test_bad_archive_paths_and_links(self): for name,link in [('../escape',None),('/escape',None),('other/file',None),('component/b','../../escape')]: with self.subTest(name=name),tempfile.TemporaryDirectory() as tmp: -- 2.54.0 From 65a8dbd469334ae3544447e47e8bdf5082dde666 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:25:52 +0200 Subject: [PATCH 07/58] fix: safely extract CUDA bundles with Python 3.11 --- scripts/bootstrap-cuda-toolkit.py | 67 ++++++++++++++++++++++++++----- scripts/test-cuda-bootstrap.py | 11 ++++- 2 files changed, 68 insertions(+), 10 deletions(-) diff --git a/scripts/bootstrap-cuda-toolkit.py b/scripts/bootstrap-cuda-toolkit.py index 9574eea6..fd36039c 100644 --- a/scripts/bootstrap-cuda-toolkit.py +++ b/scripts/bootstrap-cuda-toolkit.py @@ -5,6 +5,7 @@ No driver installation, model access, root privileges or inference. NVIDIA's redistrib archives are assembly inputs, not a general-purpose CUDA installer. """ import argparse +import copy import hashlib import inspect import json @@ -57,42 +58,90 @@ def validate_lock(lock, manifest): def extract_members(source, destination, members, *, supports_filter=None): """Use tarfile's data policy on both new and older Python runtimes. - Python 3.11 includes ``tarfile.data_filter`` but its ``extractall`` does - not accept the ``filter`` keyword. Pre-filtering every member preserves - the same path, link, mode, and ownership checks there. Fail closed if a - Python runtime has neither API rather than extracting unfiltered data. + Python 3.11 runners may have neither ``extractall(filter=...)`` nor the + later ``tarfile.data_filter`` helper, so provide the same restricted data + policy locally. Never fall back to unfiltered extraction. """ if supports_filter is None: supports_filter = 'filter' in inspect.signature(source.extractall).parameters if supports_filter: source.extractall(destination, members=members, filter='data') return - data_filter = getattr(tarfile, 'data_filter', None) - if data_filter is None: - raise RuntimeError('safe tar extraction requires Python tarfile data_filter support') safe_members = [] for member in members: - safe_member = data_filter(member, str(destination)) + safe_member = safe_data_filter(member, destination) if safe_member is not None: safe_members.append(safe_member) source.extractall(destination, members=safe_members) +def safe_data_filter(member, destination): + """Python 3.11-compatible equivalent of tarfile's restrictive data filter.""" + name = member.name + if name.startswith('/') or os.path.isabs(name): + raise ValueError('absolute archive member path') + root = os.path.realpath(destination) + target = os.path.realpath(os.path.join(root, name)) + if os.path.commonpath((target, root)) != root: + raise ValueError('archive member escapes extraction root') + + filtered = copy.copy(member) + mode = member.mode + if mode is not None: + mode &= 0o755 + if member.isreg() or member.islnk(): + if not mode & 0o100: + mode &= ~0o111 + mode |= 0o600 + elif member.isdir() or member.issym(): + mode = None + else: + raise ValueError('unsupported special archive member') + filtered.mode = mode + + filtered.uid = filtered.gid = None + filtered.uname = filtered.gname = None + if member.issym() or member.islnk(): + if os.path.isabs(member.linkname): + raise ValueError('absolute archive link target') + normalized = os.path.normpath(member.linkname) + filtered.linkname = normalized + if member.issym(): + link_target = os.path.join(root, os.path.dirname(name), normalized) + else: + link_target = os.path.join(root, normalized) + resolved = os.path.realpath(link_target) + if os.path.commonpath((resolved, root)) != root: + raise ValueError('archive link escapes extraction root') + return filtered + + def extract(archive, destination, root_name): with tarfile.open(archive, 'r:xz') as source: members=source.getmembers() if len(members)>50000 or sum(x.size for x in members)>6*1024**3: raise ValueError('archive expansion limit exceeded') - seen=set() + seen=set();links=set() for item in members: path=PurePosixPath(item.name) if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!=root_name: raise ValueError('archive path outside component root') + if item.name.rstrip('/') != str(path): + raise ValueError('non-canonical archive member path') if item.name in seen: raise ValueError('duplicate archive member') seen.add(item.name) if not (item.isdir() or item.isfile() or item.issym() or item.islnk()): raise ValueError('unsupported archive member') + if item.issym() or item.islnk(): + links.add(str(path)) + # Prevent a later member from traversing through an archive-created + # symlink/hardlink parent, even when each link target is individually + # confined to the destination. + for item in members: + path=PurePosixPath(item.name) + if any(str(parent) in links for parent in path.parents): + raise ValueError('archive member descends through a link') extract_members(source, destination, members) return destination/root_name diff --git a/scripts/test-cuda-bootstrap.py b/scripts/test-cuda-bootstrap.py index fd371aeb..1302b978 100644 --- a/scripts/test-cuda-bootstrap.py +++ b/scripts/test-cuda-bootstrap.py @@ -36,9 +36,18 @@ class Tests(unittest.TestCase): with tarfile.open(archive,'w:xz') as t: item=tarfile.TarInfo('component/b');item.type=tarfile.SYMTYPE;item.linkname='../../escape';t.addfile(item) with tarfile.open(archive,'r:xz') as source: - with self.assertRaises(tarfile.FilterError): + with self.assertRaises(ValueError): m.extract_members(source,dest,source.getmembers(),supports_filter=False) self.assertFalse((root/'escape').exists()) + def test_rejects_member_nested_under_archive_symlink(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo('component/a');item.type=tarfile.SYMTYPE;item.linkname='..';t.addfile(item) + # Lexically this link is still inside the root, but after the + # parent symlink is followed it would escape the extraction tree. + item=tarfile.TarInfo('component/a/x');item.type=tarfile.SYMTYPE;item.linkname='../..';t.addfile(item) + with self.assertRaises(ValueError):m.extract(archive,root/'out','component') def test_bad_archive_paths_and_links(self): for name,link in [('../escape',None),('/escape',None),('other/file',None),('component/b','../../escape')]: with self.subTest(name=name),tempfile.TemporaryDirectory() as tmp: -- 2.54.0 From cde6063c9c7b7be1a96155a18eb87e7b63215c29 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:27:18 +0200 Subject: [PATCH 08/58] fix: ignore archive owner metadata on Python 3.11 --- scripts/bootstrap-cuda-toolkit.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/scripts/bootstrap-cuda-toolkit.py b/scripts/bootstrap-cuda-toolkit.py index fd36039c..d4e95b86 100644 --- a/scripts/bootstrap-cuda-toolkit.py +++ b/scripts/bootstrap-cuda-toolkit.py @@ -72,7 +72,14 @@ def extract_members(source, destination, members, *, supports_filter=None): safe_member = safe_data_filter(member, destination) if safe_member is not None: safe_members.append(safe_member) - source.extractall(destination, members=safe_members) + # tarfile 3.11's legacy chown path does not treat None ownership fields as + # "use current user". Pin filtered members to the extracting identity so + # archive ownership is ignored without relying on a Python 3.12 behavior. + for member in safe_members: + member.uid = os.geteuid() + member.gid = os.getegid() + member.uname = member.gname = '' + source.extractall(destination, members=safe_members, numeric_owner=True) def safe_data_filter(member, destination): -- 2.54.0 From b7d8388806e1b0f0bb671034a0221a89fed0ea71 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 21:52:39 +0200 Subject: [PATCH 09/58] ci: fix Linux CLI artifact path and Docker client --- .github/workflows/linux.yml | 64 +++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 9c25b120..479f3b50 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -220,7 +220,7 @@ jobs: run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next - name: Verify ELF and checksum run: | - binary=control-plane/target/x86_64-unknown-linux-musl/release/strata-next + binary=target/x86_64-unknown-linux-musl/release/strata-next if readelf -l "$binary" | grep -q INTERP; then echo 'ELF has a dynamic interpreter' >&2 exit 1 @@ -248,69 +248,69 @@ jobs: cd dist sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS - name: Static CLI model smoke - run: python3 scripts/smoke-static-cli.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-static-cli.py target/x86_64-unknown-linux-musl/release/strata-next - name: Engine loader probe before model acquisition - run: python3 scripts/smoke-engine-probe.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-engine-probe.py target/x86_64-unknown-linux-musl/release/strata-next - name: Explicit GPU profile driver policy without GPU - run: python3 scripts/smoke-gpu-requirement.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-gpu-requirement.py target/x86_64-unknown-linux-musl/release/strata-next - name: Declared GPU memory admission and child UUID pin without GPU - run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-cuda-memory.py target/x86_64-unknown-linux-musl/release/strata-next - name: Atomic pinned assets before native serving - run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-asset-bootstrap.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native GGUF pack preparation against upstream oracle - run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-native-pack.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native fetch prepare serve and verified offline reuse - run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-native-bootstrap.py target/x86_64-unknown-linux-musl/release/strata-next - name: Pinned MTP structural preflight and native bootstrap - run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-mtp-pack.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native runtime profile metadata admission - run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-runtime-profile.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native systemd unit syntax and path safety - run: python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-service-unit.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native installer with actual isolated systemd user service run: | uid=$(id -u) sudo systemctl start "user@$uid.service" export XDG_RUNTIME_DIR="/run/user/$uid" export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus" - python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --lifecycle - python3 scripts/smoke-native-switch.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + python3 scripts/smoke-service-unit.py target/x86_64-unknown-linux-musl/release/strata-next --lifecycle + python3 scripts/smoke-native-switch.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native deployment configuration without worker launch - run: python3 scripts/smoke-config-check.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-config-check.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native deployment readiness deadline without GPU - run: python3 scripts/smoke-wait-ready.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-wait-ready.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native API authentication without GPU - run: python3 scripts/smoke-native-auth.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-native-auth.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native custom text and regex tools without GPU - run: python3 scripts/smoke-custom-tools.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-custom-tools.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native auto/none/required/forced tool policy without GPU - run: python3 scripts/smoke-tool-policy.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-tool-policy.py target/x86_64-unknown-linux-musl/release/strata-next - name: Live Responses replay and corrupt SSE evidence without GPU - run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-live-responses-replay.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-live-responses-replay.py target/x86_64-unknown-linux-musl/release/strata-next - name: Input token count exact GEN wire parity without inference - run: python3 scripts/smoke-input-tokens.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-input-tokens.py target/x86_64-unknown-linux-musl/release/strata-next - name: Chat Completions live protocol and wire parity - run: python3 scripts/smoke-chat-completions.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-chat-completions.py target/x86_64-unknown-linux-musl/release/strata-next - name: Messages named SSE and tool protocol without GPU - run: python3 scripts/smoke-messages.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-messages.py target/x86_64-unknown-linux-musl/release/strata-next - name: SSE idle keep-alive, terminal parity and disconnect without GPU - run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/smoke-sse-keepalive.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/smoke-sse-keepalive.py target/x86_64-unknown-linux-musl/release/strata-next - name: Stored Responses retrieval and deletion without GPU - run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-response-history.py target/x86_64-unknown-linux-musl/release/strata-next - name: Durable Responses restart and disk failure gate - run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --durable + run: python3 scripts/smoke-response-history.py target/x86_64-unknown-linux-musl/release/strata-next --durable - name: Native drain and resume without GPU - run: python3 scripts/smoke-native-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-native-drain.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native signal shutdown grace without GPU - run: python3 scripts/smoke-signal-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-signal-drain.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native generation deadline and recovery without GPU - run: python3 scripts/smoke-generation-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-generation-deadline.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native queue deadline without expiring active work - run: python3 scripts/smoke-queue-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-queue-deadline.py target/x86_64-unknown-linux-musl/release/strata-next - name: Static CLI HTTP cancellation failure isolation - run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + run: python3 scripts/smoke-worker-cancel.py target/x86_64-unknown-linux-musl/release/strata-next - name: Static CLI HTTP crash recovery without request replay - run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --restart + run: python3 scripts/smoke-worker-cancel.py target/x86_64-unknown-linux-musl/release/strata-next --restart - name: Embedded CPU worker packaging without GPU run: | musl-gcc -O2 -static scripts/fixtures/embedded-worker.c -o "$RUNNER_TEMP/embedded-worker" @@ -346,6 +346,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - name: Install the Docker CLI + run: command -v docker >/dev/null 2>&1 || { apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io >/dev/null; } - name: Build actual CLI-only scratch image run: docker build --file deploy/Dockerfile.static-cli --tag strata-cli-check . - name: Check isolated CLI container startup and shutdown -- 2.54.0 From ca8b1fee67795f3c6fff9d9b7ef147b2ca6b9a87 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 22:09:10 +0200 Subject: [PATCH 10/58] ci: provide systemd tools and tokenizer source for Linux tests --- .github/workflows/linux.yml | 2 +- deploy/Dockerfile.static-cli | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 479f3b50..79cbc6e2 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -208,7 +208,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: apt-get update && apt-get install -y ca-certificates curl musl-tools cmake binutils python3-numpy + run: apt-get update && apt-get install -y ca-certificates curl musl-tools cmake binutils python3-numpy systemd - name: Install pinned Rust and target run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none diff --git a/deploy/Dockerfile.static-cli b/deploy/Dockerfile.static-cli index 066dde61..68182dd7 100644 --- a/deploy/Dockerfile.static-cli +++ b/deploy/Dockerfile.static-cli @@ -7,8 +7,11 @@ RUN apt-get update \ RUN rustup target add "${RUST_TARGET}" WORKDIR /src +COPY Cargo.toml Cargo.lock ./ COPY rust-toolchain.toml ./ COPY manifests/ ./manifests/ +COPY crates/ ./crates/ +COPY desktop-core/ ./desktop-core/ COPY control-plane/ ./control-plane/ COPY engine/strata/LICENSE ./engine/strata/LICENSE RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \ -- 2.54.0 From 679572a13e3c0c79a59e3e6f2cdbad1cfeaecac2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 22:22:16 +0200 Subject: [PATCH 11/58] ci: isolate systemd lifecycle smoke in Linux container --- .github/workflows/linux.yml | 43 ++++++++++++++++++++++++++++----- deploy/Dockerfile.static-cli | 2 +- deploy/Dockerfile.systemd-smoke | 12 +++++++++ 3 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 deploy/Dockerfile.systemd-smoke diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 79cbc6e2..80598740 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -269,12 +269,43 @@ jobs: run: python3 scripts/smoke-service-unit.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native installer with actual isolated systemd user service run: | - uid=$(id -u) - sudo systemctl start "user@$uid.service" - export XDG_RUNTIME_DIR="/run/user/$uid" - export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus" - python3 scripts/smoke-service-unit.py target/x86_64-unknown-linux-musl/release/strata-next --lifecycle - python3 scripts/smoke-native-switch.py target/x86_64-unknown-linux-musl/release/strata-next + image="leleka-systemd-smoke:${GITHUB_RUN_ID}" + container="leleka-systemd-smoke-${GITHUB_RUN_ID}" + cleanup() { + docker rm --force "$container" >/dev/null 2>&1 || true + docker image rm "$image" >/dev/null 2>&1 || true + } + trap cleanup EXIT + docker build --file deploy/Dockerfile.systemd-smoke --tag "$image" . + docker run --detach --privileged --cgroupns=private --name "$container" \ + --tmpfs /run --tmpfs /run/lock \ + --stop-signal SIGRTMIN+3 "$image" + for attempt in $(seq 1 30); do + if docker exec "$container" systemctl show-environment >/dev/null 2>&1; then break; fi + test "$attempt" -lt 30 || { docker logs "$container"; exit 1; } + sleep 1 + done + uid=1000 + docker exec "$container" systemctl start "user@$uid.service" + for attempt in $(seq 1 30); do + if docker exec "$container" test -S "/run/user/$uid/bus"; then break; fi + test "$attempt" -lt 30 || { docker logs "$container"; exit 1; } + sleep 1 + done + docker cp target/x86_64-unknown-linux-musl/release/strata-next "$container:/tmp/strata-next" + docker cp scripts/smoke-service-unit.py "$container:/tmp/smoke-service-unit.py" + docker cp scripts/smoke-native-switch.py "$container:/tmp/smoke-native-switch.py" + docker cp scripts/smoke-worker-cancel.py "$container:/tmp/smoke-worker-cancel.py" + docker exec --user "$uid" \ + --env HOME=/home/leleka \ + --env XDG_RUNTIME_DIR="/run/user/$uid" \ + --env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \ + "$container" python3 /tmp/smoke-service-unit.py /tmp/strata-next --lifecycle + docker exec --user "$uid" \ + --env HOME=/home/leleka \ + --env XDG_RUNTIME_DIR="/run/user/$uid" \ + --env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \ + "$container" python3 /tmp/smoke-native-switch.py /tmp/strata-next - name: Native deployment configuration without worker launch run: python3 scripts/smoke-config-check.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native deployment readiness deadline without GPU diff --git a/deploy/Dockerfile.static-cli b/deploy/Dockerfile.static-cli index 68182dd7..d36d96b1 100644 --- a/deploy/Dockerfile.static-cli +++ b/deploy/Dockerfile.static-cli @@ -19,5 +19,5 @@ RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \ FROM scratch ARG RUST_TARGET=x86_64-unknown-linux-musl -COPY --from=build /src/control-plane/target/${RUST_TARGET}/release/strata-next /strata-next +COPY --from=build /src/target/${RUST_TARGET}/release/strata-next /strata-next ENTRYPOINT ["/strata-next"] diff --git a/deploy/Dockerfile.systemd-smoke b/deploy/Dockerfile.systemd-smoke new file mode 100644 index 00000000..4f3d4925 --- /dev/null +++ b/deploy/Dockerfile.systemd-smoke @@ -0,0 +1,12 @@ +FROM debian:bookworm-slim + +ENV container=docker + +RUN apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ + dbus-user-session python3 systemd systemd-sysv util-linux \ + && useradd --create-home --uid 1000 --shell /bin/sh leleka \ + && rm -rf /var/lib/apt/lists/* + +STOPSIGNAL SIGRTMIN+3 +CMD ["/sbin/init"] -- 2.54.0 From 982f4ce3266acb41358b55601847b3061e201680 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 22:32:26 +0200 Subject: [PATCH 12/58] ci: probe container on isolated runner network --- .github/workflows/linux.yml | 11 ++++--- scripts/smoke-cli-container.py | 55 +++++++++++++++++++++++++++------- 2 files changed, 51 insertions(+), 15 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 80598740..f7c6fb91 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -208,7 +208,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: apt-get update && apt-get install -y ca-certificates curl musl-tools cmake binutils python3-numpy systemd + run: apt-get update && apt-get install -y ca-certificates curl musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none @@ -265,9 +265,7 @@ jobs: run: python3 scripts/smoke-mtp-pack.py target/x86_64-unknown-linux-musl/release/strata-next - name: Native runtime profile metadata admission run: python3 scripts/smoke-runtime-profile.py target/x86_64-unknown-linux-musl/release/strata-next - - name: Native systemd unit syntax and path safety - run: python3 scripts/smoke-service-unit.py target/x86_64-unknown-linux-musl/release/strata-next - - name: Native installer with actual isolated systemd user service + - name: Native systemd unit and lifecycle tests in isolated container run: | image="leleka-systemd-smoke:${GITHUB_RUN_ID}" container="leleka-systemd-smoke-${GITHUB_RUN_ID}" @@ -296,6 +294,11 @@ jobs: docker cp scripts/smoke-service-unit.py "$container:/tmp/smoke-service-unit.py" docker cp scripts/smoke-native-switch.py "$container:/tmp/smoke-native-switch.py" docker cp scripts/smoke-worker-cancel.py "$container:/tmp/smoke-worker-cancel.py" + docker exec --user "$uid" \ + --env HOME=/home/leleka \ + --env XDG_RUNTIME_DIR="/run/user/$uid" \ + --env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \ + "$container" python3 /tmp/smoke-service-unit.py /tmp/strata-next docker exec --user "$uid" \ --env HOME=/home/leleka \ --env XDG_RUNTIME_DIR="/run/user/$uid" \ diff --git a/scripts/smoke-cli-container.py b/scripts/smoke-cli-container.py index c0ed8e47..7fa79592 100644 --- a/scripts/smoke-cli-container.py +++ b/scripts/smoke-cli-container.py @@ -2,6 +2,7 @@ """Exercise the actual CLI-only scratch image; never starts an inference worker.""" import json from pathlib import Path +import socket import subprocess import sys import time @@ -17,18 +18,27 @@ def docker(*args, check=True): def main(image): name = 'strata-cli-smoke-' + uuid.uuid4().hex + network = 'strata-cli-smoke-' + uuid.uuid4().hex + job_container = socket.gethostname() common = ['--name', name, '--read-only', '--user', '65532:65532', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges'] root = Path(__file__).resolve().parents[1] opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) - def get(port, route): + def get(address, route): try: - with opener.open(f'http://127.0.0.1:{port}{route}', timeout=2) as response: + with opener.open(f'{address}{route}', timeout=2) as response: return response.status, json.load(response) except urllib.error.HTTPError as error: return error.code, json.load(error) + inspected_job = docker('inspect', '--format', '{{.Id}}', job_container, check=False) + attached_to_runner_container = inspected_job.returncode == 0 and bool(inspected_job.stdout.strip()) + if attached_to_runner_container: + job_container = inspected_job.stdout.strip() + network_created = False + network_connected = False + try: version = docker('run', '--rm', *common, '--network', 'none', image, '--version').stdout assert version.startswith('strata-next '), version @@ -38,21 +48,40 @@ def main(image): info = json.loads(docker('run', '--rm', *common, '--network', 'none', image, 'engine-info').stdout) assert info['embedded'] is False and info['model_bundled'] is False, info - docker('run', '-d', *common, '-p', '127.0.0.1::8081', - '-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve') - binding = docker('port', name, '8081/tcp').stdout.strip() - assert binding.startswith('127.0.0.1:'), binding - port = int(binding.rsplit(':', 1)[1]) + if attached_to_runner_container: + # In Gitea, the Actions job itself is a sibling container on gitea-net; + # its 127.0.0.1 is not the Docker host where -p publishes ports. Use a + # private per-test network and join only this job plus the smoke image. + docker('network', 'create', '--internal', network) + network_created = True + docker('network', 'connect', network, job_container) + network_connected = True + docker('run', '-d', *common, '--network', network, + '--network-alias', name, '-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve') + address = f'http://{name}:8081' + else: + # Native VM runners can reach host-loopback port publication. + docker('run', '-d', *common, '-p', '127.0.0.1::8081', + '-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve') + binding = docker('port', name, '8081/tcp').stdout.strip() + assert binding.startswith('127.0.0.1:'), binding + address = f'http://{binding}' deadline = time.monotonic() + 15 while True: try: - assert get(port, '/health') == (200, {'status': 'ok'}) + status, health = get(address, '/health') + assert status == 200 and health == {'status': 'ok'}, (status, health) break - except (OSError, AssertionError): + except (OSError, urllib.error.URLError, AssertionError) as error: if time.monotonic() >= deadline: - raise + state = docker('inspect', '--format', '{{json .State}}', name, + check=False).stdout + logs = docker('logs', name, check=False).stdout + raise AssertionError( + f'CLI service did not become healthy; state={state}; logs={logs}' + ) from error time.sleep(0.1) - status, ready = get(port, '/ready') + status, ready = get(address, '/ready') assert status == 503 and ready['ready'] is False, (status, ready) docker('stop', '--time', '10', name) state = json.loads(docker('inspect', '--format', '{{json .State}}', name).stdout) @@ -61,6 +90,10 @@ def main(image): 'non-root read-only health200/ready503, graceful stop. No GPU inference qualified.') finally: docker('rm', '-f', name, check=False) + if network_connected: + docker('network', 'disconnect', network, job_container, check=False) + if network_created: + docker('network', 'rm', network, check=False) if __name__ == '__main__': -- 2.54.0 From 878b4df303a563e8b478c46892c6dc333dae8f47 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 23:10:49 +0200 Subject: [PATCH 13/58] ci: install Docker CLI for systemd lifecycle test --- .github/workflows/linux.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index f7c6fb91..2a19ddd9 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -208,7 +208,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: apt-get update && apt-get install -y ca-certificates curl musl-tools cmake binutils python3-numpy + run: apt-get update && apt-get install -y ca-certificates curl docker.io musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none -- 2.54.0 From f463149d029c8e28d07c4be527058b81ae8f7f8b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 23:27:05 +0200 Subject: [PATCH 14/58] test: report systemd readiness preflight errors --- scripts/smoke-service-unit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/smoke-service-unit.py b/scripts/smoke-service-unit.py index 00833a24..4bcbf464 100644 --- a/scripts/smoke-service-unit.py +++ b/scripts/smoke-service-unit.py @@ -164,7 +164,7 @@ exit {42 if fail_action else 0} '--ready-timeout-s', '2', env=fault_env, check=False) assert bad.returncode != 0, bad.stdout actions = [line.split('|')[2] for line in commands.read_text().splitlines()] - assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), actions + assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), (actions, bad.stderr, bad.stdout) finally: changed_http.shutdown(); changed_http.server_close(); changed_thread.join(timeout=5) fault_unit.write_bytes(retained) -- 2.54.0 From c767751d962731cde3228d78ee7657b49c9856c8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 23:39:48 +0200 Subject: [PATCH 15/58] test: include system root certificates in smoke image --- deploy/Dockerfile.systemd-smoke | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deploy/Dockerfile.systemd-smoke b/deploy/Dockerfile.systemd-smoke index 4f3d4925..ce12fc96 100644 --- a/deploy/Dockerfile.systemd-smoke +++ b/deploy/Dockerfile.systemd-smoke @@ -4,7 +4,7 @@ ENV container=docker RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ - dbus-user-session python3 systemd systemd-sysv util-linux \ + ca-certificates dbus-user-session python3 systemd systemd-sysv util-linux \ && useradd --create-home --uid 1000 --shell /bin/sh leleka \ && rm -rf /var/lib/apt/lists/* -- 2.54.0 From 096d21dcec3a616b0a0323b04fe87c78caf3c728 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 00:13:16 +0200 Subject: [PATCH 16/58] test: stream smoke fixture into Docker volume --- scripts/smoke-runtime-image.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/scripts/smoke-runtime-image.py b/scripts/smoke-runtime-image.py index d4ca1f25..8842653c 100644 --- a/scripts/smoke-runtime-image.py +++ b/scripts/smoke-runtime-image.py @@ -12,7 +12,12 @@ import uuid def docker(*args, check=True): - return subprocess.run(['docker', *map(str, args)], check=check, capture_output=True, text=True, timeout=30) + try: + return subprocess.run(['docker', *map(str, args)], check=check, + capture_output=True, text=True, timeout=30) + except subprocess.CalledProcessError as error: + detail = (error.stderr or '').strip()[-2048:] + raise RuntimeError(f'docker command failed ({error.returncode}): {detail}') from None def main(receipt): @@ -24,6 +29,9 @@ def main(receipt): spec = importlib.util.spec_from_file_location('helper', Path(__file__).with_name('smoke-worker-cancel.py')) helper = importlib.util.module_from_spec(spec); spec.loader.exec_module(helper) name = 'strata-runtime-smoke-' + uuid.uuid4().hex + fixture_container = 'strata-runtime-fixture-' + uuid.uuid4().hex + fixture_volume = 'strata-runtime-fixture-' + uuid.uuid4().hex + base = proof['base'] opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) with tempfile.TemporaryDirectory(prefix='strata-container-fixture-') as tmp: root = Path(tmp); root.chmod(0o755) @@ -33,11 +41,21 @@ def main(receipt): 'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}})) for path in root.iterdir(): path.chmod(0o644) try: + # The Docker daemon may be outside the job container. A job-local + # /tmp bind source is therefore not guaranteed to exist on it. + # `docker cp` streams this synthetic fixture through the CLI into + # a named volume; the tested image then mounts that volume read-only. + docker('volume', 'create', fixture_volume) + docker('create', '--name', fixture_container, '--platform', 'linux/amd64', + '--mount', f'type=volume,src={fixture_volume},dst=/fixture', + '--entrypoint', '/bin/sleep', base, '30') + docker('cp', f'{root}/.', f'{fixture_container}:/fixture/') + docker('rm', fixture_container) docker('run', '-d', '--name', name, '--platform', 'linux/amd64', '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '65532:65532', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void', '-p', '127.0.0.1::8081', - '--mount', f'type=bind,src={root},dst=/fixture,readonly', image, + '--mount', f'type=volume,src={fixture_volume},dst=/fixture,readonly', image, 'serve', '--config', '/fixture/config.json') port = int(docker('port', name, '8081/tcp').stdout.strip().rsplit(':', 1)[1]) def request(route, body=None): @@ -72,6 +90,8 @@ def main(receipt): print('Combined CPU OCI: Responses A exact, worker crash/restart A exact, nonroot/read-only, graceful stop. No GPU/model qualification.') finally: docker('rm','-f',name,check=False) + docker('rm','-f',fixture_container,check=False) + docker('volume','rm',fixture_volume,check=False) if __name__=='__main__': main(sys.argv[1]) -- 2.54.0 From cb075ef762c96ce93f42d97853eadece81a8e4a1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 00:32:38 +0200 Subject: [PATCH 17/58] test: probe runtime image from its network namespace --- scripts/smoke-runtime-image.py | 76 ++++++++++++++++++++++++---------- scripts/test-runtime-image.py | 8 ++++ 2 files changed, 61 insertions(+), 23 deletions(-) diff --git a/scripts/smoke-runtime-image.py b/scripts/smoke-runtime-image.py index 8842653c..9e6da635 100644 --- a/scripts/smoke-runtime-image.py +++ b/scripts/smoke-runtime-image.py @@ -7,9 +7,45 @@ import subprocess import sys import tempfile import time -import urllib.request import uuid +PROBE_SCRIPT = r'''#!/bin/bash +set -euo pipefail +request() { + local method="$1" path="$2" body="${3-}" request status line response + if ! { exec 3<>/dev/tcp/127.0.0.1/8081; } 2>/dev/null; then return 1; fi + if [[ -n "$body" ]]; then + printf -v request '%s %s HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: %s\r\n\r\n%s' \ + "$method" "$path" "${#body}" "$body" + else + printf -v request '%s %s HTTP/1.0\r\nHost: localhost\r\nConnection: close\r\n\r\n' "$method" "$path" + fi + printf '%s' "$request" >&3 + IFS= read -r status <&3 || { exec 3<&-; exec 3>&-; return 1; } + status="${status%$'\r'}" + while IFS= read -r line <&3; do + line="${line%$'\r'}" + [[ -n "$line" ]] || break + done + response="$(cat <&3)" + exec 3<&- + exec 3>&- + [[ "${status:9:3}" == 200 ]] || { echo "HTTP request failed: $status $response" >&2; return 1; } + printf '%s' "$response" +} +deadline=$((SECONDS + 15)) +until status="$(request GET /status)"; do + if (( SECONDS >= deadline )); then echo 'worker did not become ready within 15s' >&2; exit 1; fi + sleep 0.1 +done +[[ "$status" == *'"ready":true'* ]] || { echo "unexpected /status response: $status" >&2; exit 1; } +result="$(request POST /v1/responses '{"model":"embedded-fixture","input":"Reply A","max_output_tokens":1,"reasoning":{"effort":"none"}}')" +[[ "$result" == *'"status":"completed"'* && "$result" == *'"text":"A"'* ]] || { + echo "unexpected Responses result: $result" >&2 + exit 1 +} +''' + def docker(*args, check=True): try: @@ -32,14 +68,15 @@ def main(receipt): fixture_container = 'strata-runtime-fixture-' + uuid.uuid4().hex fixture_volume = 'strata-runtime-fixture-' + uuid.uuid4().hex base = proof['base'] - opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) with tempfile.TemporaryDirectory(prefix='strata-container-fixture-') as tmp: root = Path(tmp); root.chmod(0o755) helper.tokenizer(root) (root/'config.json').write_text(json.dumps({'bind': '0.0.0.0:8081', 'model': 'embedded-fixture', 'engine_probe': True, 'engine': {'executable': '@embedded', 'args': ['/tmp/worker.pid'], 'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}})) + (root/'probe.sh').write_text(PROBE_SCRIPT) for path in root.iterdir(): path.chmod(0o644) + (root/'probe.sh').chmod(0o755) try: # The Docker daemon may be outside the job container. A job-local # /tmp bind source is therefore not guaranteed to exist on it. @@ -54,28 +91,21 @@ def main(receipt): docker('run', '-d', '--name', name, '--platform', 'linux/amd64', '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '65532:65532', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-e', 'CUDA_VISIBLE_DEVICES=', - '-e', 'NVIDIA_VISIBLE_DEVICES=void', '-p', '127.0.0.1::8081', + '-e', 'NVIDIA_VISIBLE_DEVICES=void', '--mount', f'type=volume,src={fixture_volume},dst=/fixture,readonly', image, 'serve', '--config', '/fixture/config.json') - port = int(docker('port', name, '8081/tcp').stdout.strip().rsplit(':', 1)[1]) - def request(route, body=None): - req = urllib.request.Request(f'http://127.0.0.1:{port}{route}', - data=json.dumps(body).encode() if body else None, headers={'Content-Type': 'application/json'}) - with opener.open(req, timeout=5) as response: return json.load(response) - def ready(): - deadline = time.monotonic()+15 - while time.monotonic() Date: Tue, 6 Oct 2026 01:12:48 +0200 Subject: [PATCH 18/58] ci: avoid unsupported Gitea artifact actions --- .github/workflows/linux.yml | 48 ++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 2a19ddd9..f4a0da94 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -370,11 +370,6 @@ jobs: docker image rm "$image" rm "$receipt" fi - - uses: actions/upload-artifact@v4 - with: - name: strata-next-linux-x86_64-musl - path: dist/ - linux-cli-container: needs: verify runs-on: ubuntu-latest @@ -397,10 +392,45 @@ jobs: permissions: contents: write steps: - - uses: actions/download-artifact@v4 - with: - name: strata-next-linux-x86_64-musl - path: dist/ + - uses: actions/checkout@v4 + - name: Install release build tools + run: apt-get update && apt-get install -y ca-certificates curl gh musl-tools cmake binutils python3-numpy + - name: Install pinned Rust and target + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" + rustup toolchain install 1.99.0 --profile minimal + rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + - name: Rebuild release CLI assets on the tag commit + run: | + cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next + binary=target/x86_64-unknown-linux-musl/release/strata-next + if readelf -l "$binary" | grep -q INTERP; then + echo 'ELF has a dynamic interpreter' >&2 + exit 1 + fi + if readelf -d "$binary" | grep -q NEEDED; then + echo 'ELF has a dynamic library dependency' >&2 + exit 1 + fi + "$binary" --version + mkdir -p dist + cp "$binary" dist/strata-next-linux-x86_64-musl + { + echo "Commit: $GITHUB_SHA" + echo "Workflow: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + rustc --version + cargo --version + musl-gcc --version + readelf --version + } > dist/BUILD-PROVENANCE.txt + { + readelf -h "$binary" + readelf -l "$binary" + readelf -d "$binary" + } > dist/ELF-AUDIT.txt + (cd dist && sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS) - name: Publish CLI preview release env: GH_TOKEN: ${{ github.token }} -- 2.54.0 From 65589dff4484f1efb5693e119ac3cde8600c208f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 01:47:32 +0200 Subject: [PATCH 19/58] ci: compile CUDA package in CPU-only Docker --- .github/workflows/linux.yml | 127 +++++-------- deploy/Dockerfile.cuda-builder | 30 +++ deploy/README.md | 51 ++++-- docs/build-validation.md | 25 ++- scripts/build-cuda-engine-in-docker.py | 244 +++++++++++++++++++++++++ scripts/check-local.sh | 3 +- scripts/test-cuda-docker-builder.py | 189 +++++++++++++++++++ 7 files changed, 555 insertions(+), 114 deletions(-) create mode 100644 deploy/Dockerfile.cuda-builder create mode 100644 scripts/build-cuda-engine-in-docker.py create mode 100644 scripts/test-cuda-docker-builder.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index f4a0da94..9de32def 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -15,10 +15,6 @@ on: description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact) type: boolean default: false - static_cuda_package: - description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference) - type: boolean - default: false permissions: contents: read @@ -52,69 +48,13 @@ jobs: - name: Bounded KAR expert component GPU tests run: scripts/check-kar-expert-gpu.sh - static-cuda-package: - if: github.event_name == 'workflow_dispatch' && inputs.static_cuda_package && github.event.repository.private - needs: verify - runs-on: [self-hosted, linux, x64, strata-gpu] - steps: - - uses: actions/checkout@v4 - - name: Build and audit engine without GPU inference - env: - CUDA_VISIBLE_DEVICES: '' - BUILD_JOBS: '2' - STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }} - run: nice -n 10 scripts/build-static-cuda.sh - - name: Install pinned Rust and musl target - run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl - command -v musl-gcc - - name: Assemble combined private package - run: | - engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata" - python3 scripts/build-linux-package.py --engine "$engine" \ - --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \ - --output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Build compatible private runtime image without GPU inference - run: | - package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - python3 scripts/build-runtime-image.py --package "$package" \ - --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ - > "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")" - docker save --output "$package/runtime-image.tar" "$image" - cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json" - (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS) - - uses: actions/upload-artifact@v4 - with: - name: strata-next-static-cuda-preview - path: ${{ runner.temp }}/strata-package-${{ github.run_id }}/ - if-no-files-found: error - retention-days: 7 - - name: Remove uploaded package copy - run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Remove owned runtime image - if: always() - run: | - receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - if test -s "$receipt"; then - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" - rm "$receipt" - fi - - name: Remove private build intermediates - if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" - hosted-cuda-package: if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private needs: verify runs-on: ubuntu-latest timeout-minutes: 150 + permissions: + contents: write env: CUDA_VISIBLE_DEVICES: '' BUILD_JOBS: '1' @@ -122,18 +62,16 @@ jobs: CUDA_ARCHITECTURES: '120' steps: - uses: actions/checkout@v4 - - name: Install compatible host tools (no drivers) + - name: Install Docker and package tools (no drivers) run: | echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && apt-get install -y ca-certificates curl gcc-13 g++-13 cmake ninja-build musl-tools binutils + apt-get update && apt-get install -y ca-certificates curl docker.io gh musl-tools binutils python3-numpy - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Record actual toolchain run: | - "$CUDACXX" --version - g++-13 --version df -h "$RUNNER_TEMP" free -h python3 - <<'PYTOOL' @@ -141,17 +79,17 @@ jobs: from pathlib import Path info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text()) info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(), - gcc=subprocess.check_output(['g++-13','--version'],text=True), - nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True), cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False) (Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n') PYTOOL - - name: Build actual static CUDA engine and audit without GPU - env: - CC: gcc-13 - CXX: g++-13 - CUDAHOSTCXX: g++-13 - run: scripts/build-static-cuda.sh + - name: Compile and audit actual CUDA engine in CPU-only Docker + run: | + python3 scripts/build-cuda-engine-in-docker.py \ + --toolkit "$CUDAToolkit_ROOT" \ + --build-dir "$RUNNER_TEMP/strata-hosted-cuda-build" \ + --output "$STRATA_BUILD_DIR/strata" \ + --metadata "$RUNNER_TEMP/CUDA-BUILDER.json" \ + --image-tag "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - name: Install pinned Rust and musl target run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none @@ -181,16 +119,29 @@ jobs: image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")" docker save --output "$package/runtime-image.tar" "$image" cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json" - cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json" + python3 - "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$RUNNER_TEMP/CUDA-BUILDER.json" "$package/CUDA-TOOLCHAIN.json" <<'PYTOOL' + import json, sys + from pathlib import Path + bootstrap=json.loads(Path(sys.argv[1]).read_text()) + builder=json.loads(Path(sys.argv[2]).read_text()) + bootstrap['docker_builder']=builder + Path(sys.argv[3]).write_text(json.dumps(bootstrap,indent=2)+'\n') + PYTOOL tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS) - - uses: actions/upload-artifact@v4 - with: - name: strata-next-hosted-cuda-preview - path: ${{ runner.temp }}/strata-hosted-cuda-package/ - if-no-files-found: error - retention-days: 7 - - name: Remove uploaded package copy + - name: Publish private CUDA preview release + env: + GH_TOKEN: ${{ github.token }} + run: | + export GH_HOST="${GITHUB_SERVER_URL#https://}" + export GH_HOST="${GH_HOST#http://}" + tag="cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + gh release create "$tag" "$RUNNER_TEMP/strata-hosted-cuda-package/"* \ + --target "$GITHUB_SHA" --repo "$GITHUB_REPOSITORY" \ + --title "CUDA build preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ + --notes 'Actual CUDA compilation and packaging from this commit. Built in a GPU-hidden Docker container. This is not driver, inference, model-quality or performance qualification.' \ + --prerelease + - name: Remove privately published package copy run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package" - name: Remove owned intermediate image and build files if: always() @@ -198,9 +149,15 @@ jobs: receipt="$RUNNER_TEMP/strata-hosted-image.json" if test -s "$receipt"; then image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" + docker image rm "$image" || true fi - rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build" + builder_label="leleka.cuda-builder.run=${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if command -v docker >/dev/null 2>&1; then + docker ps -aq --filter "label=$builder_label" | xargs -r docker rm -f || true + docker volume ls -q --filter "label=$builder_label" | xargs -r docker volume rm --force || true + docker image ls -q --filter "label=$builder_label" | sort -u | xargs -r docker image rm || true + fi + rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-cuda-build" "$RUNNER_TEMP/strata-hosted-package-build" linux-static-cli: needs: verify @@ -435,6 +392,8 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: | + export GH_HOST="${GITHUB_SERVER_URL#https://}" + export GH_HOST="${GH_HOST#http://}" gh release create "${GITHUB_REF_NAME}" dist/strata-next-linux-x86_64-musl dist/SHA256SUMS dist/BUILD-PROVENANCE.txt dist/ELF-AUDIT.txt \ --repo "${GITHUB_REPOSITORY}" --title "Strata Next ${GITHUB_REF_NAME}" \ --notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --prerelease diff --git a/deploy/Dockerfile.cuda-builder b/deploy/Dockerfile.cuda-builder new file mode 100644 index 00000000..439c6038 --- /dev/null +++ b/deploy/Dockerfile.cuda-builder @@ -0,0 +1,30 @@ +FROM --platform=linux/amd64 ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b + +ENV DEBIAN_FRONTEND=noninteractive + +# Freeze Ubuntu's package view as well as the base-image digest. CUDA itself is +# supplied separately by the checksum-pinned redistributable bundle. +RUN rm -f /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list && \ + printf '%s\n' \ + 'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble main universe' \ + 'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble-updates main universe' \ + 'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble-security main universe' \ + > /etc/apt/sources.list && \ + apt-get -o Acquire::Check-Valid-Until=false update && \ + apt-get install -y --no-install-recommends \ + ca-certificates cmake gcc-13 g++-13 git ninja-build python3 python3-numpy && \ + rm -rf /var/lib/apt/lists/* && \ + test "$(gcc-13 -dumpfullversion | cut -d. -f1)" = 13 && \ + mkdir -p /stage/source /stage/toolkit /build && chmod 1777 /build + +ENV CUDACXX=/opt/cuda/bin/nvcc \ + CUDAToolkit_ROOT=/opt/cuda \ + CUDAHOSTCXX=/usr/bin/g++-13 \ + CC=/usr/bin/gcc-13 \ + CXX=/usr/bin/g++-13 \ + CUDA_VISIBLE_DEVICES= \ + NVIDIA_VISIBLE_DEVICES=void \ + HOME=/tmp/home + +WORKDIR /workspace +ENTRYPOINT ["/bin/bash"] diff --git a/deploy/README.md b/deploy/README.md index 1010ce20..acffbaac 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -602,21 +602,27 @@ CMake's static CUDA runtime and cuBLAS targets and statically links the engine's GNU C++ runtime. The default CUDA profile continues to use shared toolkit libraries. HIP and non-Linux/GNU configurations reject this option. -On a Linux builder with the toolkit and CMake already installed: +On a Linux x86_64 host with Docker and the pinned CUDA toolkit bundle already +bootstrapped, use the repository wrapper to build inside a digest-pinned Ubuntu +24.04 amd64 image. The source checkout and toolkit are read-only mounts, output +paths must be fresh and outside the checkout, and no GPU device is passed into +the container: ```sh -export CUDACXX=/absolute/path/to/cuda/bin/nvcc -export CUDAToolkit_ROOT=/absolute/path/to/cuda -# Optional existing pinned llama.cpp checkout; otherwise CMake fetches its pinned source: -export STRATA_GGML_DIR=/absolute/path/to/llama.cpp -BUILD_JOBS=2 scripts/build-static-cuda.sh +python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/strata-cuda-toolkit +python3 scripts/build-cuda-engine-in-docker.py \ + --toolkit /tmp/strata-cuda-toolkit \ + --build-dir /tmp/strata-cuda-build \ + --output /tmp/strata-cuda-output/strata \ + --metadata /tmp/strata-cuda-output/CUDA-BUILDER.json \ + --image-tag local-1 ``` -The script builds only `strata`, using SM 120 and portable AVX2 GGML defaults; -`CUDA_ARCHITECTURES` and `STRATA_BUILD_DIR` can override the build target/path. -It audits ELF dependencies and runs only `--help` with no GPU visible. It does -not install anything, serve a model, change a service, or run a speed test. -CMake's imported targets provide the static dependency closure; see the +The wrapper compiles only `strata`, using SM 120 and portable AVX2 GGML defaults; +`CUDA_ARCHITECTURES` remains configurable in `scripts/build-static-cuda.sh`. +It audits ELF dependencies and runs only `--help` with NVIDIA device nodes hidden. +It does not install anything, serve a model, change a service, run a kernel, or +measure speed. CMake's imported targets provide the static dependency closure; see the [FindCUDAToolkit reference](https://cmake.org/cmake/help/latest/module/FindCUDAToolkit.html). The measured CUDA 13.2 build has only `libm.so.6`, `libc.so.6` and the host loader @@ -638,10 +644,16 @@ the dynamic engine. See the [packaging report](../docs/experiments/2026-10-04-la No quality, numerical parity, speedup or production-ready claim follows from linking successfully. Keep the default profile until the model gates pass. -The optional `static_cuda_package` workflow-dispatch job performs the build and -ELF audit on the private CUDA runner without inference. It publishes no package -and cleans its private build directory. The runner must have the required -compiler/toolkit in its environment; hosted execution has not yet occurred. +The optional `hosted_cuda_package` workflow-dispatch job bootstraps the +checksum-pinned toolkit on the generic Linux runner, then builds the actual CUDA +engine in this GPU-hidden Docker image before assembling the executable and OCI +preview. It publishes a private prerelease asset with provenance and checksums. +This verifies compilation, ELF dependencies and GPU-hidden help only; the host +driver, kernel execution, real model, quality and performance still require +separate GPU qualification. This job publishes a private prerelease because +the Gitea instance does not support the GitHub-hosted `upload-artifact` action. +The independent `keyless_gpu` job remains opt-in and requires an actual GPU +runner for kernel-execution tests. ## Fetch pinned assets as part of native startup @@ -997,11 +1009,10 @@ operator/CI-declared provenance, not a binary-to-source attestation, and this pipeline does not promise bit-identical compiler output. Python is used only on the build host; the resulting runtime does not require it. -The manual `static_cuda_package` workflow builds the engine then assembles and -uploads the combined preview to the **private repository**, with seven-day -artifact retention. It cleans owned build directories after the upload attempt; the final package -copy is removed only after a successful upload. A failed upload leaves that -private final package available for recovery. +The manual `hosted_cuda_package` workflow builds the engine inside a pinned, +GPU-hidden Docker builder on the generic Linux CPU runner, assembles the combined +preview, and publishes it as a private prerelease with provenance and checksums. +The workflow removes its local package copy only after successful publication. The normal hosted job uses `--cpu-fixture` to exercise the same assembly path and then tests exact serving output/restart against the external fixture. CPU artifacts are explicitly marked and are not CUDA releases. No model weights, diff --git a/docs/build-validation.md b/docs/build-validation.md index 6edfc9ca..c3c12131 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -796,8 +796,9 @@ readiness remain separate acceptance gates. No image is pushed to a registry. `workflow_dispatch` input `hosted_cuda_package=true` selects a private-repository Ubuntu 24.04 CPU job. It never targets the private GPU runner. The existing -`static_cuda_package` and `keyless_gpu` inputs remain false unless explicitly -selected. This build does not load a model or install a driver. +`keyless_gpu` input remains false unless explicitly selected and requires a +dedicated GPU runner. The CUDA build route itself needs only the generic Linux +CPU runner. This build does not load a model or install a driver. The build-only `scripts/bootstrap-cuda-toolkit.py` assembles seven components from NVIDIA's [CUDA 13.0.1 redistrib manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.1.json), @@ -807,9 +808,13 @@ prefix, bounded downloads/expansion, safe tar extraction, collision/link checks and retained component licenses avoid a system CUDA installation. This is a build dependency bootstrap, not an end-user runtime installer. NVIDIA documents [component assembly and supported host compilers](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-installation-guide-linux/index.html). -The job explicitly uses GCC 13, one engine compile job, two Rust build jobs and a -150-minute job limit; it refuses acquisition below 6 GiB RAM or 12 GiB free disk. -Actual host/compiler versions and initial resources are recorded. Toolkit bytes +The job builds the CUDA engine with `scripts/build-cuda-engine-in-docker.py` in a +digest-pinned Ubuntu 24.04 amd64 Docker builder, with the source and toolkit +mounted read-only and no GPU devices or NVIDIA container runtime. GCC 13 is +scoped to the engine builder; the job uses one engine compile job, two Rust build +jobs and a 150-minute limit. The toolkit bootstrap refuses acquisition below 6 +GiB RAM or 12 GiB free disk. Container compiler/image identity and initial host +resources are recorded. Toolkit bytes are pinned; hosted OS/compiler patch updates mean byte-identical rebuilds are not asserted. @@ -825,11 +830,13 @@ equality remain mandatory checks for this build-path change. Existing static-engine, combined-package and OCI builders supply the actual compile/link, dependency/ABI, embedded identity and GPU-hidden help gates. -The private `strata-next-hosted-cuda-preview` artifact retains package checksums, +The private prerelease `cuda-preview-.` retains package checksums, source provenance, image archive/receipt, exact toolkit manifest/toolchain data -and component license archive. Retention is seven days. Successful upload is -required; an ephemeral hosted runner is not durable fallback storage if upload -fails. Owned build directories and image are cleaned. Tests use deliberately +and component license archive. Publishing uses the same Gitea-compatible `gh +release create` path as the CLI preview; the unsupported `actions/upload-artifact` +action is not used. A failed publication fails the job; an ephemeral hosted +runner is not durable fallback storage if publication fails. Owned build +directories and image are cleaned. Tests use deliberately invalid archives/receipts and do not require CUDA; only a successful manual actual-CUDA job qualifies compilation and packaging. GPU driver loading, full-model/MTP inference, quality and clean-node rollback remain separate gates. diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py new file mode 100644 index 00000000..77828a47 --- /dev/null +++ b/scripts/build-cuda-engine-in-docker.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Build and audit the CUDA engine in a pinned CPU-only Linux Docker container.""" +import argparse +import hashlib +from io import BytesIO +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tarfile +import tempfile +import uuid + +REPO = Path(__file__).resolve().parents[1].resolve() +DOCKERFILE = REPO / 'deploy/Dockerfile.cuda-builder' +BASE = 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' +PLATFORM = 'linux/amd64' + +CONTAINER_BUILD = r'''set -euo pipefail +test -x /opt/cuda/bin/nvcc +test -f /opt/cuda/lib/libcudart_static.a +shopt -s nullglob +devices=(/dev/nvidia*) +if (( ${#devices[@]} != 0 )); then + echo "CUDA builder unexpectedly sees NVIDIA device nodes: ${devices[*]}" >&2 + exit 91 +fi +test "${CUDA_VISIBLE_DEVICES+x}" = x && test -z "$CUDA_VISIBLE_DEVICES" +test "${NVIDIA_VISIBLE_DEVICES}" = void +mkdir -p /tmp/home /build/engine /build/output +python3 - <<'PY' +import json, os, subprocess +def capture(*args): + return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT).strip() +data = { + 'builder_base': os.environ['LELEKA_BUILDER_BASE'], + 'builder_platform': 'linux/amd64', + 'apt_snapshot': '20260917T000000Z', + 'nvidia_device_nodes_visible': False, + 'cuda_visible_devices': os.environ['CUDA_VISIBLE_DEVICES'], + 'nvidia_visible_devices': os.environ['NVIDIA_VISIBLE_DEVICES'], + 'nvcc': capture('/opt/cuda/bin/nvcc', '--version'), + 'gcc': capture('gcc-13', '--version'), + 'gxx': capture('g++-13', '--version'), + 'cmake': capture('cmake', '--version'), + 'ninja': capture('ninja', '--version'), + 'packages': capture('dpkg-query', '-W', '-f=${Package}=${Version}\\n', + 'ca-certificates', 'cmake', 'gcc-13', 'g++-13', 'git', 'ninja-build', 'python3', 'python3-numpy'), +} +with open(os.environ['LELEKA_TOOLCHAIN_METADATA'], 'w', encoding='utf-8') as stream: + json.dump(data, stream, indent=2) + stream.write('\\n') +PY +scripts/build-static-cuda.sh +install -m 0755 /build/engine/strata "$LELEKA_ENGINE_OUTPUT" +''' + + +def digest(path): + h = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def stage_tracked_source(destination): + changed = subprocess.run(['git', '-C', str(REPO), 'diff', '--quiet', 'HEAD', '--'], check=False) + if changed.returncode == 1: + raise ValueError('refusing to build from a checkout with tracked changes; commit the source first') + if changed.returncode < 0: + raise ValueError('git diff was interrupted while checking the source checkout') + if changed.returncode != 0: + raise subprocess.CalledProcessError(changed.returncode, changed.args) + archive = subprocess.check_output(['git', '-C', str(REPO), 'archive', '--format=tar', 'HEAD']) + with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source: + try: + source.extractall(destination, filter='data') + except (OSError, tarfile.TarError, ValueError) as error: + raise ValueError(f'could not safely stage the committed source tree: {error}') from error + return subprocess.check_output(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], text=True).strip(), hashlib.sha256(archive).hexdigest() + + +def outside_repo(path, label): + resolved = path.resolve() + repo = REPO.resolve() + if resolved == repo or repo in resolved.parents: + raise ValueError(f'{label} must stay outside the source checkout') + if any(char in str(resolved) for char in ',:\n'): + raise ValueError(f'{label} contains a character unsupported in Docker mount paths') + return resolved + + +def run(command): + subprocess.run([str(arg) for arg in command], check=True) + + +def capture(command): + return subprocess.check_output([str(arg) for arg in command], text=True).strip() + + +def build(args): + docker = shutil.which(args.docker) if '/' not in args.docker else args.docker + if not docker: + raise ValueError('Docker CLI is not available') + toolkit = args.toolkit.resolve(strict=True) + if not (toolkit / 'bin/nvcc').is_file() or not (toolkit / 'lib/libcudart_static.a').is_file(): + raise ValueError('toolkit is missing nvcc or static CUDA runtime') + build_dir = outside_repo(args.build_dir, 'build directory') + engine_output = outside_repo(args.output, 'engine output') + metadata_output = outside_repo(args.metadata, 'metadata output') + for path in (toolkit, build_dir, engine_output.parent, metadata_output.parent): + if any(char in str(path) for char in ',:\n'): + raise ValueError('a Docker mount path contains an unsupported character') + output_roots = (engine_output.parent, metadata_output.parent) + if any(build_dir == output or build_dir in output.parents or output in build_dir.parents + for output in output_roots): + raise ValueError('build and output directories must not overlap') + if engine_output.exists() or metadata_output.exists(): + raise ValueError('refusing to overwrite an existing build output') + if build_dir.exists() and any(build_dir.iterdir()): + raise ValueError('build directory must be fresh and empty') + build_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + engine_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + metadata_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + + dockerfile = DOCKERFILE.read_text(encoding='utf-8') + match = re.search(r'^FROM --platform=linux/amd64 (\S+)$', dockerfile, re.M) + if not match or match.group(1) != BASE: + raise ValueError('CUDA builder Dockerfile must use the reviewed immutable amd64 base') + if not re.fullmatch(r'[A-Za-z0-9_.-]{1,46}', args.image_tag): + raise ValueError('invalid image tag') + nonce = uuid.uuid4().hex[:12] + tag = f'leleka-cuda-builder:{args.image_tag}-{nonce}' + image_built = False + container_id = None + staging_container_id = None + volume_names = {kind: f'leleka-cuda-{kind}-{args.image_tag}-{nonce}' for kind in ('source', 'toolkit', 'build')} + owned_volumes = [] + source = build_dir / 'source' + try: + source.mkdir(mode=0o700) + source_commit, source_archive_sha256 = stage_tracked_source(source) + with tempfile.TemporaryDirectory(prefix='leleka-cuda-docker-context-') as context_name: + context = Path(context_name) + image_context = context / 'image' + image_context.mkdir() + shutil.copyfile(DOCKERFILE, image_context / 'Dockerfile') + run([docker, 'build', '--platform', PLATFORM, '--pull', '--file', image_context / 'Dockerfile', + '--label', f'leleka.cuda-builder.run={args.image_tag}', '--tag', tag, image_context]) + image_built = True + image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', tag], text=True).strip() + if not re.fullmatch(r'sha256:[0-9a-f]{64}', image_id): + raise ValueError('Docker returned an invalid builder image ID') + for kind, volume in volume_names.items(): + created = capture([docker, 'volume', 'create', '--label', f'leleka.cuda-builder.run={args.image_tag}', volume]) + if created != volume: + raise ValueError(f'Docker returned an unexpected {kind} volume name') + owned_volumes.append(volume) + staging_container_id = capture([ + docker, 'create', '--platform', PLATFORM, '--network', 'none', + '--label', f'leleka.cuda-builder.run={args.image_tag}', + '--mount', f'type=volume,source={volume_names["source"]},target=/stage/source', + '--mount', f'type=volume,source={volume_names["toolkit"]},target=/stage/toolkit', + '--entrypoint', '/bin/true', tag + ]) + if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', staging_container_id): + raise ValueError('Docker returned an invalid staging container ID') + run([docker, 'cp', f'{source}/.', f'{staging_container_id}:/stage/source']) + run([docker, 'cp', f'{toolkit}/.', f'{staging_container_id}:/stage/toolkit']) + run([docker, 'rm', staging_container_id]) + staging_container_id = None + uid, gid = os.getuid(), os.getgid() + container_id = capture([docker, 'create', '--platform', PLATFORM, '--network', 'bridge', '--read-only', + '--label', f'leleka.cuda-builder.run={args.image_tag}', + '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '512', + '--tmpfs', f'/tmp:rw,nosuid,nodev,size=1g,uid={uid},gid={gid}', '--user', f'{uid}:{gid}', + '--mount', f'type=volume,source={volume_names["source"]},target=/workspace,readonly', + '--mount', f'type=volume,source={volume_names["toolkit"]},target=/opt/cuda,readonly', + '--mount', f'type=volume,source={volume_names["build"]},target=/build', + '--workdir', '/workspace', + '--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + '--env', 'HOME=/tmp/home', '--env', 'CUDA_VISIBLE_DEVICES=', '--env', 'NVIDIA_VISIBLE_DEVICES=void', + '--env', f'LELEKA_BUILDER_BASE={BASE}', '--env', 'LELEKA_ENGINE_OUTPUT=/build/output/strata', + '--env', 'LELEKA_TOOLCHAIN_METADATA=/build/output/CUDA-BUILDER.json', + '--env', 'CUDACXX=/opt/cuda/bin/nvcc', '--env', 'CUDAToolkit_ROOT=/opt/cuda', + '--env', 'CUDAHOSTCXX=/usr/bin/g++-13', '--env', 'CC=/usr/bin/gcc-13', '--env', 'CXX=/usr/bin/g++-13', + '--env', 'STRATA_BUILD_DIR=/build/engine', '--env', 'BUILD_JOBS=1', '--env', 'CUDA_ARCHITECTURES=120', + tag, '-lc', CONTAINER_BUILD]) + if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', container_id): + raise ValueError('Docker returned an invalid build container ID') + run([docker, 'start', '--attach', container_id]) + run([docker, 'cp', f'{container_id}:/build/output/strata', engine_output]) + run([docker, 'cp', f'{container_id}:/build/output/CUDA-BUILDER.json', metadata_output]) + if not engine_output.is_file() or engine_output.is_symlink(): + raise ValueError('Docker build did not produce a regular engine file') + engine_output.chmod(0o755) + container_metadata = json.loads(metadata_output.read_text(encoding='utf-8')) + expected = {'builder_base': BASE, 'builder_platform': PLATFORM, + 'nvidia_device_nodes_visible': False, 'cuda_visible_devices': '', 'nvidia_visible_devices': 'void'} + if any(container_metadata.get(key) != value for key, value in expected.items()): + raise ValueError('container toolchain metadata violates CPU-only builder policy') + metadata = {'schema_version': 1, **container_metadata, 'source_commit': source_commit, + 'source_archive_sha256': source_archive_sha256, 'builder_image_id': image_id, + 'engine_sha256': digest(engine_output), 'engine_bytes': engine_output.stat().st_size, + 'gpu_tested': False, 'model_tested': False, + 'qualification': 'CUDA compilation, ELF dependency audit and GPU-hidden --help only.'} + metadata_output.write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8') + return metadata + finally: + if source.exists(): + shutil.rmtree(source) + for owned_container in (container_id, staging_container_id): + if owned_container: + subprocess.run([docker, 'rm', '--force', owned_container], check=False, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for volume in owned_volumes: + subprocess.run([docker, 'volume', 'rm', '--force', volume], check=False, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if image_built: + subprocess.run([docker, 'image', 'rm', tag], check=False, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--toolkit', type=Path, required=True, help='checksum-verified toolkit from bootstrap-cuda-toolkit.py') + parser.add_argument('--build-dir', type=Path, required=True, help='fresh private directory outside the checkout') + parser.add_argument('--output', type=Path, required=True, help='new engine file path outside the checkout') + parser.add_argument('--metadata', type=Path, required=True, help='new provenance JSON path outside the checkout') + parser.add_argument('--image-tag', required=True, help='unique CI run/attempt suffix for the temporary builder image') + parser.add_argument('--docker', default='docker', help='Docker CLI (used by tests)') + args = parser.parse_args() + try: + result = build(args) + print(json.dumps(result, sort_keys=True)) + except (OSError, ValueError, subprocess.SubprocessError, json.JSONDecodeError) as error: + parser.exit(1, f'Docker CUDA build failed: {error}\n') + + +if __name__ == '__main__': + main() diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 27af6254..53684890 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -3,13 +3,14 @@ set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" +python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" "${repo_root}/scripts/build-cuda-engine-in-docker.py" python3 "${repo_root}/scripts/test-benchmark-harness.py" python3 "${repo_root}/scripts/test-native-service.py" python3 "${repo_root}/scripts/test-native-api.py" python3 "${repo_root}/scripts/test-native-menu.py" python3 "${repo_root}/scripts/test-model-switch.py" python3 "${repo_root}/scripts/test-cuda-bootstrap.py" +python3 "${repo_root}/scripts/test-cuda-docker-builder.py" python3 "${repo_root}/scripts/test-static-cuda-elf.py" python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-runtime-image.py" diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py new file mode 100644 index 00000000..8a32f983 --- /dev/null +++ b/scripts/test-cuda-docker-builder.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""CPU-only contract tests for the Docker CUDA builder wrapper.""" +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +MODULE = Path(__file__).with_name('build-cuda-engine-in-docker.py') +spec = importlib.util.spec_from_file_location('cuda_docker_builder', MODULE) +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +class Tests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='cuda-docker-contract-') + self.root = Path(self.temp.name) + self.source_repo = self.root / 'repo' + (self.source_repo / 'deploy').mkdir(parents=True) + (self.source_repo / 'scripts').mkdir() + shutil.copyfile(builder.DOCKERFILE, self.source_repo / 'deploy/Dockerfile.cuda-builder') + (self.source_repo / 'scripts/build-static-cuda.sh').write_text('#!/bin/sh\nexit 0\n', encoding='utf-8') + (self.source_repo / 'scripts/check-static-cuda-elf.py').write_text('# fixture\n', encoding='utf-8') + subprocess.run(['git', '-C', str(self.source_repo), 'init', '-q'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'config', 'user.email', 'cuda-test@example.invalid'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'config', 'user.name', 'CUDA test'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'add', '-f', 'deploy/Dockerfile.cuda-builder', + 'scripts/build-static-cuda.sh', 'scripts/check-static-cuda-elf.py'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'commit', '-qm', 'fixture'], check=True) + (self.source_repo / '.env').write_text('must not be staged', encoding='utf-8') + self.original_repo = builder.REPO + self.original_dockerfile = builder.DOCKERFILE + builder.REPO = self.source_repo.resolve() + builder.DOCKERFILE = self.source_repo / 'deploy/Dockerfile.cuda-builder' + self.toolkit = self.root / 'toolkit' + (self.toolkit / 'bin').mkdir(parents=True) + (self.toolkit / 'lib').mkdir() + (self.toolkit / 'bin/nvcc').write_text('fixture', encoding='utf-8') + (self.toolkit / 'lib/libcudart_static.a').write_bytes(b'fixture') + self.fake_docker = self.root / 'docker' + self.log = self.root / 'calls.jsonl' + fake = r'''#!/usr/bin/env python3 +import json, pathlib, sys +args=sys.argv[1:] +with open(__LOG_PATH__, 'a') as f: f.write(json.dumps(args)+'\n') +if args[0] == 'build': + dockerfile=pathlib.Path(args[args.index('--file')+1]).read_text() + assert 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' in dockerfile +elif args[:2] == ['image','inspect']: + print('sha256:' + 'a'*64) +elif args[:2] == ['volume','create']: + print(args[-1]) +elif args[0] == 'create': + if '--entrypoint' not in args: + assert '--read-only' in args and '--gpus' not in args and '--device' not in args and '--runtime' not in args + mounts=[args[i+1] for i,x in enumerate(args[:-1]) if x=='--mount'] + assert len(mounts)==3 and all(item.startswith('type=volume,') for item in mounts) + assert any('target=/workspace,readonly' in item for item in mounts) + assert any('target=/opt/cuda,readonly' in item for item in mounts) + assert any('target=/build' in item and 'readonly' not in item for item in mounts) + envs=[args[i+1] for i,x in enumerate(args[:-1]) if x=='--env'] + assert 'CUDA_VISIBLE_DEVICES=' in envs and 'NVIDIA_VISIBLE_DEVICES=void' in envs + print(('a' if '--entrypoint' in args else 'b')*64) +elif args[0] == 'cp': + if args[2].endswith(':/stage/source'): + source=pathlib.Path(args[1][:-2]) + assert (source/'scripts/build-static-cuda.sh').is_file() + assert not (source/'.env').exists() + elif args[2].endswith(':/stage/toolkit'): + source=pathlib.Path(args[1][:-2]) + assert (source/'bin/nvcc').is_file() + elif args[1].endswith(':/build/output/strata'): + pathlib.Path(args[2]).write_bytes(b'fake compiled CUDA engine') + elif args[1].endswith(':/build/output/CUDA-BUILDER.json'): + pathlib.Path(args[2]).write_text(json.dumps({ + 'builder_base':'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b', + 'builder_platform':'linux/amd64','apt_snapshot':'20260917T000000Z', + 'nvidia_device_nodes_visible':False,'cuda_visible_devices':'','nvidia_visible_devices':'void', + 'nvcc':'fixture','gcc':'fixture','gxx':'fixture','cmake':'fixture','ninja':'fixture','packages':'fixture'})) +elif args[0] == 'start': + if pathlib.Path(__FAIL_RUN__).exists(): sys.exit(42) +elif args[0] == 'rm' or args[:2] == ['volume','rm'] or args[:2] == ['image','rm']: + pass +else: + raise AssertionError(args) +'''.replace('__LOG_PATH__', json.dumps(str(self.log))) + self.fake_docker.write_text(fake.replace('__FAIL_RUN__', json.dumps(str(self.root / 'fail-run'))), encoding='utf-8') + self.fake_docker.chmod(0o755) + + def tearDown(self): + builder.REPO = self.original_repo + builder.DOCKERFILE = self.original_dockerfile + self.temp.cleanup() + + def arguments(self, **overrides): + from argparse import Namespace + values = dict(toolkit=self.toolkit, + build_dir=self.root / 'build', + output=self.root / 'out' / 'strata', + metadata=self.root / 'out' / 'CUDA-BUILDER.json', + image_tag='test-1', docker=str(self.fake_docker)) + values.update(overrides) + return Namespace(**values) + + def docker_calls(self): + return [json.loads(line) for line in self.log.read_text().splitlines()] + + def test_container_build_has_pinned_cpu_only_invocation(self): + result = builder.build(self.arguments()) + self.assertEqual(result['builder_base'], builder.BASE) + self.assertFalse(result['gpu_tested']) + self.assertEqual(result['source_commit'], subprocess.check_output( + ['git', '-C', str(self.source_repo), 'rev-parse', 'HEAD'], text=True).strip()) + self.assertEqual(result['engine_sha256'], builder.digest(self.root / 'out/strata')) + calls = self.docker_calls() + build = next(args for args in calls if args[0] == 'build') + container = next(args for args in calls if args[0] == 'create' and '--entrypoint' not in args) + self.assertEqual(build[build.index('--platform')+1], 'linux/amd64') + self.assertEqual(container[container.index('--platform')+1], 'linux/amd64') + self.assertNotIn('--gpus', container) + self.assertIn(['rm', '--force', 'b'*64], calls) + self.assertTrue(any(call[:2] == ['volume', 'rm'] for call in calls)) + self.assertEqual(calls[-1][:2], ['image','rm']) + subprocess.run(['bash','-n','-c',builder.CONTAINER_BUILD], check=True) + + def test_owned_docker_resources_are_removed_when_build_fails(self): + (self.root / 'fail-run').touch() + with self.assertRaises(subprocess.CalledProcessError): + builder.build(self.arguments()) + calls = self.docker_calls() + self.assertIn(['rm', '--force', 'b'*64], calls) + self.assertEqual(calls[-1][:2], ['image', 'rm']) + + def test_refuses_output_inside_source_checkout_before_docker(self): + with self.assertRaisesRegex(ValueError, 'outside the source checkout'): + builder.build(self.arguments(output=self.source_repo / 'artifacts/strata')) + self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '') + + def test_refuses_existing_output(self): + output = self.root / 'existing' + output.mkdir() + (output / 'strata').write_bytes(b'keep') + with self.assertRaisesRegex(ValueError, 'refusing to overwrite'): + builder.build(self.arguments(output=output / 'strata')) + self.assertEqual((output / 'strata').read_bytes(), b'keep') + self.assertFalse(self.log.exists()) + + def test_refuses_overlapping_build_and_output_directories(self): + with self.assertRaisesRegex(ValueError, 'must not overlap'): + builder.build(self.arguments(build_dir=self.root / 'out')) + self.assertFalse(self.log.exists()) + + def test_rejects_changed_builder_base_before_docker(self): + with tempfile.TemporaryDirectory() as d: + bad = Path(d) / 'Dockerfile' + bad.write_text('FROM ubuntu:latest\n', encoding='utf-8') + old = builder.DOCKERFILE + builder.DOCKERFILE = bad + try: + with self.assertRaisesRegex(ValueError, 'immutable amd64 base'): + builder.build(self.arguments()) + finally: + builder.DOCKERFILE = old + self.assertFalse(self.log.exists()) + + def test_refuses_tracked_source_changes_before_docker(self): + (self.source_repo / 'scripts/build-static-cuda.sh').write_text('#!/bin/sh\necho modified\n', encoding='utf-8') + diff = subprocess.run(['git', '-C', str(self.source_repo), 'diff', '--quiet', 'HEAD', '--'], check=False) + self.assertEqual(diff.returncode, 1) + with self.assertRaisesRegex(ValueError, 'tracked changes'): + builder.build(self.arguments()) + self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '') + + def test_manual_cuda_job_uses_generic_linux_and_no_artifact_action(self): + workflow = (self.original_repo / '.github/workflows/linux.yml').read_text(encoding='utf-8') + job = workflow.split(' hosted-cuda-package:', 1)[1].split('\n linux-static-cli:', 1)[0] + self.assertIn('runs-on: ubuntu-latest', job) + self.assertIn('scripts/build-cuda-engine-in-docker.py', job) + self.assertIn('gh release create', job) + self.assertNotIn('strata-gpu', job) + self.assertNotIn('actions/upload-artifact', job) + self.assertNotIn('static_cuda_package', workflow) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From 2833a86482208e8a6cf37814bb1518218b31bf71 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 02:06:04 +0200 Subject: [PATCH 20/58] fix: extract CUDA build source on runner Python --- scripts/build-cuda-engine-in-docker.py | 53 +++++++++++++++++++++++--- scripts/test-cuda-docker-builder.py | 22 +++++++++++ 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py index 77828a47..95fa96b7 100644 --- a/scripts/build-cuda-engine-in-docker.py +++ b/scripts/build-cuda-engine-in-docker.py @@ -6,6 +6,7 @@ from io import BytesIO import json import os from pathlib import Path +from pathlib import PurePosixPath import re import shutil import subprocess @@ -66,6 +67,49 @@ def digest(path): return h.hexdigest() +def extract_git_archive(archive, destination): + """Extract only regular files/directories from git archive on old and new Python.""" + root = destination.resolve() + with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source: + members = source.getmembers() + seen = set() + checked = [] + for member in members: + name = member.name + normalized_name = name.rstrip('/') if member.isdir() else name + path = PurePosixPath(normalized_name) + if (not normalized_name or path.is_absolute() or + any(part in ('', '.', '..') for part in normalized_name.split('/'))): + raise ValueError(f'unsafe path in committed source archive: {name!r}') + if not (member.isdir() or member.isfile()): + raise ValueError(f'unsupported entry in committed source archive: {name!r}') + target = root.joinpath(*path.parts) + if target == root or root not in target.parents: + raise ValueError(f'archive path escapes staging directory: {name!r}') + if path in seen: + raise ValueError(f'duplicate path in committed source archive: {name!r}') + seen.add(path) + checked.append((member, path, target)) + + directories = {root} + for member, path, target in checked: + if member.isdir(): + directories.add(target) + continue + directories.update(parent for parent in target.parents if parent == root or root in parent.parents) + target.parent.mkdir(mode=0o755, parents=True, exist_ok=True) + payload = source.extractfile(member) + if payload is None: + raise ValueError(f'missing file payload in committed source archive: {member.name!r}') + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0) + fd = os.open(target, flags, member.mode & 0o777 & ~0o6000) + with os.fdopen(fd, 'wb') as output, payload: + shutil.copyfileobj(payload, output) + for directory in sorted(directories, key=lambda item: len(item.parts), reverse=True): + if directory.is_dir(): + directory.chmod(0o755) + + def stage_tracked_source(destination): changed = subprocess.run(['git', '-C', str(REPO), 'diff', '--quiet', 'HEAD', '--'], check=False) if changed.returncode == 1: @@ -75,11 +119,10 @@ def stage_tracked_source(destination): if changed.returncode != 0: raise subprocess.CalledProcessError(changed.returncode, changed.args) archive = subprocess.check_output(['git', '-C', str(REPO), 'archive', '--format=tar', 'HEAD']) - with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source: - try: - source.extractall(destination, filter='data') - except (OSError, tarfile.TarError, ValueError) as error: - raise ValueError(f'could not safely stage the committed source tree: {error}') from error + try: + extract_git_archive(archive, destination) + except (OSError, tarfile.TarError, ValueError) as error: + raise ValueError(f'could not safely stage the committed source tree: {error}') from error return subprocess.check_output(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], text=True).strip(), hashlib.sha256(archive).hexdigest() diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 8a32f983..b79e3572 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -1,11 +1,13 @@ #!/usr/bin/env python3 """CPU-only contract tests for the Docker CUDA builder wrapper.""" import importlib.util +from io import BytesIO import json from pathlib import Path import shutil import subprocess import tempfile +import tarfile import unittest MODULE = Path(__file__).with_name('build-cuda-engine-in-docker.py') @@ -174,6 +176,26 @@ else: builder.build(self.arguments()) self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '') + def test_archive_extraction_rejects_parent_paths_and_symlinks(self): + for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)): + with self.subTest(name=name): + archive = BytesIO() + with tarfile.open(fileobj=archive, mode='w:') as output: + entry = tarfile.TarInfo(name) + entry.type = kind + entry.linkname = '../outside' + if kind == tarfile.REGTYPE: + entry.size = 1 + output.addfile(entry, BytesIO(b'x')) + else: + output.addfile(entry) + destination = self.root / f"safe-stage-{name.replace('/', '_')}" + destination.mkdir() + with self.assertRaisesRegex(ValueError, 'unsafe path|unsupported entry'): + builder.extract_git_archive(archive.getvalue(), destination) + self.assertEqual(list(destination.iterdir()), []) + self.assertFalse((self.root / 'escape').exists()) + def test_manual_cuda_job_uses_generic_linux_and_no_artifact_action(self): workflow = (self.original_repo / '.github/workflows/linux.yml').read_text(encoding='utf-8') job = workflow.split(' hosted-cuda-package:', 1)[1].split('\n linux-static-cli:', 1)[0] -- 2.54.0 From 27b02c8b1158a120dcbd0484611e934686c43a4b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 03:26:56 +0200 Subject: [PATCH 21/58] fix: handle missing CUDA archive modes on Python 3.11 --- scripts/bootstrap-cuda-toolkit.py | 27 ++++++++++++++++----------- scripts/test-cuda-bootstrap.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/scripts/bootstrap-cuda-toolkit.py b/scripts/bootstrap-cuda-toolkit.py index d4e95b86..263aae7d 100644 --- a/scripts/bootstrap-cuda-toolkit.py +++ b/scripts/bootstrap-cuda-toolkit.py @@ -94,17 +94,22 @@ def safe_data_filter(member, destination): filtered = copy.copy(member) mode = member.mode - if mode is not None: - mode &= 0o755 - if member.isreg() or member.islnk(): - if not mode & 0o100: - mode &= ~0o111 - mode |= 0o600 - elif member.isdir() or member.issym(): - mode = None - else: - raise ValueError('unsupported special archive member') - filtered.mode = mode + # Python 3.11's extractall() chmod path passes mode straight to os.chmod, + # so ``None`` (the data-filter convention for directories/symlinks) crashes. + # Give directories owner-only traversal/write permissions; this preserves + # the filter's security intent while remaining compatible with old tarfile. + if member.isdir(): + mode = 0o700 + elif member.isreg() or member.islnk(): + mode = 0o600 if mode is None else mode & 0o755 + if not mode & 0o100: + mode &= ~0o111 + mode |= 0o600 + elif member.issym(): + mode = None + else: + raise ValueError('unsupported special archive member') + filtered.mode = mode filtered.uid = filtered.gid = None filtered.uname = filtered.gname = None diff --git a/scripts/test-cuda-bootstrap.py b/scripts/test-cuda-bootstrap.py index 1302b978..df736e84 100644 --- a/scripts/test-cuda-bootstrap.py +++ b/scripts/test-cuda-bootstrap.py @@ -30,6 +30,24 @@ class Tests(unittest.TestCase): with tarfile.open(archive,'r:xz') as source: m.extract_members(source,dest,source.getmembers(),supports_filter=False) self.assertEqual((dest/'component/lib/b').read_bytes(),b'a') + def test_python311_fallback_accepts_members_without_mode(self): + # NVIDIA component archives can contain directory/file entries without + # a mode. The legacy tarfile chmod path must never receive None. + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out' + with tarfile.open(archive,'w:xz') as t: + directory=tarfile.TarInfo('component/include');directory.type=tarfile.DIRTYPE;t.addfile(directory) + item=tarfile.TarInfo('component/include/header.h');item.size=1;t.addfile(item,io.BytesIO(b'h')) + with tarfile.open(archive,'r:xz') as source: + members=source.getmembers() + for member in members:member.mode=None + # Emulate old extractall()'s fully-trusted default after the + # caller's explicit data-policy validation has run. + with patch.object(source,'extraction_filter',tarfile.fully_trusted_filter,create=True): + m.extract_members(source,dest,members,supports_filter=False) + self.assertEqual((dest/'component/include/header.h').read_bytes(),b'h') + self.assertEqual((dest/'component/include').stat().st_mode & 0o777,0o700) + self.assertEqual((dest/'component/include/header.h').stat().st_mode & 0o777,0o600) def test_python311_style_fallback_rejects_escaping_link(self): with tempfile.TemporaryDirectory() as tmp: root=Path(tmp);archive=root/'test.tar.xz';dest=root/'out' -- 2.54.0 From f245abc53228b8ea9efab72d0dbc29a180dc1379 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 03:51:34 +0200 Subject: [PATCH 22/58] test: keep CUDA archive regression Python 3.11 compatible --- scripts/test-cuda-bootstrap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-cuda-bootstrap.py b/scripts/test-cuda-bootstrap.py index df736e84..2de171a2 100644 --- a/scripts/test-cuda-bootstrap.py +++ b/scripts/test-cuda-bootstrap.py @@ -43,7 +43,7 @@ class Tests(unittest.TestCase): for member in members:member.mode=None # Emulate old extractall()'s fully-trusted default after the # caller's explicit data-policy validation has run. - with patch.object(source,'extraction_filter',tarfile.fully_trusted_filter,create=True): + with patch.object(source,'extraction_filter',lambda member,path: member,create=True): m.extract_members(source,dest,members,supports_filter=False) self.assertEqual((dest/'component/include/header.h').read_bytes(),b'h') self.assertEqual((dest/'component/include').stat().st_mode & 0o777,0o700) -- 2.54.0 From be8f66f96140542e1b3789f768baf00bad80b92a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 04:23:48 +0200 Subject: [PATCH 23/58] ci: isolate hosted CUDA build metadata output --- .github/workflows/linux.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 9de32def..c756bb4b 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -88,7 +88,7 @@ jobs: --toolkit "$CUDAToolkit_ROOT" \ --build-dir "$RUNNER_TEMP/strata-hosted-cuda-build" \ --output "$STRATA_BUILD_DIR/strata" \ - --metadata "$RUNNER_TEMP/CUDA-BUILDER.json" \ + --metadata "$RUNNER_TEMP/strata-hosted-cuda-metadata/CUDA-BUILDER.json" \ --image-tag "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - name: Install pinned Rust and musl target run: | @@ -119,7 +119,7 @@ jobs: image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")" docker save --output "$package/runtime-image.tar" "$image" cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json" - python3 - "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$RUNNER_TEMP/CUDA-BUILDER.json" "$package/CUDA-TOOLCHAIN.json" <<'PYTOOL' + python3 - "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$RUNNER_TEMP/strata-hosted-cuda-metadata/CUDA-BUILDER.json" "$package/CUDA-TOOLCHAIN.json" <<'PYTOOL' import json, sys from pathlib import Path bootstrap=json.loads(Path(sys.argv[1]).read_text()) @@ -157,7 +157,7 @@ jobs: docker volume ls -q --filter "label=$builder_label" | xargs -r docker volume rm --force || true docker image ls -q --filter "label=$builder_label" | sort -u | xargs -r docker image rm || true fi - rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-cuda-build" "$RUNNER_TEMP/strata-hosted-package-build" + rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-cuda-build" "$RUNNER_TEMP/strata-hosted-cuda-metadata" "$RUNNER_TEMP/strata-hosted-package-build" linux-static-cli: needs: verify -- 2.54.0 From f7d273e5600aace3a468f4337b336874bb7a5434 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 04:43:05 +0200 Subject: [PATCH 24/58] test: account for proc fd reuse in embedded payload check --- control-plane/src/embedded_engine.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/control-plane/src/embedded_engine.rs b/control-plane/src/embedded_engine.rs index 05c0cb30..19544e6a 100644 --- a/control-plane/src/embedded_engine.rs +++ b/control-plane/src/embedded_engine.rs @@ -119,15 +119,25 @@ mod tests { #[test] fn sealed_payload_is_exact_immutable_and_removed_on_drop() { use std::io::Write; + use std::os::unix::fs::MetadataExt; let engine = materialize(b"immutable fixture bytes").unwrap(); let path = engine.executable.clone(); assert_eq!(std::fs::read(&path).unwrap(), b"immutable fixture bytes"); + let metadata = std::fs::metadata(&path).unwrap(); + let identity = (metadata.dev(), metadata.ino()); let mut other = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); assert!(other.write_all(b"x").is_err()); assert!(other.set_len(0).is_err()); assert!(other.set_len(100).is_err()); drop(other); drop(engine); - assert!(!path.exists()); + // The path names a process fd, not a persistent file. Rust tests run + // concurrently, so another test can reuse that fd number immediately + // after drop; assert the original memfd identity disappeared instead. + match std::fs::metadata(&path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Ok(after) => assert_ne!((after.dev(), after.ino()), identity), + Err(error) => panic!("unexpected fd path metadata error: {error}"), + } } } -- 2.54.0 From f4dbcfd53e6f6e5573f66494d8331600c55d5e46 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 05:13:37 +0200 Subject: [PATCH 25/58] fix: seed CA trust for pinned CUDA Docker build --- deploy/Dockerfile.cuda-builder | 4 ++++ scripts/build-cuda-engine-in-docker.py | 24 +++++++++++++++++++++- scripts/test-cuda-docker-builder.py | 28 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/deploy/Dockerfile.cuda-builder b/deploy/Dockerfile.cuda-builder index 439c6038..d5b21524 100644 --- a/deploy/Dockerfile.cuda-builder +++ b/deploy/Dockerfile.cuda-builder @@ -2,6 +2,10 @@ FROM --platform=linux/amd64 ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085 ENV DEBIAN_FRONTEND=noninteractive +# The minimal pinned Ubuntu base has no CA store. Seed it from the trusted +# Linux CI runner so HTTPS verification works before apt installs ca-certificates. +COPY runner-ca-certificates.crt /etc/ssl/certs/ca-certificates.crt + # Freeze Ubuntu's package view as well as the base-image digest. CUDA itself is # supplied separately by the checksum-pinned redistributable bundle. RUN rm -f /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list && \ diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py index 95fa96b7..c687b02c 100644 --- a/scripts/build-cuda-engine-in-docker.py +++ b/scripts/build-cuda-engine-in-docker.py @@ -9,6 +9,7 @@ from pathlib import Path from pathlib import PurePosixPath import re import shutil +import ssl import subprocess import tarfile import tempfile @@ -144,6 +145,23 @@ def capture(command): return subprocess.check_output([str(arg) for arg in command], text=True).strip() +def runner_ca_bundle(): + """Return the runner's CA bundle for bootstrapping HTTPS in the base image.""" + cafile = ssl.get_default_verify_paths().cafile + if not cafile: + raise ValueError('Linux runner has no default CA bundle path') + try: + path = Path(cafile).resolve(strict=True) + except OSError as error: + raise ValueError('Linux runner CA bundle is missing or unreadable') from error + if not path.is_file(): + raise ValueError('Linux runner CA bundle is not a regular file') + contents = path.read_bytes() + if not contents or b'-----BEGIN CERTIFICATE-----' not in contents: + raise ValueError('Linux runner CA bundle is empty or invalid') + return contents + + def build(args): docker = shutil.which(args.docker) if '/' not in args.docker else args.docker if not docker: @@ -186,11 +204,14 @@ def build(args): try: source.mkdir(mode=0o700) source_commit, source_archive_sha256 = stage_tracked_source(source) + ca_bundle = runner_ca_bundle() + ca_bundle_sha256 = hashlib.sha256(ca_bundle).hexdigest() with tempfile.TemporaryDirectory(prefix='leleka-cuda-docker-context-') as context_name: context = Path(context_name) image_context = context / 'image' image_context.mkdir() shutil.copyfile(DOCKERFILE, image_context / 'Dockerfile') + (image_context / 'runner-ca-certificates.crt').write_bytes(ca_bundle) run([docker, 'build', '--platform', PLATFORM, '--pull', '--file', image_context / 'Dockerfile', '--label', f'leleka.cuda-builder.run={args.image_tag}', '--tag', tag, image_context]) image_built = True @@ -246,7 +267,8 @@ def build(args): if any(container_metadata.get(key) != value for key, value in expected.items()): raise ValueError('container toolchain metadata violates CPU-only builder policy') metadata = {'schema_version': 1, **container_metadata, 'source_commit': source_commit, - 'source_archive_sha256': source_archive_sha256, 'builder_image_id': image_id, + 'source_archive_sha256': source_archive_sha256, + 'runner_ca_bundle_sha256': ca_bundle_sha256, 'builder_image_id': image_id, 'engine_sha256': digest(engine_output), 'engine_bytes': engine_output.stat().st_size, 'gpu_tested': False, 'model_tested': False, 'qualification': 'CUDA compilation, ELF dependency audit and GPU-hidden --help only.'} diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index b79e3572..6897925a 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -1,14 +1,17 @@ #!/usr/bin/env python3 """CPU-only contract tests for the Docker CUDA builder wrapper.""" import importlib.util +import hashlib from io import BytesIO import json from pathlib import Path import shutil import subprocess +from types import SimpleNamespace import tempfile import tarfile import unittest +from unittest.mock import patch MODULE = Path(__file__).with_name('build-cuda-engine-in-docker.py') spec = importlib.util.spec_from_file_location('cuda_docker_builder', MODULE) @@ -33,8 +36,12 @@ class Tests(unittest.TestCase): 'scripts/build-static-cuda.sh', 'scripts/check-static-cuda-elf.py'], check=True) subprocess.run(['git', '-C', str(self.source_repo), 'commit', '-qm', 'fixture'], check=True) (self.source_repo / '.env').write_text('must not be staged', encoding='utf-8') + self.original_runner_ca_bundle = builder.runner_ca_bundle self.original_repo = builder.REPO self.original_dockerfile = builder.DOCKERFILE + self.ca_bundle = b'-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n' + self.ca_patch = patch.object(builder, 'runner_ca_bundle', return_value=self.ca_bundle) + self.ca_patch.start() builder.REPO = self.source_repo.resolve() builder.DOCKERFILE = self.source_repo / 'deploy/Dockerfile.cuda-builder' self.toolkit = self.root / 'toolkit' @@ -50,7 +57,10 @@ args=sys.argv[1:] with open(__LOG_PATH__, 'a') as f: f.write(json.dumps(args)+'\n') if args[0] == 'build': dockerfile=pathlib.Path(args[args.index('--file')+1]).read_text() + context=pathlib.Path(args[-1]) assert 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' in dockerfile + assert (context/'runner-ca-certificates.crt').is_file() + assert 'COPY runner-ca-certificates.crt /etc/ssl/certs/ca-certificates.crt' in dockerfile elif args[:2] == ['image','inspect']: print('sha256:' + 'a'*64) elif args[:2] == ['volume','create']: @@ -93,6 +103,7 @@ else: self.fake_docker.chmod(0o755) def tearDown(self): + self.ca_patch.stop() builder.REPO = self.original_repo builder.DOCKERFILE = self.original_dockerfile self.temp.cleanup() @@ -110,6 +121,22 @@ else: def docker_calls(self): return [json.loads(line) for line in self.log.read_text().splitlines()] + def test_runner_ca_bundle_resolves_a_default_symlink(self): + pem = self.root / 'runner-ca.pem' + pem.write_bytes(self.ca_bundle) + link = self.root / 'runner-ca-link.pem' + link.symlink_to(pem) + with patch.object(builder.ssl, 'get_default_verify_paths', + return_value=SimpleNamespace(cafile=str(link))): + self.assertEqual(self.original_runner_ca_bundle(), self.ca_bundle) + + def test_runner_ca_bundle_rejects_missing_path(self): + missing = self.root / 'missing-ca.pem' + with patch.object(builder.ssl, 'get_default_verify_paths', + return_value=SimpleNamespace(cafile=str(missing))): + with self.assertRaisesRegex(ValueError, 'missing or unreadable'): + self.original_runner_ca_bundle() + def test_container_build_has_pinned_cpu_only_invocation(self): result = builder.build(self.arguments()) self.assertEqual(result['builder_base'], builder.BASE) @@ -126,6 +153,7 @@ else: self.assertIn(['rm', '--force', 'b'*64], calls) self.assertTrue(any(call[:2] == ['volume', 'rm'] for call in calls)) self.assertEqual(calls[-1][:2], ['image','rm']) + self.assertEqual(result['runner_ca_bundle_sha256'], hashlib.sha256(self.ca_bundle).hexdigest()) subprocess.run(['bash','-n','-c',builder.CONTAINER_BUILD], check=True) def test_owned_docker_resources_are_removed_when_build_fails(self): -- 2.54.0 From 00f04de5a76206a1d7ee1847c2d055c2d4790acf Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 05:21:34 +0200 Subject: [PATCH 26/58] fix: install make in CUDA builder image --- deploy/Dockerfile.cuda-builder | 2 +- scripts/build-cuda-engine-in-docker.py | 3 ++- scripts/test-cuda-docker-builder.py | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/deploy/Dockerfile.cuda-builder b/deploy/Dockerfile.cuda-builder index d5b21524..d1766704 100644 --- a/deploy/Dockerfile.cuda-builder +++ b/deploy/Dockerfile.cuda-builder @@ -16,7 +16,7 @@ RUN rm -f /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list && \ > /etc/apt/sources.list && \ apt-get -o Acquire::Check-Valid-Until=false update && \ apt-get install -y --no-install-recommends \ - ca-certificates cmake gcc-13 g++-13 git ninja-build python3 python3-numpy && \ + ca-certificates cmake gcc-13 g++-13 git make ninja-build python3 python3-numpy && \ rm -rf /var/lib/apt/lists/* && \ test "$(gcc-13 -dumpfullversion | cut -d. -f1)" = 13 && \ mkdir -p /stage/source /stage/toolkit /build && chmod 1777 /build diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py index c687b02c..fe765442 100644 --- a/scripts/build-cuda-engine-in-docker.py +++ b/scripts/build-cuda-engine-in-docker.py @@ -48,8 +48,9 @@ data = { 'gxx': capture('g++-13', '--version'), 'cmake': capture('cmake', '--version'), 'ninja': capture('ninja', '--version'), + 'make': capture('make', '--version'), 'packages': capture('dpkg-query', '-W', '-f=${Package}=${Version}\\n', - 'ca-certificates', 'cmake', 'gcc-13', 'g++-13', 'git', 'ninja-build', 'python3', 'python3-numpy'), + 'ca-certificates', 'cmake', 'gcc-13', 'g++-13', 'git', 'make', 'ninja-build', 'python3', 'python3-numpy'), } with open(os.environ['LELEKA_TOOLCHAIN_METADATA'], 'w', encoding='utf-8') as stream: json.dump(data, stream, indent=2) diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 6897925a..86be5812 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -61,6 +61,7 @@ if args[0] == 'build': assert 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' in dockerfile assert (context/'runner-ca-certificates.crt').is_file() assert 'COPY runner-ca-certificates.crt /etc/ssl/certs/ca-certificates.crt' in dockerfile + assert 'ca-certificates cmake gcc-13 g++-13 git make ninja-build' in dockerfile elif args[:2] == ['image','inspect']: print('sha256:' + 'a'*64) elif args[:2] == ['volume','create']: -- 2.54.0 From 4125a0305ffe19c173598a6f31400a693d68e474 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 05:51:30 +0200 Subject: [PATCH 27/58] fix: emit valid CUDA toolchain metadata JSON --- scripts/build-cuda-engine-in-docker.py | 2 +- scripts/test-cuda-docker-builder.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py index fe765442..0d02cf2e 100644 --- a/scripts/build-cuda-engine-in-docker.py +++ b/scripts/build-cuda-engine-in-docker.py @@ -54,7 +54,7 @@ data = { } with open(os.environ['LELEKA_TOOLCHAIN_METADATA'], 'w', encoding='utf-8') as stream: json.dump(data, stream, indent=2) - stream.write('\\n') + stream.write(chr(10)) PY scripts/build-static-cuda.sh install -m 0755 /build/engine/strata "$LELEKA_ENGINE_OUTPUT" diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 86be5812..360908c3 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -139,6 +139,7 @@ else: self.original_runner_ca_bundle() def test_container_build_has_pinned_cpu_only_invocation(self): + self.assertIn('stream.write(chr(10))', builder.CONTAINER_BUILD) result = builder.build(self.arguments()) self.assertEqual(result['builder_base'], builder.BASE) self.assertFalse(result['gpu_tested']) -- 2.54.0 From 70f99ba63ee7ccf6bba27890881c69d3b1ba88b9 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 06:06:05 +0200 Subject: [PATCH 28/58] fix: install GNU time for CUDA packaging job --- .github/workflows/linux.yml | 2 +- scripts/test-cuda-docker-builder.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index c756bb4b..d1ca0421 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -67,7 +67,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && apt-get install -y ca-certificates curl docker.io gh musl-tools binutils python3-numpy + apt-get update && apt-get install -y ca-certificates curl docker.io gh musl-tools binutils python3-numpy time - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Record actual toolchain diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 360908c3..e59f2620 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -232,6 +232,8 @@ else: self.assertIn('runs-on: ubuntu-latest', job) self.assertIn('scripts/build-cuda-engine-in-docker.py', job) self.assertIn('gh release create', job) + self.assertRegex(job, r'apt-get install -y .*\btime\b') + self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job) self.assertNotIn('strata-gpu', job) self.assertNotIn('actions/upload-artifact', job) self.assertNotIn('static_cuda_package', workflow) -- 2.54.0 From 7446c70dfac45d239dda1ded69a44e0dbd118854 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 06:41:34 +0200 Subject: [PATCH 29/58] fix: probe CUDA engine in compatible runtime image --- .github/workflows/linux.yml | 3 ++- scripts/build-linux-package.py | 24 +++++++++++++++++++---- scripts/build-runtime-image.py | 5 ++++- scripts/test-cuda-docker-builder.py | 2 ++ scripts/test-linux-package.py | 26 +++++++++++++++++++++++++ scripts/test-runtime-image.py | 30 +++++++++++++++++++++++++++++ 6 files changed, 84 insertions(+), 6 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index d1ca0421..962ba6f1 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -112,7 +112,8 @@ jobs: package="$RUNNER_TEMP/strata-hosted-cuda-package" /usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \ --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" + --cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" \ + --defer-engine-help-probe-to-runtime-image python3 scripts/build-runtime-image.py --package "$package" \ --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ > "$RUNNER_TEMP/strata-hosted-image.json" diff --git a/scripts/build-linux-package.py b/scripts/build-linux-package.py index 5688d067..213b3e53 100644 --- a/scripts/build-linux-package.py +++ b/scripts/build-linux-package.py @@ -68,6 +68,15 @@ def static_outer(binary): return {'program_headers': headers, 'dynamic_section': dynamic} +def probe_engine_help(binary, stage, env, *, defer_to_runtime_image): + if defer_to_runtime_image: + return 'deferred-to-runtime-image' + probe = stage / 'probe.json' + probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True})) + run([binary, 'provision', '--config', probe], env=env, timeout=30) + return 'passed-on-package-builder-host' + + @contextlib.contextmanager def lock(path): # Caller-controlled build/output paths are private; keep the inode for reuse. @@ -95,6 +104,9 @@ def publish(source, output): def assemble(args): if platform.system() != 'Linux' or platform.machine() != 'x86_64': raise ValueError('package assembly requires Linux x86_64') + defer_help = getattr(args, 'defer_engine_help_probe_to_runtime_image', False) + if defer_help and args.cpu_fixture: + raise ValueError('only CUDA package builds may defer the loader probe to the runtime image') source_check(REPO, args.revision) output = args.output.absolute() output.parent.mkdir(parents=True, exist_ok=True) @@ -137,17 +149,19 @@ def assemble(args): info['declared_source_revision'] == args.revision and info['bytes'] == size and info['target_os'] == 'linux' and info['target_arch'] == 'x86_64'): raise ValueError('combined engine identity does not match pinned input') - probe = stage / 'probe.json' - probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True})) - run([binary, 'provision', '--config', probe], env=probe_env, timeout=30) + help_probe = probe_engine_help(binary, stage, probe_env, + defer_to_runtime_image=defer_help) source_check(REPO, args.revision) provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview', 'source_revision': args.revision, 'target': TARGET, 'engine': info, + 'engine_help_probe': help_probe, 'engine_elf_audit': audit, 'outer_elf_audit': outer, 'cargo_lock_sha256': sha256(REPO / 'control-plane/Cargo.lock'), 'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']), 'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False, - 'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.', + 'qualification': ('Exact payload identity and outer ELF; loader help is verified in the compatible runtime image; no inference.' + if help_probe == 'deferred-to-runtime-image' else + 'Exact payload identity, outer ELF and GPU-hidden loader help on package builder host; no inference.'), 'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'} (published / 'PROVENANCE.json').write_text(json.dumps(provenance, indent=2) + '\n') (published / 'SHA256SUMS').write_text(''.join(f'{sha256(p)} {p.name}\n' for p in [binary, published / 'PROVENANCE.json'])) @@ -165,6 +179,8 @@ def main(): parser.add_argument('--output', type=Path, required=True) parser.add_argument('--cargo-target-dir', type=Path, required=True, help='dedicated build directory; do not run other Cargo commands here concurrently') parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release') + parser.add_argument('--defer-engine-help-probe-to-runtime-image', action='store_true', + help='run the embedded engine loader probe only in the final runtime image, for CUDA engines with a newer glibc floor than the build host') args = parser.parse_args() try: print(json.dumps(assemble(args))) diff --git a/scripts/build-runtime-image.py b/scripts/build-runtime-image.py index bfe4d491..9929be2c 100644 --- a/scripts/build-runtime-image.py +++ b/scripts/build-runtime-image.py @@ -70,6 +70,8 @@ def freeze(package, stage, receipt_sha, cpu_fixture): not re.fullmatch(r'[0-9a-f]{64}', engine.get('sha256', ''))): raise ValueError('invalid embedded engine identity') if not cpu_fixture: + if p.get('engine_help_probe') != 'deferred-to-runtime-image': + raise ValueError('CUDA package must defer loader help until the compatible runtime image') audit = p.get('engine_elf_audit', {}) if audit.get('toolkit_shared_libraries') is not False or audit.get('host_glibc_required') is not True: raise ValueError('missing static CUDA ELF audit') @@ -138,7 +140,8 @@ def assemble(args): isolated_run(image, ['engine-help']) result = {'schema_version': 1, 'image': image, 'base': args.base, 'base_glibc': glibc, 'package_receipt_sha256': args.receipt_sha256, 'source_revision': p['source_revision'], - 'kind': p['kind'], 'gpu_tested': False, 'model_tested': False, + 'kind': p['kind'], 'engine_help_probe': 'passed-in-runtime-image', + 'gpu_tested': False, 'model_tested': False, 'qualification': 'Non-root GPU-hidden embedded identity and loader help only.'} success = True return result diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index e59f2620..d94b911b 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -234,6 +234,8 @@ else: self.assertIn('gh release create', job) self.assertRegex(job, r'apt-get install -y .*\btime\b') self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job) + self.assertIn('--defer-engine-help-probe-to-runtime-image', job) + self.assertIn('scripts/build-runtime-image.py --package', job) self.assertNotIn('strata-gpu', job) self.assertNotIn('actions/upload-artifact', job) self.assertNotIn('static_cuda_package', workflow) diff --git a/scripts/test-linux-package.py b/scripts/test-linux-package.py index 13e931a7..d756dad0 100644 --- a/scripts/test-linux-package.py +++ b/scripts/test-linux-package.py @@ -76,6 +76,20 @@ class PackageTests(unittest.TestCase): with pkg.lock(alias): self.fail('symlink lock accepted') + def test_cuda_loader_probe_can_be_deferred_only_as_declared(self): + probe_binary = self.root / 'strata-next' + stage = self.root / 'stage' + stage.mkdir() + with patch.object(pkg, 'run') as run: + self.assertEqual(pkg.probe_engine_help(probe_binary, stage, {}, defer_to_runtime_image=True), + 'deferred-to-runtime-image') + run.assert_not_called() + with patch.object(pkg, 'run') as run: + self.assertEqual(pkg.probe_engine_help(probe_binary, stage, {}, defer_to_runtime_image=False), + 'passed-on-package-builder-host') + run.assert_called_once() + self.assertTrue((stage / 'probe.json').is_file()) + @unittest.skipUnless(sys.platform == 'linux', 'Linux atomic publication') def test_atomic_publication_never_replaces_existing_directory(self): staged, output = self.root / 'stage', self.root / 'out' @@ -117,6 +131,18 @@ class PackageTests(unittest.TestCase): build.assert_not_called() self.assertEqual((output / 'old').read_text(), 'keep') + def test_cpu_fixture_cannot_defer_loader_probe(self): + from types import SimpleNamespace + args = SimpleNamespace(engine=self.root/'engine', sha256='0'*64, revision='a'*40, + output=self.root/'out', cargo_target_dir=self.root/'target', + cpu_fixture=True, defer_engine_help_probe_to_runtime_image=True) + with patch.object(pkg.platform, 'system', return_value='Linux'), \ + patch.object(pkg.platform, 'machine', return_value='x86_64'), \ + patch.object(pkg.subprocess, 'run') as build: + with self.assertRaisesRegex(ValueError, 'only CUDA package builds'): + pkg.assemble(args) + build.assert_not_called() + if __name__ == '__main__': unittest.main() diff --git a/scripts/test-runtime-image.py b/scripts/test-runtime-image.py index d0d6b4a3..c8aca429 100644 --- a/scripts/test-runtime-image.py +++ b/scripts/test-runtime-image.py @@ -28,6 +28,7 @@ class PackageTests(unittest.TestCase): 'source_revision': 'a'*40, 'target': 'x86_64-unknown-linux-musl', 'engine': {'embedded': True, 'target_os': 'linux', 'target_arch': 'x86_64', 'declared_source_revision': 'a'*40, 'bytes': 3, 'sha256': 'b'*64}, + 'engine_help_probe': 'deferred-to-runtime-image', 'engine_elf_audit': {'toolkit_shared_libraries': False, 'host_glibc_required': True, 'minimum_glibc': '2.43'}} (self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input') @@ -110,6 +111,35 @@ class PackageTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'size limit'): b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1) + def test_cuda_package_requires_runtime_image_loader_probe(self): + self.provenance.pop('engine_help_probe') + self.write() + with self.assertRaisesRegex(ValueError, 'defer loader help'): + self.freeze() + + def test_successful_image_probes_embedded_help_after_identity(self): + args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256=self.sha, cpu_fixture=False) + image = 'sha256:' + 'd'*64 + isolated = [] + def docker(*argv, **kwargs): + if argv[0] == 'build': + Path(argv[argv.index('--iidfile')+1]).write_text(image) + return SimpleNamespace(stdout='') + def probe(probe_image, arguments, *, entrypoint=None): + isolated.append((probe_image, arguments, entrypoint)) + if entrypoint == 'getconf': + return 'glibc 2.43\n' + if arguments == ['engine-info']: + return json.dumps(self.provenance['engine']) + if arguments == ['engine-help']: + return '' + raise AssertionError((arguments, entrypoint)) + with patch.object(b, 'docker', side_effect=docker), patch.object(b, 'isolated_run', side_effect=probe): + result = b.assemble(args) + self.assertEqual(result['engine_help_probe'], 'passed-in-runtime-image') + self.assertEqual([call[1] for call in isolated], [['GNU_LIBC_VERSION'], ['engine-info'], ['engine-help']]) + self.assertEqual([call[2] for call in isolated], ['getconf', None, None]) + def test_runtime_probe_script_has_valid_bash_syntax(self): subprocess.run(['bash', '-n'], input=smoke.PROBE_SCRIPT, text=True, capture_output=True, check=True) -- 2.54.0 From 59b30049e3524aa46ce1c52998e46d97ad10e698 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 07:21:02 +0200 Subject: [PATCH 30/58] fix: publish preview through public Gitea host --- .github/workflows/linux.yml | 5 +++-- scripts/test-cuda-docker-builder.py | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 962ba6f1..ecba6668 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -134,8 +134,9 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: | - export GH_HOST="${GITHUB_SERVER_URL#https://}" - export GH_HOST="${GH_HOST#http://}" + # Gitea exposes an internal http://gitea:3000 URL to job containers; + # gh interprets GH_HOST as a public HTTPS hostname, not that service alias. + export GH_HOST=git.vezha.io tag="cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" gh release create "$tag" "$RUNNER_TEMP/strata-hosted-cuda-package/"* \ --target "$GITHUB_SHA" --repo "$GITHUB_REPOSITORY" \ diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index d94b911b..81b6ac59 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -232,6 +232,8 @@ else: self.assertIn('runs-on: ubuntu-latest', job) self.assertIn('scripts/build-cuda-engine-in-docker.py', job) self.assertIn('gh release create', job) + self.assertIn('export GH_HOST=git.vezha.io', job) + self.assertNotIn('GH_HOST="${GITHUB_SERVER_URL', job) self.assertRegex(job, r'apt-get install -y .*\btime\b') self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job) self.assertIn('--defer-engine-help-probe-to-runtime-image', job) -- 2.54.0 From a8fa7e013adac3b34fbde81b7b254d804be97152 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 08:01:06 +0200 Subject: [PATCH 31/58] Publish CUDA preview through Gitea API v1 --- .github/workflows/linux.yml | 16 +- scripts/publish-gitea-release.py | 219 ++++++++++++++++++++++++++++ scripts/test-cuda-docker-builder.py | 8 +- scripts/test-gitea-release.py | 194 ++++++++++++++++++++++++ 4 files changed, 425 insertions(+), 12 deletions(-) create mode 100644 scripts/publish-gitea-release.py create mode 100644 scripts/test-gitea-release.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index ecba6668..90848475 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -54,7 +54,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 150 permissions: - contents: write + releases: write env: CUDA_VISIBLE_DEVICES: '' BUILD_JOBS: '1' @@ -67,7 +67,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && apt-get install -y ca-certificates curl docker.io gh musl-tools binutils python3-numpy time + apt-get update && apt-get install -y ca-certificates curl docker.io musl-tools binutils python3-numpy time - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Record actual toolchain @@ -132,17 +132,15 @@ jobs: (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS) - name: Publish private CUDA preview release env: - GH_TOKEN: ${{ github.token }} + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + GITHUB_API_URL: ${{ github.api_url }} run: | - # Gitea exposes an internal http://gitea:3000 URL to job containers; - # gh interprets GH_HOST as a public HTTPS hostname, not that service alias. - export GH_HOST=git.vezha.io tag="cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - gh release create "$tag" "$RUNNER_TEMP/strata-hosted-cuda-package/"* \ - --target "$GITHUB_SHA" --repo "$GITHUB_REPOSITORY" \ + python3 scripts/publish-gitea-release.py \ + --tag "$tag" --target "$GITHUB_SHA" \ --title "CUDA build preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ --notes 'Actual CUDA compilation and packaging from this commit. Built in a GPU-hidden Docker container. This is not driver, inference, model-quality or performance qualification.' \ - --prerelease + --directory "$RUNNER_TEMP/strata-hosted-cuda-package" - name: Remove privately published package copy run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package" - name: Remove owned intermediate image and build files diff --git a/scripts/publish-gitea-release.py b/scripts/publish-gitea-release.py new file mode 100644 index 00000000..58e002b7 --- /dev/null +++ b/scripts/publish-gitea-release.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Publish the privately built CUDA preview through Gitea's API v1.""" +import argparse +import hashlib +import http.client +import json +import os +from pathlib import Path +import re +import ssl +import stat +import sys +from urllib.parse import urlencode, urlsplit + +PACKAGE_BINARY = 'strata-next-linux-x86_64-musl' +PACKAGE_ASSETS = {PACKAGE_BINARY, 'PROVENANCE.json'} +IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'} +ASSETS = PACKAGE_ASSETS | IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'} +CHUNK_SIZE = 1024 * 1024 + + +def file_sha256(path): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as source: + if not stat.S_ISREG(os.fstat(source.fileno()).st_mode): + raise ValueError(f'not a regular artifact file: {path.name}') + return hashlib.file_digest(source, 'sha256').hexdigest() + + +def verify_manifest(directory, manifest, expected): + path = directory / manifest + lines = path.read_text(encoding='ascii').splitlines() + entries = {} + for line in lines: + match = re.fullmatch(r'([0-9a-f]{64}) ([A-Za-z0-9_.-]+)', line) + if not match or match[2] in entries: + raise ValueError(f'invalid {manifest} entry') + entries[match[2]] = match[1] + if set(entries) != expected: + raise ValueError(f'{manifest} does not cover the required artifact set') + for name, expected_sha in entries.items(): + if file_sha256(directory / name) != expected_sha: + raise ValueError(f'{manifest} checksum mismatch: {name}') + + +def read_json(path): + try: + value = json.loads(path.read_text(encoding='utf-8')) + except (OSError, json.JSONDecodeError) as error: + raise ValueError(f'invalid artifact JSON: {path.name}') from error + if not isinstance(value, dict): + raise ValueError(f'artifact JSON must be an object: {path.name}') + return value + + +def verify_artifacts(directory, target): + if not directory.is_dir(): + raise ValueError('artifact directory does not exist') + paths = list(directory.iterdir()) + if {path.name for path in paths} != ASSETS: + raise ValueError('artifact directory must contain exactly the CUDA preview files') + for path in paths: + file_sha256(path) + verify_manifest(directory, 'SHA256SUMS', PACKAGE_ASSETS) + verify_manifest(directory, 'IMAGE-SHA256SUMS', IMAGE_ASSETS) + package = read_json(directory / 'PROVENANCE.json') + if (package.get('kind') != 'static-cuda-preview' or package.get('source_revision') != target or + package.get('engine_help_probe') != 'deferred-to-runtime-image' or + package.get('gpu_tested') is not False or package.get('model_tested') is not False): + raise ValueError('combined package provenance is not a CUDA-only preview for this commit') + image = read_json(directory / 'IMAGE-PROVENANCE.json') + if (image.get('kind') != 'static-cuda-preview' or image.get('source_revision') != target or + image.get('engine_help_probe') != 'passed-in-runtime-image' or + image.get('gpu_tested') is not False or image.get('model_tested') is not False or + image.get('package_receipt_sha256') != file_sha256(directory / 'SHA256SUMS')): + raise ValueError('runtime image provenance is not qualified for this package and commit') + toolchain = read_json(directory / 'CUDA-TOOLCHAIN.json') + docker_builder = toolchain.get('docker_builder') + if (toolchain.get('source') != target or toolchain.get('driver_tested') is not False or + toolchain.get('model_tested') is not False or not isinstance(docker_builder, dict) or + docker_builder.get('source_commit') != target or + docker_builder.get('engine_sha256') != package.get('engine', {}).get('sha256')): + raise ValueError('CUDA toolchain provenance is not bound to this commit and engine') + return {path.name: {'size': path.stat().st_size, 'sha256': file_sha256(path)} for path in paths} + + +def parse_api_url(api_url): + parts = urlsplit(api_url) + if (parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password or + parts.query or parts.fragment or not parts.path.rstrip('/').endswith('/api/v1')): + raise ValueError('API URL must be a Gitea /api/v1 base URL') + prefix = parts.path.rstrip('/') + return parts, prefix + + +def connection(parts): + cls = http.client.HTTPSConnection if parts.scheme == 'https' else http.client.HTTPConnection + return cls(parts.hostname, parts.port, timeout=300, **({'context': ssl.create_default_context()} if parts.scheme == 'https' else {})) + + +def request_json(parts, prefix, path, token, payload, method='POST', expected_status=201): + body = json.dumps(payload, separators=(',', ':')).encode('utf-8') + conn = connection(parts) + try: + conn.request(method, prefix + path, body=body, + headers={'Authorization': f'token {token}', 'Content-Type': 'application/json', + 'Accept': 'application/json'}) + response = conn.getresponse() + data = response.read(1024 * 1024 + 1) + if response.status != expected_status: + detail = data[:1024].decode('utf-8', 'replace').replace(token, '[redacted]') + raise RuntimeError(f'Gitea API returned HTTP {response.status}: {detail}') + return json.loads(data) + finally: + conn.close() + + +def upload_asset(parts, prefix, path, token, asset, expected): + name = asset.name + route = prefix + path + '/assets?' + urlencode({'name': name}) + fd = os.open(asset, os.O_RDONLY | os.O_NOFOLLOW) + conn = None + try: + source_stat = os.fstat(fd) + if not stat.S_ISREG(source_stat.st_mode): + raise ValueError(f'not a regular artifact file: {name}') + size = source_stat.st_size + if size != expected['size']: + raise ValueError(f'artifact size changed after verification: {name}') + conn = connection(parts) + conn.putrequest('POST', route) + conn.putheader('Authorization', f'token {token}') + conn.putheader('Content-Type', 'application/octet-stream') + conn.putheader('Content-Length', str(size)) + conn.putheader('Accept', 'application/json') + conn.endheaders() + digest = hashlib.sha256() + sent = 0 + with os.fdopen(fd, 'rb') as source: + fd = -1 + while sent < size: + block = source.read(min(CHUNK_SIZE, size - sent)) + if not block: + raise ValueError(f'artifact was truncated during upload: {name}') + sent += len(block) + digest.update(block) + conn.send(block) + if digest.hexdigest() != expected['sha256']: + raise ValueError(f'artifact content changed after verification: {name}') + response = conn.getresponse() + data = response.read(1024 * 1024 + 1) + if response.status != 201: + detail = data[:1024].decode('utf-8', 'replace').replace(token, '[redacted]') + raise RuntimeError(f'Gitea asset upload returned HTTP {response.status}: {detail}') + metadata = json.loads(data) + if metadata.get('name') != name or metadata.get('size') != size: + raise ValueError(f'Gitea returned mismatched asset metadata: {name}') + return {'name': name, 'size': size} + finally: + if fd >= 0: + os.close(fd) + if conn is not None: + conn.close() + + +def publish(api_url, repository, token, tag, target, title, notes, directory): + if not token: + raise ValueError('GITEA_TOKEN is required') + repo_parts = repository.split('/') + if len(repo_parts) != 2 or any(part in {'.', '..'} or not re.fullmatch(r'[A-Za-z0-9_.-]+', part) + for part in repo_parts): + raise ValueError('repository must be owner/name') + if not re.fullmatch(r'cuda-preview-[0-9]+-[0-9]+', tag): + raise ValueError('preview tag must be run-scoped cuda-preview-RUN-ATTEMPT') + if not re.fullmatch(r'[0-9a-f]{40}', target): + raise ValueError('target must be a full lowercase Git SHA') + parts, prefix = parse_api_url(api_url) + hashes = verify_artifacts(directory, target) + owner, repo = repo_parts + release = request_json(parts, prefix, f'/repos/{owner}/{repo}/releases', token, + {'tag_name': tag, 'target_commitish': target, 'name': title, + 'body': notes, 'draft': True, 'prerelease': True}) + release_id = release.get('id') + if type(release_id) is not int or release_id <= 0: + raise ValueError('Gitea did not return a valid release ID') + asset_route = f'/repos/{owner}/{repo}/releases/{release_id}' + uploaded = [] + for name in sorted(ASSETS): + uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name])) + finalized = request_json(parts, prefix, asset_route, token, {'draft': False}, + method='PATCH', expected_status=200) + if finalized.get('id') != release_id or finalized.get('draft') is not False: + raise ValueError('Gitea did not confirm publication of the complete preview release') + return {'release_id': release_id, 'release_url': release.get('html_url'), + 'tag': tag, 'target': target, 'assets': [dict(uploaded_asset, sha256=hashes[uploaded_asset['name']]['sha256']) + for uploaded_asset in uploaded]} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--api-url', default=os.environ.get('GITHUB_API_URL'), required=os.environ.get('GITHUB_API_URL') is None) + parser.add_argument('--repository', default=os.environ.get('GITHUB_REPOSITORY'), required=os.environ.get('GITHUB_REPOSITORY') is None) + parser.add_argument('--tag', required=True) + parser.add_argument('--target', required=True) + parser.add_argument('--title', required=True) + parser.add_argument('--notes', required=True) + parser.add_argument('--directory', type=Path, required=True) + args = parser.parse_args() + try: + result = publish(args.api_url, args.repository, os.environ.get('GITEA_TOKEN', ''), + args.tag, args.target, args.title, args.notes, args.directory) + print(json.dumps(result, sort_keys=True)) + except (ValueError, OSError, RuntimeError, http.client.HTTPException, json.JSONDecodeError) as error: + print(f'Gitea release publication failed: {error}', file=sys.stderr) + raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 81b6ac59..463915fe 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -231,13 +231,15 @@ else: job = workflow.split(' hosted-cuda-package:', 1)[1].split('\n linux-static-cli:', 1)[0] self.assertIn('runs-on: ubuntu-latest', job) self.assertIn('scripts/build-cuda-engine-in-docker.py', job) - self.assertIn('gh release create', job) - self.assertIn('export GH_HOST=git.vezha.io', job) - self.assertNotIn('GH_HOST="${GITHUB_SERVER_URL', job) self.assertRegex(job, r'apt-get install -y .*\btime\b') self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job) self.assertIn('--defer-engine-help-probe-to-runtime-image', job) self.assertIn('scripts/build-runtime-image.py --package', job) + self.assertIn('releases: write', job) + self.assertIn('secrets.GITEA_TOKEN', job) + self.assertIn('github.api_url', job) + self.assertIn('scripts/publish-gitea-release.py', job) + self.assertNotIn('gh release create', job) self.assertNotIn('strata-gpu', job) self.assertNotIn('actions/upload-artifact', job) self.assertNotIn('static_cuda_package', workflow) diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py new file mode 100644 index 00000000..5cf02073 --- /dev/null +++ b/scripts/test-gitea-release.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Contract tests for private CUDA preview release publishing.""" +import hashlib +import importlib.util +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import tempfile +import threading +from types import SimpleNamespace +from urllib.parse import parse_qs, urlsplit +import unittest + +spec = importlib.util.spec_from_file_location('publisher', Path(__file__).with_name('publish-gitea-release.py')) +publisher = importlib.util.module_from_spec(spec) +spec.loader.exec_module(publisher) + +TOKEN = 'fixture-action-token' +REVISION = 'a' * 40 + + +class FakeGitea(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def send_json(self, status, payload): + body = json.dumps(payload).encode() + self.send_response(status) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + if self.headers.get('Authorization') != f'token {TOKEN}': + self.send_json(401, {'message': 'bad token'}) + return + if self.path == '/api/v1/repos/owner/repo/releases': + body = self.rfile.read(int(self.headers['Content-Length'])) + self.server.release_payload = json.loads(body) + if self.server.fail_create: + return self.send_json(403, {'message': TOKEN}) + return self.send_json(201, {'id': 73, 'html_url': 'http://gitea.invalid/owner/repo/releases/tag/x'}) + parsed = urlsplit(self.path) + if parsed.path == '/api/v1/repos/owner/repo/releases/73/assets': + size = int(self.headers['Content-Length']) + digest = hashlib.sha256() + remaining = size + while remaining: + block = self.rfile.read(min(128 * 1024, remaining)) + if not block: + raise AssertionError('truncated streamed request body') + digest.update(block) + remaining -= len(block) + name = parse_qs(parsed.query)['name'][0] + self.server.assets.append({'name': name, 'size': size, 'sha256': digest.hexdigest()}) + if self.server.fail_asset: + return self.send_json(500, {'message': TOKEN}) + return self.send_json(201, {'name': name, 'size': size}) + self.send_json(404, {'message': 'unexpected route'}) + + def do_PATCH(self): + if self.headers.get('Authorization') != f'token {TOKEN}': + return self.send_json(401, {'message': 'bad token'}) + if self.path != '/api/v1/repos/owner/repo/releases/73': + return self.send_json(404, {'message': 'unexpected route'}) + self.server.finalize_payload = json.loads(self.rfile.read(int(self.headers['Content-Length']))) + self.send_json(200, {'id': 73, 'draft': self.server.finalize_payload['draft']}) + + +class PublisherTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.directory = Path(self.tmp.name) + self.server = ThreadingHTTPServer(('127.0.0.1', 0), FakeGitea) + self.server.release_payload = None + self.server.finalize_payload = None + self.server.assets = [] + self.server.fail_create = False + self.server.fail_asset = False + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.thread.join) + self.addCleanup(self.server.shutdown) + self.api_url = f'http://127.0.0.1:{self.server.server_port}/api/v1' + self.write_artifacts() + + def write_artifacts(self): + directory = self.directory + (directory / publisher.PACKAGE_BINARY).write_bytes(b'embedded-engine-fixture') + engine_sha = hashlib.sha256(b'cuda-engine-fixture').hexdigest() + package_provenance = { + 'kind': 'static-cuda-preview', 'source_revision': REVISION, + 'engine_help_probe': 'deferred-to-runtime-image', 'gpu_tested': False, 'model_tested': False, + 'engine': {'sha256': engine_sha}, + } + (directory / 'PROVENANCE.json').write_text(json.dumps(package_provenance)) + package_files = [publisher.PACKAGE_BINARY, 'PROVENANCE.json'] + (directory / 'SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(directory / name)} {name}\n' for name in package_files)) + receipt = publisher.file_sha256(directory / 'SHA256SUMS') + (directory / 'runtime-image.tar').write_bytes(b'runtime-image-' * 180000) + image_provenance = { + 'kind': 'static-cuda-preview', 'source_revision': REVISION, + 'engine_help_probe': 'passed-in-runtime-image', 'gpu_tested': False, 'model_tested': False, + 'package_receipt_sha256': receipt, + } + (directory / 'IMAGE-PROVENANCE.json').write_text(json.dumps(image_provenance)) + (directory / 'CUDA-TOOLCHAIN.json').write_text(json.dumps({ + 'source': REVISION, 'driver_tested': False, 'model_tested': False, + 'docker_builder': {'source_commit': REVISION, 'engine_sha256': engine_sha}, + })) + (directory / 'CUDA-LICENSES.tar').write_bytes(b'license archive') + image_files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'] + (directory / 'IMAGE-SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(directory / name)} {name}\n' for name in image_files)) + + def test_uploads_exact_hashed_assets_via_api_v1_and_streams_large_asset(self): + result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'CUDA preview 42.1', 'Build-only preview.', self.directory) + self.assertEqual(result['release_id'], 73) + self.assertEqual(result['target'], REVISION) + self.assertEqual(len(result['assets']), len(publisher.ASSETS)) + self.assertEqual(self.server.release_payload, { + 'tag_name': 'cuda-preview-42-1', 'target_commitish': REVISION, 'name': 'CUDA preview 42.1', + 'body': 'Build-only preview.', 'draft': True, 'prerelease': True, + }) + self.assertEqual(self.server.finalize_payload, {'draft': False}) + uploaded = {asset['name']: asset for asset in self.server.assets} + self.assertEqual(set(uploaded), publisher.ASSETS) + self.assertGreater(uploaded['runtime-image.tar']['size'], publisher.CHUNK_SIZE) + for name in publisher.ASSETS: + self.assertEqual(uploaded[name]['sha256'], publisher.file_sha256(self.directory / name)) + + def test_checksum_failure_precedes_api_call(self): + (self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered') + with self.assertRaisesRegex(ValueError, 'SHA256SUMS checksum mismatch'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def test_wrong_source_provenance_is_rejected(self): + path = self.directory / 'IMAGE-PROVENANCE.json' + image = json.loads(path.read_text()) + image['source_revision'] = 'c' * 40 + path.write_text(json.dumps(image)) + files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'] + (self.directory / 'IMAGE-SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in files)) + with self.assertRaisesRegex(ValueError, 'runtime image provenance'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def test_api_failures_redact_token_and_do_not_finalize_incomplete_release(self): + self.server.fail_create = True + with self.assertRaisesRegex(RuntimeError, r'HTTP 403: \{"message": "\[redacted\]"\}') as failure: + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertNotIn(TOKEN, str(failure.exception)) + self.assertIsNone(self.server.finalize_payload) + + self.server.fail_create = False + self.server.fail_asset = True + with self.assertRaisesRegex(RuntimeError, r'HTTP 500: \{"message": "\[redacted\]"\}'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.finalize_payload) + + def test_unexpected_extra_file_and_invalid_route_are_rejected(self): + (self.directory / 'private-key').write_text('never upload') + with self.assertRaisesRegex(ValueError, 'exactly the CUDA preview files'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + (self.directory / 'private-key').unlink() + with self.assertRaisesRegex(ValueError, 'API URL'): + publisher.publish(self.api_url.replace('/api/v1', '/api/v3'), 'owner/repo', TOKEN, + 'cuda-preview-42-1', REVISION, 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def test_invalid_scope_and_target_rejected(self): + with self.assertRaisesRegex(ValueError, 'owner/name'): + publisher.publish(self.api_url, '../repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + with self.assertRaisesRegex(ValueError, 'full lowercase Git SHA'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', 'ABC', + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From d3e63a789ea354aa9ba28c6063978207239f951e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 08:21:06 +0200 Subject: [PATCH 32/58] Retain checkout permission for Gitea preview job --- .github/workflows/linux.yml | 1 + scripts/test-cuda-docker-builder.py | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 90848475..f9e2065b 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -54,6 +54,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 150 permissions: + contents: read releases: write env: CUDA_VISIBLE_DEVICES: '' diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 463915fe..de1fc94e 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -235,6 +235,7 @@ else: self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job) self.assertIn('--defer-engine-help-probe-to-runtime-image', job) self.assertIn('scripts/build-runtime-image.py --package', job) + self.assertIn('contents: read', job) self.assertIn('releases: write', job) self.assertIn('secrets.GITEA_TOKEN', job) self.assertIn('github.api_url', job) -- 2.54.0 From 3bcfbfd856830608077fa670dc15920648e6703b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 10:36:48 +0200 Subject: [PATCH 33/58] STRA-8: make streamed KAR publication recoverable --- control-plane/src/kar_overlay.rs | 14 +- control-plane/src/kar_stream_encode.rs | 373 ++++--- control-plane/src/kar_writer.rs | 90 +- control-plane/src/model_pipeline.rs | 145 ++- control-plane/src/prepare_preview.rs | 1400 ++++++++++++++++++------ control-plane/src/stream_parts.rs | 349 ++++-- docs/build-validation.md | 1 + docs/compressed-runtime.md | 14 + 8 files changed, 1772 insertions(+), 614 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index ffa8396d..2c62b8f6 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -693,12 +693,14 @@ pub fn prepare( let section_path = staging.0.join(format!("{:06}.section", prepared.len())); let section = kar_stream_encode::encode_section( &mut source, - location.absolute, - location.kind, - location.source_bytes, - elements, - &calibration, - §ion_path, + &kar_stream_encode::SectionRequest { + absolute_offset: location.absolute, + source_kind: location.kind, + source_bytes: location.source_bytes, + elements, + calibration: &calibration, + destination: §ion_path, + }, )?; if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 { return Err(format!("{}: candidate source changed", candidate.name)); diff --git a/control-plane/src/kar_stream_encode.rs b/control-plane/src/kar_stream_encode.rs index 037078d3..830a28fd 100644 --- a/control-plane/src/kar_stream_encode.rs +++ b/control-plane/src/kar_stream_encode.rs @@ -19,15 +19,98 @@ pub struct SectionResult { pub relative_l2: f64, } +pub struct SectionRequest<'a> { + pub absolute_offset: u64, + pub source_kind: u32, + pub source_bytes: u64, + pub elements: u64, + pub calibration: &'a kar_codec::Calibration, + pub destination: &'a Path, +} + +struct SectionLayout { + levels: usize, + words: u64, + books_start: u64, + planes_start: u64, + plane_stride: u64, + section_bytes: u64, +} + +struct SectionEncoder<'a> { + path: std::path::PathBuf, + calibration: &'a kar_codec::Calibration, + scale_writer: BufWriter, + plane_writers: Vec>, + pending: [f32; 32], + filled: usize, + seen: u64, + groups: u64, + error_sum: f64, + reference_sum: f64, +} + pub fn encode_section( reader: &mut R, - absolute_offset: u64, - source_kind: u32, - source_bytes: u64, - elements: u64, - calibration: &kar_codec::Calibration, - destination: &Path, + request: &SectionRequest<'_>, ) -> Result { + let layout = SectionLayout::new(request.elements, request.calibration)?; + let section = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(request.destination) + .map_err(|error| error.to_string())?; + let result = section + .set_len(layout.section_bytes) + .map_err(|error| error.to_string()) + .and_then(|()| encode_section_contents(reader, request, &layout)); + drop(section); + if result.is_err() { + let _ = fs::remove_file(request.destination); + } + result +} + +impl SectionLayout { + fn new(elements: u64, calibration: &kar_codec::Calibration) -> Result { + validate_calibration(elements, calibration)?; + let levels = calibration.books.len(); + let words = elements.div_ceil(32); + let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?; + let books_start = round_up(scales_bytes, 16)?; + let books_bytes = (1u64 << (levels + 2)) - 4; + let planes_start = round_up( + books_start + .checked_add(books_bytes) + .ok_or("KAR books overflow")?, + 16, + )?; + let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?; + if plane_stride > u32::MAX as u64 { + return Err("KAR plane stride exceeds format limit".into()); + } + let planes_bytes = plane_stride + .checked_mul(levels as u64) + .ok_or("KAR planes overflow")?; + let section_bytes = round_up( + planes_start + .checked_add(planes_bytes) + .ok_or("KAR section overflow")?, + 256, + )?; + Ok(Self { + levels, + words, + books_start, + planes_start, + plane_stride, + section_bytes, + }) + } +} + +fn validate_calibration(elements: u64, calibration: &kar_codec::Calibration) -> Result<(), String> { let levels = calibration.books.len(); if elements == 0 || !(1..=8).contains(&levels) @@ -46,138 +129,164 @@ pub fn encode_section( { return Err("invalid streamed KAR calibration".into()); } - let words = elements.div_ceil(32); - let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?; - let books_start = round_up(scales_bytes, 16)?; - let books_bytes = (1u64 << (levels + 2)) - 4; - let planes_start = round_up( - books_start - .checked_add(books_bytes) - .ok_or("KAR books overflow")?, - 16, + Ok(()) +} + +fn encode_section_contents( + reader: &mut R, + request: &SectionRequest<'_>, + layout: &SectionLayout, +) -> Result { + let (source_digest, derived_digest, relative_l2) = + encode_stream_values(reader, request, layout)?; + sync_file(request.destination)?; + let digest = hash_file(request.destination)?; + Ok(SectionResult { + bytes: layout.section_bytes, + digest, + source_digest, + derived_digest, + relative_l2, + }) +} + +fn encode_stream_values( + reader: &mut R, + request: &SectionRequest<'_>, + layout: &SectionLayout, +) -> Result<([u8; 32], [u8; 32], f64), String> { + let mut encoder = SectionEncoder::new(request.destination, request.calibration, layout)?; + let mut source_hash = Sha256::new(); + let mut derived_hash = Sha256::new(); + let decoded_bytes = gguf_f32_stream::visit( + reader, + request.absolute_offset, + request.source_kind, + request.source_bytes, + |raw, f32_bytes| { + source_hash.update(raw); + derived_hash.update(f32_bytes); + encoder.push(f32_bytes, request.elements) + }, )?; - let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?; - if plane_stride > u32::MAX as u64 { - return Err("KAR plane stride exceeds format limit".into()); - } - let section_bytes = round_up( - planes_start - .checked_add( - plane_stride - .checked_mul(levels as u64) - .ok_or("KAR planes overflow")?, - ) - .ok_or("KAR section overflow")?, - 256, - )?; - let section = OpenOptions::new() + let relative_l2 = encoder.finish(request.elements, decoded_bytes, layout)?; + Ok(( + source_hash.finalize().into(), + derived_hash.finalize().into(), + relative_l2, + )) +} + +fn sync_file(path: &Path) -> Result<(), String> { + OpenOptions::new() .read(true) .write(true) - .create_new(true) - .open(destination) - .map_err(|error| error.to_string())?; - let result = (|| -> Result { - section - .set_len(section_bytes) - .map_err(|error| error.to_string())?; - let mut scale_writer = writer_at(destination, 0)?; - let mut plane_writers = (0..levels) - .map(|level| writer_at(destination, planes_start + level as u64 * plane_stride)) + .open(path) + .and_then(|file| file.sync_all()) + .map_err(|error| error.to_string()) +} + +impl<'a> SectionEncoder<'a> { + fn new( + path: &Path, + calibration: &'a kar_codec::Calibration, + layout: &SectionLayout, + ) -> Result { + let scale_writer = writer_at(path, 0)?; + let plane_writers = (0..layout.levels) + .map(|level| { + writer_at( + path, + layout.planes_start + level as u64 * layout.plane_stride, + ) + }) .collect::, _>>()?; - let mut pending = [0.0f32; 32]; - let mut filled = 0usize; - let mut seen = 0u64; - let mut groups = 0u64; - let mut error_sum = 0.0f64; - let mut reference_sum = 0.0f64; - let mut source_hash = Sha256::new(); - let mut derived_hash = Sha256::new(); - let decoded_bytes = gguf_f32_stream::visit( - reader, - absolute_offset, - source_kind, - source_bytes, - |raw, f32_bytes| { - source_hash.update(raw); - derived_hash.update(f32_bytes); - for word in f32_bytes.as_chunks::<4>().0 { - if seen >= elements { - return Err("GGUF tensor decodes beyond its shape".into()); - } - pending[filled] = f32::from_le_bytes(*word); - filled += 1; - seen += 1; - if filled == 32 { - write_group( - &pending, - calibration, - &mut scale_writer, - &mut plane_writers, - &mut error_sum, - &mut reference_sum, - )?; - filled = 0; - groups += 1; - } - } - Ok(()) - }, + Ok(Self { + path: path.to_path_buf(), + calibration, + scale_writer, + plane_writers, + pending: [0.0; 32], + filled: 0, + seen: 0, + groups: 0, + error_sum: 0.0, + reference_sum: 0.0, + }) + } + + fn push(&mut self, bytes: &[u8], elements: u64) -> Result<(), String> { + for word in bytes.as_chunks::<4>().0 { + if self.seen >= elements { + return Err("GGUF tensor decodes beyond its shape".into()); + } + self.pending[self.filled] = f32::from_le_bytes(*word); + self.filled += 1; + self.seen += 1; + if self.filled == 32 { + self.write_pending(32)?; + } + } + Ok(()) + } + + fn write_pending(&mut self, count: usize) -> Result<(), String> { + write_group( + &self.pending[..count], + self.calibration, + &mut self.scale_writer, + &mut self.plane_writers, + &mut self.error_sum, + &mut self.reference_sum, )?; - if seen != elements + self.filled = 0; + self.groups += 1; + Ok(()) + } + + fn finish( + &mut self, + elements: u64, + decoded_bytes: u64, + layout: &SectionLayout, + ) -> Result { + if self.seen != elements || decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? { return Err("GGUF decoded tensor shape mismatch".into()); } - if filled != 0 { - write_group( - &pending[..filled], - calibration, - &mut scale_writer, - &mut plane_writers, - &mut error_sum, - &mut reference_sum, - )?; - groups += 1; + if self.filled != 0 { + self.write_pending(self.filled)?; } - if groups != words { + if self.groups != layout.words { return Err("KAR encoded group count mismatch".into()); } - scale_writer.flush().map_err(|error| error.to_string())?; - for writer in &mut plane_writers { + self.scale_writer + .flush() + .map_err(|error| error.to_string())?; + for writer in &mut self.plane_writers { writer.flush().map_err(|error| error.to_string())?; } - drop(scale_writer); - drop(plane_writers); - let mut book_writer = writer_at(destination, books_start)?; - for book in &calibration.books { + self.write_books(layout.books_start)?; + if self.reference_sum == 0.0 { + Ok(self.error_sum.sqrt()) + } else { + Ok((self.error_sum / self.reference_sum).sqrt()) + } + } + + fn write_books(&self, offset: u64) -> Result<(), String> { + let mut writer = writer_at(&self.path, offset)?; + for book in &self.calibration.books { for bits in book { - book_writer + writer .write_all(&bits.to_le_bytes()) .map_err(|error| error.to_string())?; } } - book_writer.flush().map_err(|error| error.to_string())?; - drop(book_writer); - section.sync_all().map_err(|error| error.to_string())?; - let digest = hash_file(destination)?; - let relative_l2 = if reference_sum == 0.0 { - error_sum.sqrt() - } else { - (error_sum / reference_sum).sqrt() - }; - Ok(SectionResult { - bytes: section_bytes, - digest, - source_digest: source_hash.finalize().into(), - derived_digest: derived_hash.finalize().into(), - relative_l2, - }) - })(); - drop(section); - if result.is_err() { - let _ = fs::remove_file(destination); + writer.flush().map_err(|error| error.to_string())?; + Ok(()) } - result } fn write_group( @@ -316,12 +425,14 @@ mod tests { let output = root.join("streamed.section"); let streamed = encode_section( &mut Cursor::new(&source), - 0, - 0, - source.len() as u64, - weights.len() as u64, - &calibration, - &output, + &SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: source.len() as u64, + elements: weights.len() as u64, + calibration: &calibration, + destination: &output, + }, ) .unwrap(); assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap()); @@ -382,12 +493,14 @@ mod tests { )); let result = encode_section( &mut Cursor::new(&source), - 0, - 21, - source.len() as u64, - (257 * iq3_s::BLOCK_ELEMENTS) as u64, - &calibration, - &path, + &SectionRequest { + absolute_offset: 0, + source_kind: 21, + source_bytes: source.len() as u64, + elements: (257 * iq3_s::BLOCK_ELEMENTS) as u64, + calibration: &calibration, + destination: &path, + }, ) .unwrap(); assert_eq!( diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index e55065f3..92161080 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -285,13 +285,7 @@ fn write_archive_inner( return Err("KAR tensors exceed source element count".into()); } let archive_bytes = cursor; - let temporary = destination.with_file_name(format!( - "{}.part", - destination - .file_name() - .ok_or("KAR destination has no filename")? - .to_string_lossy() - )); + let temporary = archive_temporary_path(destination)?; let mut file = OpenOptions::new() .write(true) .create_new(true) @@ -375,13 +369,32 @@ fn write_archive_inner( return Err(error); } }; - // A hard link publishes a fully written archive atomically without replacing - // an existing destination, even if another writer won the race after preflight. - if let Err(error) = fs::hard_link(&temporary, destination) { - let _ = fs::remove_file(&temporary); + publish_verified_archive(&temporary, destination, summary, remove_archive_temp) +} + +fn archive_temporary_path(destination: &Path) -> Result { + let name = destination + .file_name() + .ok_or("KAR destination has no filename")? + .to_string_lossy(); + Ok(destination.with_file_name(format!("{name}.part"))) +} + +fn remove_archive_temp(path: &Path) -> Result<(), String> { + fs::remove_file(path).map_err(|error| error.to_string()) +} + +fn publish_verified_archive( + temporary: &Path, + destination: &Path, + summary: kar::Summary, + cleanup: fn(&Path) -> Result<(), String>, +) -> Result { + if let Err(error) = fs::hard_link(temporary, destination) { + let _ = cleanup(temporary); return Err(error.to_string()); } - fs::remove_file(&temporary).map_err(|error| error.to_string())?; + cleanup(temporary)?; Ok(summary) } @@ -952,6 +965,59 @@ fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { mod tests { use super::*; + fn fail_cleanup(_: &Path) -> Result<(), String> { + Err("injected temporary cleanup failure".into()) + } + + #[test] + fn post_publish_temporary_cleanup_error_keeps_archive_without_overwriting() { + let root = std::env::temp_dir().join(format!("strata-kar-publish-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let temporary = root.join("candidate.part"); + let destination = root.join("archive.kar"); + fs::write(&temporary, b"verified archive").unwrap(); + let summary = kar::Summary { + archive_bytes: 16, + tensor_count: 1, + total_elements: 1, + source_total_elements: 1, + accounted_bpw: 128.0, + source_digest: [0; 32], + source_bytes: 4, + max_planes: 0, + }; + assert!(publish_verified_archive(&temporary, &destination, summary, fail_cleanup).is_err()); + assert_eq!(fs::read(&destination).unwrap(), b"verified archive"); + assert!(temporary.exists()); + + let unrelated = root.join("unrelated.kar"); + let competing = root.join("competing.part"); + fs::write(&unrelated, b"do not replace").unwrap(); + fs::write(&competing, b"other archive").unwrap(); + let competing_summary = kar::Summary { + archive_bytes: 13, + tensor_count: 1, + total_elements: 1, + source_total_elements: 1, + accounted_bpw: 104.0, + source_digest: [0; 32], + source_bytes: 4, + max_planes: 0, + }; + assert!( + publish_verified_archive( + &competing, + &unrelated, + competing_summary, + remove_archive_temp, + ) + .is_err() + ); + assert_eq!(fs::read(unrelated).unwrap(), b"do not replace"); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn streams_canonical_nested_section_and_rejects_corruption() { let source = SourceIdentity { diff --git a/control-plane/src/model_pipeline.rs b/control-plane/src/model_pipeline.rs index 1822c559..b15c5d7e 100644 --- a/control-plane/src/model_pipeline.rs +++ b/control-plane/src/model_pipeline.rs @@ -92,47 +92,114 @@ async fn ensure_sharded_streamed_with_policy( levels: u8, ple_part_elements: Option, ) -> Result> { - if !(1..=8).contains(&levels) { - return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); + StreamedEnsureRequest { + manifest, + source_dir, + archive, + levels, + ple_part_elements, } + .run() + .await +} + +struct StreamedEnsureRequest<'a> { + manifest: &'a model::Manifest, + source_dir: &'a Path, + archive: &'a Path, + levels: u8, + ple_part_elements: Option, +} + +impl StreamedEnsureRequest<'_> { + async fn run(self) -> Result> { + self.validate()?; + preflight_existing_shards(self.manifest, self.source_dir, self.archive, self.levels)?; + model::fetch(self.manifest, self.source_dir).await?; + model::verify(self.manifest, self.source_dir).await?; + self.resolve_archive() + } + + fn validate(&self) -> Result<(), Box> { + if !(1..=8).contains(&self.levels) { + return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); + } + if let Some(limit) = self.ple_part_elements { + stream_parts::validate_ple_limit(limit)?; + } + Ok(()) + } + + fn resolve_archive(self) -> Result> { + match fs::symlink_metadata(self.archive) { + Ok(metadata) => self.reuse_existing(metadata), + Err(error) if error.kind() == io::ErrorKind::NotFound => self.create_archive(), + Err(error) => Err(error.into()), + } + } + + fn reuse_existing(&self, metadata: fs::Metadata) -> Result> { + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("existing KAR path must be a regular file".into()); + } + let summary = if prepare_preview::has_pending_streamed_publication(self.archive)? { + prepare_preview::recover_sharded_streamed_provenance( + self.manifest, + self.source_dir, + self.archive, + self.levels, + self.ple_part_elements, + )? + .ok_or("KAR recovery intent disappeared before verification")? + } else { + self.verify_archive()? + }; + Ok(PreviewOutcome::Reused(summary)) + } + + fn create_archive(&self) -> Result> { + let created = if let Some(limit) = self.ple_part_elements { + prepare_preview::prepare_sharded_streamed_ple( + self.manifest, + self.source_dir, + self.archive, + self.levels, + limit, + )? + } else { + prepare_preview::prepare_sharded_streamed( + self.manifest, + self.source_dir, + self.archive, + self.levels, + )? + }; + self.verify_archive()?; + Ok(PreviewOutcome::Created(created)) + } + + fn verify_archive(&self) -> Result { + verify_streamed_archive( + self.manifest, + self.source_dir, + self.archive, + self.levels, + self.ple_part_elements, + ) + } +} + +fn verify_streamed_archive( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, + ple_part_elements: Option, +) -> Result { if let Some(limit) = ple_part_elements { - stream_parts::validate_ple_limit(limit)?; - } - preflight_existing_shards(manifest, source_dir, archive, levels)?; - model::fetch(manifest, source_dir).await?; - model::verify(manifest, source_dir).await?; - match fs::symlink_metadata(archive) { - Ok(metadata) => { - if !metadata.is_file() || metadata.file_type().is_symlink() { - return Err("existing KAR path must be a regular file".into()); - } - let summary = if let Some(limit) = ple_part_elements { - prepare_preview::verify_sharded_streamed_ple( - manifest, source_dir, archive, levels, limit, - )? - } else { - prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)? - }; - Ok(PreviewOutcome::Reused(summary)) - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let created = if let Some(limit) = ple_part_elements { - prepare_preview::prepare_sharded_streamed_ple( - manifest, source_dir, archive, levels, limit, - )? - } else { - prepare_preview::prepare_sharded_streamed(manifest, source_dir, archive, levels)? - }; - if let Some(limit) = ple_part_elements { - prepare_preview::verify_sharded_streamed_ple( - manifest, source_dir, archive, levels, limit, - )?; - } else { - prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?; - } - Ok(PreviewOutcome::Created(created)) - } - Err(error) => Err(error.into()), + prepare_preview::verify_sharded_streamed_ple(manifest, source_dir, archive, levels, limit) + } else { + prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels) } } diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index a2c44974..bef0960d 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -6,6 +6,7 @@ use std::{ fs::{self, File}, io::{BufWriter, Read, Seek, SeekFrom, Write}, path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, }; use sha2::{Digest, Sha256}; @@ -20,6 +21,7 @@ use crate::{ const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; const MAX_TENSORS: usize = 1000; const MAX_TENSOR_ELEMENTS: u64 = 1_000_000; +static PROVENANCE_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); pub(crate) fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result { if !derived_bytes.is_multiple_of(4) || !(1..=8).contains(&levels) { @@ -127,6 +129,51 @@ pub struct TensorDistortion { pub section_bytes: u64, } +struct StreamVerifyRequest<'a> { + manifest: &'a Manifest, + source_dir: &'a Path, + archive_path: &'a Path, + streamed_levels: Option, + max_part_elements: u64, + ple_part_elements: Option, +} + +struct VerifiedShardedArchive { + identity: derived_mixed::ShardedIdentity, + archive_parts: Option>>, + summary: kar::Summary, + archive_digest: [u8; 32], +} + +struct ExpectedSourceRecord<'a> { + name: &'a str, + dimensions: &'a [u64], + digest: [u8; 32], + offset: u64, + bytes: u64, +} + +struct StreamProvenanceRequest<'a> { + identity: &'a derived_mixed::ShardedIdentity, + parts: &'a [Vec], + levels: u8, + ple_part_elements: Option, + archive_path: &'a Path, + intent_path: &'a Path, +} + +struct StreamPublicationOps { + hash_archive: fn(&Path) -> Result<[u8; 32], String>, + write_sidecar: fn(&Path, &serde_json::Value) -> Result<(), String>, + remove_intent: fn(&Path) -> Result<(), String>, +} + +const FILE_PUBLICATION_OPS: StreamPublicationOps = StreamPublicationOps { + hash_archive: hash_file, + write_sidecar: write_provenance, + remove_intent: remove_pending_intent, +}; + struct PreparedTensor { name: String, dims: Vec, @@ -142,6 +189,27 @@ struct StreamedTensor { nested: bool, } +struct StreamPrepareRequest<'a> { + manifest: &'a Manifest, + source_dir: &'a Path, + destination: &'a Path, + levels: u8, + max_part_elements: u64, + ple_part_elements: Option, +} + +struct StreamPreparation<'a> { + request: StreamPrepareRequest<'a>, + identity: derived_mixed::ShardedIdentity, + archive_parts: Vec>, + staging: StagingDir, + architecture: Option, + prepared: Vec, + maximum_relative_l2: f64, + tensor_distortions: Vec, + tensor_number: usize, +} + struct StagingDir(PathBuf); impl Drop for StagingDir { @@ -376,14 +444,14 @@ pub fn prepare_sharded_streamed_ple( ple_part_elements: u64, ) -> Result { stream_parts::validate_ple_limit(ple_part_elements)?; - prepare_sharded_streamed_with_policy( + prepare_sharded_streamed_with_policy(StreamPrepareRequest { manifest, source_dir, destination, levels, - stream_parts::MAX_PART_ELEMENTS, - Some(ple_part_elements), - ) + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: Some(ple_part_elements), + }) } fn prepare_sharded_streamed_with_limit( @@ -393,38 +461,193 @@ fn prepare_sharded_streamed_with_limit( levels: u8, max_part_elements: u64, ) -> Result { - prepare_sharded_streamed_with_policy( + prepare_sharded_streamed_with_policy(StreamPrepareRequest { manifest, source_dir, destination, levels, max_part_elements, - None, - ) + ple_part_elements: None, + }) } fn prepare_sharded_streamed_with_policy( - manifest: &Manifest, - source_dir: &Path, - destination: &Path, - levels: u8, - max_part_elements: u64, - ple_part_elements: Option, + request: StreamPrepareRequest<'_>, ) -> Result { - if !(1..=8).contains(&levels) { + if !(1..=8).contains(&request.levels) { return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); } + ensure_output_is_free(request.destination)?; + let identity = derived_mixed::fingerprint_shards(request.manifest, request.source_dir)?; + let archive_parts = plan_stream_parts(&request, &identity)?; + require_streamed_space(request.destination, &archive_parts, request.levels)?; + let staging = StagingDir::create(request.destination)?; + StreamPreparation::new(request, identity, archive_parts, staging).run() +} + +fn ensure_output_is_free(destination: &Path) -> Result<(), String> { if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(provenance_path(destination)?).is_ok() { return Err("KAR archive or provenance destination already exists".into()); } - let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; - let archive_parts = if let Some(limit) = ple_part_elements { - stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)? - } else { - stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)? + Ok(()) +} + +fn streamed_publish_intent_path(destination: &Path) -> Result { + Ok(destination.with_file_name(format!( + "{}.pending.json", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy() + ))) +} + +fn ensure_pending_intent(path: &Path, expected: &serde_json::Value) -> Result<(), String> { + match read_json_if_regular(path)? { + Some(existing) if existing == *expected => Ok(()), + Some(_) => Err("KAR publish intent differs from requested source or policy".into()), + None => write_provenance(path, expected), + } +} + +fn read_json_if_regular(path: &Path) -> Result, String> { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => { + let file = File::open(path).map_err(|error| error.to_string())?; + serde_json::from_reader(file) + .map(Some) + .map_err(|error| error.to_string()) + } + Ok(_) => Err("KAR publish intent must be a regular file".into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error.to_string()), + } +} + +fn remove_pending_intent(path: &Path) -> Result<(), String> { + match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error.to_string()), + } +} + +pub(crate) fn has_pending_streamed_publication(destination: &Path) -> Result { + match fs::symlink_metadata(provenance_path(destination)?) { + Ok(_) => return Ok(false), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.to_string()), + } + let pending = streamed_publish_intent_path(destination)?; + match fs::symlink_metadata(&pending) { + Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err("KAR publish intent must be a regular file".into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.to_string()), + } +} + +pub(crate) fn recover_sharded_streamed_provenance( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + levels: u8, + ple_part_elements: Option, +) -> Result, String> { + let request = StreamVerifyRequest { + manifest, + source_dir, + archive_path, + streamed_levels: Some(levels), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements, }; + recover_streamed_publication(&request, &FILE_PUBLICATION_OPS) +} + +fn recover_streamed_publication( + request: &StreamVerifyRequest<'_>, + ops: &StreamPublicationOps, +) -> Result, String> { + let intent_path = streamed_publish_intent_path(request.archive_path)?; + let Some(verified) = verify_if_intended(request, &intent_path)? else { + return Ok(None); + }; + validate_streamed_levels(request, &verified.summary)?; + let provenance_request = StreamProvenanceRequest { + identity: &verified.identity, + parts: verified + .archive_parts + .as_deref() + .ok_or("missing streamed KAR part plan")?, + levels: request + .streamed_levels + .ok_or("missing streamed KAR levels")?, + ple_part_elements: request.ple_part_elements, + archive_path: request.archive_path, + intent_path: &intent_path, + }; + finalize_streamed_publication(&provenance_request, ops)?; + Ok(Some(verified.summary)) +} + +fn verify_if_intended( + request: &StreamVerifyRequest<'_>, + intent_path: &Path, +) -> Result, String> { + let Some(intent) = read_json_if_regular(intent_path)? else { + return Ok(None); + }; + let verified = verify_sharded_archive(request)?; + let parts = verified + .archive_parts + .as_deref() + .ok_or("missing streamed KAR part plan")?; + let levels = request + .streamed_levels + .ok_or("missing streamed KAR levels")?; + let expected = + streamed_publish_intent(&verified.identity, parts, levels, request.ple_part_elements); + if intent != expected { + return Err("KAR publish intent differs from verified source or policy".into()); + } + Ok(Some(verified)) +} + +fn validate_streamed_levels( + request: &StreamVerifyRequest<'_>, + summary: &kar::Summary, +) -> Result<(), String> { + if let Some(levels) = request.streamed_levels + && summary.max_planes > levels + { + return Err("KAR stream levels exceed declared preparation level".into()); + } + Ok(()) +} + +fn plan_stream_parts( + request: &StreamPrepareRequest<'_>, + identity: &derived_mixed::ShardedIdentity, +) -> Result>, String> { + if let Some(limit) = request.ple_part_elements { + stream_parts::plan_shards_with_ple_limit(identity, request.source_dir, limit) + } else { + stream_parts::plan_shards_with_limit( + identity, + request.source_dir, + request.max_part_elements, + ) + } +} + +fn require_streamed_space( + destination: &Path, + archive_parts: &[Vec], + levels: u8, +) -> Result<(), String> { let archive_tensor_count = archive_parts.iter().map(Vec::len).sum::(); if archive_tensor_count == 0 || archive_tensor_count > 100_000 { return Err("streamed sharded tensor count exceeds KAR-2 limits".into()); @@ -446,228 +669,431 @@ fn prepare_sharded_streamed_with_policy( .unwrap_or(Path::new(".")); model::require_space(destination_parent, minimum_payload_bytes) .map_err(|error| format!("KAR minimum payload does not fit: {error}"))?; - let staging_path = destination.with_file_name(format!( - "{}.stream-parts-{}", - destination - .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy(), - std::process::id() - )); - fs::create_dir(&staging_path).map_err(|error| error.to_string())?; - let staging = StagingDir(staging_path); - let mut architecture = None::; - let mut prepared = Vec::with_capacity(archive_tensor_count); - let mut maximum_relative_l2 = 0.0f64; - let mut tensor_distortions = Vec::with_capacity(archive_tensor_count); - let mut number = 0usize; - for shard in &identity.shards { - let path = source_dir.join(&shard.name); + Ok(()) +} + +impl StagingDir { + fn create(destination: &Path) -> Result { + let path = destination.with_file_name(format!( + "{}.stream-parts-{}", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy(), + std::process::id() + )); + fs::create_dir(&path).map_err(|error| error.to_string())?; + Ok(Self(path)) + } +} + +impl<'a> StreamPreparation<'a> { + fn new( + request: StreamPrepareRequest<'a>, + identity: derived_mixed::ShardedIdentity, + archive_parts: Vec>, + staging: StagingDir, + ) -> Self { + let count = archive_parts.iter().map(Vec::len).sum(); + Self { + request, + identity, + archive_parts, + staging, + architecture: None, + prepared: Vec::with_capacity(count), + maximum_relative_l2: 0.0, + tensor_distortions: Vec::with_capacity(count), + tensor_number: 0, + } + } + + fn run(mut self) -> Result { + for index in 0..self.identity.shards.len() { + let source = &self.identity.shards[index]; + let shard = derived_mixed::ShardIdentity { + name: source.name.clone(), + gguf_sha256: source.gguf_sha256, + gguf_bytes: source.gguf_bytes, + tensor_count: source.tensor_count, + }; + self.prepare_shard(&shard)?; + } + if self.tensor_number != self.identity.tensors.len() { + return Err("GGUF tensor count changed during preparation".into()); + } + self.publish() + } + + fn prepare_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> { + let path = self.request.source_dir.join(&shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - if let Some(shard_architecture) = index.summary.architecture.as_deref() { - if architecture + self.check_shard_index(shard, &index)?; + let mut source = File::open(&path).map_err(|error| error.to_string())?; + for tensor in &index.tensors { + self.prepare_tensor(&index, &mut source, tensor)?; + } + self.verify_shard_file(shard, &path, &source) + } + + fn check_shard_index( + &mut self, + shard: &derived_mixed::ShardIdentity, + index: &gguf::TensorIndex, + ) -> Result<(), String> { + if let Some(architecture) = index.summary.architecture.as_deref() { + if self + .architecture .as_deref() - .is_some_and(|expected| expected != shard_architecture) + .is_some_and(|expected| expected != architecture) { return Err("GGUF shard architectures differ".into()); } - architecture.get_or_insert_with(|| shard_architecture.to_owned()); + self.architecture + .get_or_insert_with(|| architecture.to_owned()); } if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes { return Err("GGUF shard changed after identity derivation".into()); } - let mut source = File::open(&path).map_err(|error| error.to_string())?; - for tensor in &index.tensors { - if tensor.dimensions.len() > 4 { - return Err(format!( - "{}: KAR-2 supports up to four dimensions", - tensor.name - )); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |count, dim| count.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - let derived = &identity.tensors[number]; - if derived.name != tensor.name - || derived.source_kind != tensor.kind - || derived.derived_bytes - != elements - .checked_mul(4) - .ok_or("F32 tensor byte count overflow")? - { - return Err(format!("{}: sharded tensor identity mismatch", tensor.name)); - } - let absolute_base = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - for part in &archive_parts[number] { - let absolute = absolute_base - .checked_add(part.source_byte_offset) - .ok_or("GGUF part offset overflow")?; - let sample = kar_sample::sample_normalized( - &mut source, - absolute, - part.source_kind, - part.source_bytes, - part.derived_bytes / 4, - part.source_sha256, - kar_sample::MAX_SAMPLE_VALUES, - )?; - let calibration = kar_codec::fit_topdown(&sample, levels).ok(); - let section_path = staging.0.join(format!("{:06}.section", prepared.len())); - let (section_bytes, section_digest, nested, relative_l2) = - if let Some(calibration) = calibration { - let result = kar_stream_encode::encode_section( - &mut source, - absolute, - part.source_kind, - part.source_bytes, - part.derived_bytes / 4, - &calibration, - §ion_path, - )?; - if result.source_digest != part.source_sha256 - || result.derived_digest != part.f32_sha256 - { - return Err(format!( - "{}: streamed source or F32 digest mismatch", - part.name - )); - } - (result.bytes, result.digest, true, result.relative_l2) - } else { - let result = spool_raw_f32( - &mut source, - absolute, - part.source_kind, - part.source_bytes, - §ion_path, - )?; - if result.0 != part.source_sha256 - || result.1 != part.f32_sha256 - || result.2 != part.derived_bytes - { - return Err(format!( - "{}: streamed RAW source or F32 digest mismatch", - part.name - )); - } - (result.2, result.1, false, 0.0) - }; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - tensor_distortions.push(TensorDistortion { - name: part.name.clone(), - relative_l2, - source_kind: part.source_kind, - section_bytes, - }); - prepared.push(StreamedTensor { - prepared: PreparedTensor { - name: part.name.clone(), - dims: part.dimensions.clone(), - source_digest: part.f32_sha256, - source_offset: part.derived_offset, - section_path, - section_bytes, - section_digest, - }, - nested, - }); - } - number += 1; + Ok(()) + } + + fn prepare_tensor( + &mut self, + index: &gguf::TensorIndex, + source: &mut File, + tensor: &gguf::TensorInfo, + ) -> Result<(), String> { + let derived = self + .identity + .tensors + .get(self.tensor_number) + .ok_or("GGUF tensor count differs from sharded identity")?; + validate_tensor_identity(tensor, derived)?; + let base = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + let parts = self.archive_parts[self.tensor_number].clone(); + for part in &parts { + self.prepare_part(source, base, part)?; } + self.tensor_number += 1; + Ok(()) + } + + fn prepare_part( + &mut self, + source: &mut File, + tensor_base: u64, + part: &stream_parts::PartIdentity, + ) -> Result<(), String> { + let absolute = tensor_base + .checked_add(part.source_byte_offset) + .ok_or("GGUF part offset overflow")?; + let section_path = self + .staging + .0 + .join(format!("{:06}.section", self.prepared.len())); + let result = + encode_stream_part(source, absolute, part, self.request.levels, §ion_path)?; + self.record_part(part, section_path, result) + } + + fn record_part( + &mut self, + part: &stream_parts::PartIdentity, + section_path: PathBuf, + result: EncodedPart, + ) -> Result<(), String> { + self.maximum_relative_l2 = self.maximum_relative_l2.max(result.relative_l2); + self.tensor_distortions.push(TensorDistortion { + name: part.name.clone(), + relative_l2: result.relative_l2, + source_kind: part.source_kind, + section_bytes: result.bytes, + }); + self.prepared.push(StreamedTensor { + prepared: PreparedTensor { + name: part.name.clone(), + dims: part.dimensions.clone(), + source_digest: part.f32_sha256, + source_offset: part.derived_offset, + section_path, + section_bytes: result.bytes, + section_digest: result.digest, + }, + nested: result.nested, + }); + Ok(()) + } + + fn verify_shard_file( + &self, + shard: &derived_mixed::ShardIdentity, + path: &Path, + source: &File, + ) -> Result<(), String> { if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes - || hash_file(&path)? != shard.gguf_sha256 + || hash_file(path)? != shard.gguf_sha256 { return Err(format!( "{}: GGUF shard changed during preparation", shard.name )); } + Ok(()) } - let tensors = prepared - .iter() - .map(|entry| { - let tensor = &entry.prepared; - kar_writer::Tensor { - name: &tensor.name, - dims: &tensor.dims, - source_dtype: 0, - source_digest: tensor.source_digest, - source_offset: tensor.source_offset, - data: if entry.nested { - kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - levels, - path: &tensor.section_path, - offset: 0, - bytes: tensor.section_bytes, - digest: tensor.section_digest, - } - } else { - kar_writer::TensorData::RawFile { - path: &tensor.section_path, - offset: 0, - bytes: tensor.section_bytes, - } - }, - } + + fn publish(self) -> Result { + let intent_path = streamed_publish_intent_path(self.request.destination)?; + let intent = streamed_publish_intent( + &self.identity, + &self.archive_parts, + self.request.levels, + self.request.ple_part_elements, + ); + ensure_pending_intent(&intent_path, &intent)?; + let archive = self.write_archive()?; + self.publish_provenance(archive, intent_path) + } + + fn write_archive(&self) -> Result { + let architecture = self + .architecture + .as_deref() + .ok_or("GGUF shards have no architecture")?; + let builder = streamed_builder(&self.request); + let source_identity = kar_writer::SourceIdentity { + name: "gguf-shards#derived-f32-le-v4", + architecture, + builder: &builder, + digest: self.identity.derived_sha256, + total_elements: self.identity.derived_bytes / 4, + bytes: self.identity.derived_bytes, + }; + let tensors = self.writer_tensors(); + kar_writer::write_archive_consuming_files( + self.request.destination, + &source_identity, + &tensors, + ) + } + + fn writer_tensors(&self) -> Vec> { + self.prepared + .iter() + .map(|entry| writer_tensor(entry, self.request.levels)) + .collect() + } + + fn publish_provenance( + self, + archive: kar::Summary, + intent_path: PathBuf, + ) -> Result { + let provenance_request = StreamProvenanceRequest { + identity: &self.identity, + parts: &self.archive_parts, + levels: self.request.levels, + ple_part_elements: self.request.ple_part_elements, + archive_path: self.request.destination, + intent_path: &intent_path, + }; + let archive_digest = + finalize_streamed_publication(&provenance_request, &FILE_PUBLICATION_OPS)?; + let provenance_path = provenance_path(self.request.destination)?; + Ok(PreviewSummary { + archive, + archive_digest, + maximum_relative_l2: self.maximum_relative_l2, + tensor_distortions: self.tensor_distortions, + provenance_path: Some(provenance_path), }) - .collect::>(); - let builder = if let Some(limit) = ple_part_elements { + } +} + +fn writer_tensor(entry: &StreamedTensor, levels: u8) -> kar_writer::Tensor<'_> { + let tensor = &entry.prepared; + let data = if entry.nested { + kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + levels, + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + digest: tensor.section_digest, + } + } else { + kar_writer::TensorData::RawFile { + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + } + }; + kar_writer::Tensor { + name: &tensor.name, + dims: &tensor.dims, + source_dtype: 0, + source_digest: tensor.source_digest, + source_offset: tensor.source_offset, + data, + } +} + +fn finalize_streamed_publication( + request: &StreamProvenanceRequest<'_>, + ops: &StreamPublicationOps, +) -> Result<[u8; 32], String> { + let digest = (ops.hash_archive)(request.archive_path)?; + let provenance = streamed_provenance_value( + request.identity, + request.parts, + request.levels, + request.ple_part_elements, + digest, + ); + let path = provenance_path(request.archive_path)?; + (ops.write_sidecar)(&path, &provenance)?; + let _ = (ops.remove_intent)(request.intent_path); + Ok(digest) +} + +struct EncodedPart { + bytes: u64, + digest: [u8; 32], + nested: bool, + relative_l2: f64, +} + +fn validate_tensor_identity( + tensor: &gguf::TensorInfo, + derived: &derived_mixed::TensorIdentity, +) -> Result<(), String> { + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |count, dim| count.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + if tensor.dimensions.len() > 4 { + return Err(format!( + "{}: KAR-2 supports up to four dimensions", + tensor.name + )); + } + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || derived.derived_bytes + != elements + .checked_mul(4) + .ok_or("F32 tensor byte count overflow")? + { + return Err(format!("{}: sharded tensor identity mismatch", tensor.name)); + } + Ok(()) +} + +fn encode_stream_part( + source: &mut File, + absolute: u64, + part: &stream_parts::PartIdentity, + levels: u8, + section_path: &Path, +) -> Result { + let sample = kar_sample::sample_normalized( + source, + absolute, + part.source_kind, + part.source_bytes, + part.derived_bytes / 4, + part.source_sha256, + kar_sample::MAX_SAMPLE_VALUES, + )?; + match kar_codec::fit_topdown(&sample, levels) { + Ok(calibration) => encode_nested_part(source, absolute, part, &calibration, section_path), + Err(_) => encode_raw_part(source, absolute, part, section_path), + } +} + +fn encode_nested_part( + source: &mut File, + absolute: u64, + part: &stream_parts::PartIdentity, + calibration: &kar_codec::Calibration, + section_path: &Path, +) -> Result { + let result = kar_stream_encode::encode_section( + source, + &kar_stream_encode::SectionRequest { + absolute_offset: absolute, + source_kind: part.source_kind, + source_bytes: part.source_bytes, + elements: part.derived_bytes / 4, + calibration, + destination: section_path, + }, + )?; + if result.source_digest != part.source_sha256 || result.derived_digest != part.f32_sha256 { + return Err(format!( + "{}: streamed source or F32 digest mismatch", + part.name + )); + } + Ok(EncodedPart { + bytes: result.bytes, + digest: result.digest, + nested: true, + relative_l2: result.relative_l2, + }) +} + +fn encode_raw_part( + source: &mut File, + absolute: u64, + part: &stream_parts::PartIdentity, + section_path: &Path, +) -> Result { + let (source_digest, derived_digest, bytes) = spool_raw_f32( + source, + absolute, + part.source_kind, + part.source_bytes, + section_path, + )?; + if source_digest != part.source_sha256 + || derived_digest != part.f32_sha256 + || bytes != part.derived_bytes + { + return Err(format!( + "{}: streamed RAW source or F32 digest mismatch", + part.name + )); + } + Ok(EncodedPart { + bytes, + digest: derived_digest, + nested: false, + relative_l2: 0.0, + }) +} + +fn streamed_builder(request: &StreamPrepareRequest<'_>) -> String { + if let Some(limit) = request.ple_part_elements { format!( - "strata-next/experimental-sharded-stream-v5:g32:l{levels}:sample65536:plepart{limit}" + "strata-next/experimental-sharded-stream-v5:g32:l{}:sample65536:plepart{limit}", + request.levels ) } else { - format!("strata-next/experimental-sharded-stream-v4:g32:l{levels}:sample65536") - }; - let source_identity = kar_writer::SourceIdentity { - name: "gguf-shards#derived-f32-le-v4", - architecture: architecture - .as_deref() - .ok_or("GGUF shards have no architecture")?, - builder: &builder, - digest: identity.derived_sha256, - total_elements: identity.derived_bytes / 4, - bytes: identity.derived_bytes, - }; - let archive = - kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors)?; - let archive_digest = hash_file(destination)?; - let provenance_path = provenance_path(destination)?; - let mut provenance = sharded_provenance_value(&identity, archive_digest); - provenance["schema"] = serde_json::json!(if ple_part_elements.is_some() { - "strata-next/sharded-stream-provenance-v5" - } else { - "strata-next/sharded-stream-provenance-v4" - }); - provenance["derivation"] = - serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); - provenance["levels"] = serde_json::json!(levels); - provenance["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); - provenance["partitioned_tensors"] = partitioned_provenance(&archive_parts); - if let Some(limit) = ple_part_elements { - provenance["ple_part_elements"] = serde_json::json!(limit); + format!( + "strata-next/experimental-sharded-stream-v4:g32:l{}:sample65536", + request.levels + ) } - if let Err(error) = write_provenance(&provenance_path, &provenance) { - let _ = fs::remove_file(destination); - return Err(error); - } - Ok(PreviewSummary { - archive, - archive_digest, - maximum_relative_l2, - tensor_distortions, - provenance_path: Some(provenance_path), - }) } fn spool_raw_f32( @@ -1011,14 +1437,14 @@ pub fn verify_sharded( source_dir: &Path, archive_path: &Path, ) -> Result { - verify_sharded_inner( + verify_sharded_inner(StreamVerifyRequest { manifest, source_dir, archive_path, - None, - stream_parts::MAX_PART_ELEMENTS, - None, - ) + streamed_levels: None, + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + }) } pub fn verify_sharded_streamed( @@ -1030,14 +1456,14 @@ pub fn verify_sharded_streamed( if !(1..=8).contains(&levels) { return Err("streamed sharded verification requires 1..=8 KAR levels".into()); } - verify_sharded_inner( + verify_sharded_inner(StreamVerifyRequest { manifest, source_dir, archive_path, - Some(levels), - stream_parts::MAX_PART_ELEMENTS, - None, - ) + streamed_levels: Some(levels), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + }) } pub fn verify_sharded_streamed_ple( @@ -1051,118 +1477,189 @@ pub fn verify_sharded_streamed_ple( if !(1..=8).contains(&levels) { return Err("streamed sharded verification requires 1..=8 KAR levels".into()); } - verify_sharded_inner( + verify_sharded_inner(StreamVerifyRequest { manifest, source_dir, archive_path, - Some(levels), - stream_parts::MAX_PART_ELEMENTS, - Some(ple_part_elements), - ) + streamed_levels: Some(levels), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: Some(ple_part_elements), + }) } -fn verify_sharded_inner( - manifest: &Manifest, - source_dir: &Path, - archive_path: &Path, - streamed_levels: Option, - max_part_elements: u64, - ple_part_elements: Option, -) -> Result { - let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; - let archive_parts = if streamed_levels.is_some() { - Some(if let Some(limit) = ple_part_elements { - stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)? +fn verify_sharded_inner(request: StreamVerifyRequest<'_>) -> Result { + let verified = verify_sharded_archive(&request)?; + verify_sharded_provenance(&request, &verified)?; + Ok(verified.summary) +} + +fn verify_sharded_archive( + request: &StreamVerifyRequest<'_>, +) -> Result { + let identity = derived_mixed::fingerprint_shards(request.manifest, request.source_dir)?; + let archive_parts = if request.streamed_levels.is_some() { + Some(if let Some(limit) = request.ple_part_elements { + stream_parts::plan_shards_with_ple_limit(&identity, request.source_dir, limit)? } else { - stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)? + stream_parts::plan_shards_with_limit( + &identity, + request.source_dir, + request.max_part_elements, + )? }) } else { None }; - let (summary, sources) = kar::verify_with_sources(archive_path)?; - let expected_count = archive_parts - .as_ref() - .map_or(identity.tensors.len(), |parts| { - parts.iter().map(Vec::len).sum() - }); + let (summary, sources) = kar::verify_with_sources(request.archive_path)?; + verify_sharded_header(&identity, archive_parts.as_deref(), &summary, sources.len())?; + verify_sharded_records(&identity, archive_parts.as_deref(), &sources)?; + let archive_digest = hash_file(request.archive_path)?; + Ok(VerifiedShardedArchive { + identity, + archive_parts, + summary, + archive_digest, + }) +} + +fn verify_sharded_header( + identity: &derived_mixed::ShardedIdentity, + archive_parts: Option<&[Vec]>, + summary: &kar::Summary, + source_count: usize, +) -> Result<(), String> { + let expected_count = archive_parts.map_or(identity.tensors.len(), |parts| { + parts.iter().map(Vec::len).sum() + }); if summary.source_digest != identity.derived_sha256 || summary.source_bytes != identity.derived_bytes || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes) - || sources.len() != expected_count + || source_count != expected_count { return Err("KAR header differs from sharded derived source".into()); } - if let Some(parts) = &archive_parts { - for (record, part) in sources.iter().zip(parts.iter().flatten()) { - let record_bytes = record - .dimensions - .iter() - .try_fold(4u64, |size, dim| size.checked_mul(*dim)) - .ok_or("KAR tensor source byte count overflow")?; - if record.name != part.name - || record.dimensions != part.dimensions - || record.dtype != 0 - || record.digest != part.f32_sha256 - || record.offset != part.derived_offset - || record_bytes != part.derived_bytes - { - return Err(format!("{}: sharded KAR part source mismatch", part.name)); - } - } + Ok(()) +} + +fn verify_sharded_records( + identity: &derived_mixed::ShardedIdentity, + archive_parts: Option<&[Vec]>, + sources: &[kar::TensorSource], +) -> Result<(), String> { + if let Some(parts) = archive_parts { + verify_part_records(sources, parts) } else { - for (record, tensor) in sources.iter().zip(&identity.tensors) { - let record_bytes = record - .dimensions - .iter() - .try_fold(4u64, |size, dim| size.checked_mul(*dim)) - .ok_or("KAR tensor source byte count overflow")?; - if record.name != tensor.name - || record.dtype != 0 - || record.digest != tensor.f32_sha256 - || record.offset != tensor.derived_offset - || record_bytes != tensor.derived_bytes - { - return Err(format!( - "{}: sharded KAR tensor source mismatch", - tensor.name - )); - } + verify_tensor_records(sources, &identity.tensors) + } +} + +fn verify_part_records( + sources: &[kar::TensorSource], + parts: &[Vec], +) -> Result<(), String> { + for (record, part) in sources.iter().zip(parts.iter().flatten()) { + verify_source_record( + record, + ExpectedSourceRecord { + name: &part.name, + dimensions: &part.dimensions, + digest: part.f32_sha256, + offset: part.derived_offset, + bytes: part.derived_bytes, + }, + )?; + } + Ok(()) +} + +fn verify_tensor_records( + sources: &[kar::TensorSource], + tensors: &[derived_mixed::TensorIdentity], +) -> Result<(), String> { + for (record, tensor) in sources.iter().zip(tensors) { + verify_source_record( + record, + ExpectedSourceRecord { + name: &tensor.name, + dimensions: &[], + digest: tensor.f32_sha256, + offset: tensor.derived_offset, + bytes: tensor.derived_bytes, + }, + )?; + if record + .dimensions + .iter() + .try_fold(1u64, |size, dim| size.checked_mul(*dim)) + != Some(tensor.derived_bytes / 4) + { + return Err(format!( + "{}: sharded KAR tensor shape mismatch", + tensor.name + )); } } - let archive_digest = hash_file(archive_path)?; - let provenance = provenance_path(archive_path)?; - let file = File::open(provenance).map_err(|error| error.to_string())?; + Ok(()) +} + +fn verify_source_record( + record: &kar::TensorSource, + expected: ExpectedSourceRecord<'_>, +) -> Result<(), String> { + let bytes = record + .dimensions + .iter() + .try_fold(4u64, |size, dim| size.checked_mul(*dim)) + .ok_or("KAR tensor source byte count overflow")?; + let dimensions_match = + expected.dimensions.is_empty() || record.dimensions == expected.dimensions; + if record.name != expected.name + || !dimensions_match + || record.dtype != 0 + || record.digest != expected.digest + || record.offset != expected.offset + || bytes != expected.bytes + { + return Err(format!( + "{}: sharded KAR source record mismatch", + expected.name + )); + } + Ok(()) +} + +fn verify_sharded_provenance( + request: &StreamVerifyRequest<'_>, + verified: &VerifiedShardedArchive, +) -> Result<(), String> { + validate_streamed_levels(request, &verified.summary)?; + let expected = expected_sharded_provenance(request, verified); + let file = + File::open(provenance_path(request.archive_path)?).map_err(|error| error.to_string())?; let recorded: serde_json::Value = serde_json::from_reader(file).map_err(|error| error.to_string())?; - let mut expected = sharded_provenance_value(&identity, archive_digest); - if let Some(levels) = streamed_levels { - if summary.max_planes > levels { - return Err("KAR stream levels exceed declared preparation level".into()); - } - expected["schema"] = serde_json::json!(if ple_part_elements.is_some() { - "strata-next/sharded-stream-provenance-v5" - } else { - "strata-next/sharded-stream-provenance-v4" - }); - expected["derivation"] = - serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); - expected["levels"] = serde_json::json!(levels); - expected["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); - expected["partitioned_tensors"] = partitioned_provenance( - archive_parts - .as_ref() - .ok_or("missing streamed KAR part plan")?, - ); - if let Some(limit) = ple_part_elements { - expected["ple_part_elements"] = serde_json::json!(limit); - } - } if recorded != expected { return Err( "sharded provenance differs from source, archive, or preparation policy".into(), ); } - Ok(summary) + Ok(()) +} + +fn expected_sharded_provenance( + request: &StreamVerifyRequest<'_>, + verified: &VerifiedShardedArchive, +) -> serde_json::Value { + match (request.streamed_levels, verified.archive_parts.as_deref()) { + (Some(levels), Some(parts)) => streamed_provenance_value( + &verified.identity, + parts, + levels, + request.ple_part_elements, + verified.archive_digest, + ), + _ => sharded_provenance_value(&verified.identity, verified.archive_digest), + } } fn verify_derived( @@ -1320,6 +1817,46 @@ fn sharded_provenance_value( }) } +fn streamed_provenance_value( + identity: &derived_mixed::ShardedIdentity, + parts: &[Vec], + levels: u8, + ple_part_elements: Option, + archive_digest: [u8; 32], +) -> serde_json::Value { + let mut value = sharded_provenance_value(identity, archive_digest); + value["schema"] = serde_json::json!(if ple_part_elements.is_some() { + "strata-next/sharded-stream-provenance-v5" + } else { + "strata-next/sharded-stream-provenance-v4" + }); + value["derivation"] = serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); + value["levels"] = serde_json::json!(levels); + value["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); + value["partitioned_tensors"] = partitioned_provenance(parts); + if let Some(limit) = ple_part_elements { + value["ple_part_elements"] = serde_json::json!(limit); + } + value +} + +fn streamed_publish_intent( + identity: &derived_mixed::ShardedIdentity, + parts: &[Vec], + levels: u8, + ple_part_elements: Option, +) -> serde_json::Value { + let mut value = streamed_provenance_value(identity, parts, levels, ple_part_elements, [0; 32]); + value + .as_object_mut() + .expect("provenance is an object") + .remove("archive_sha256"); + serde_json::json!({ + "schema": "strata-next/sharded-stream-publish-intent-v1", + "expected_provenance": value, + }) +} + fn partitioned_provenance(parts: &[Vec]) -> serde_json::Value { serde_json::json!( parts @@ -1347,30 +1884,63 @@ fn partitioned_provenance(parts: &[Vec]) -> serde_js } fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> { + write_provenance_with_ops(path, value, hard_link_path, remove_file_path) +} + +fn hard_link_path(source: &Path, destination: &Path) -> std::io::Result<()> { + fs::hard_link(source, destination) +} + +fn remove_file_path(path: &Path) -> std::io::Result<()> { + fs::remove_file(path) +} + +fn write_provenance_with_ops( + path: &Path, + value: &serde_json::Value, + publish: fn(&Path, &Path) -> std::io::Result<()>, + cleanup: fn(&Path) -> std::io::Result<()>, +) -> Result<(), String> { if fs::symlink_metadata(path).is_ok() { return Err("provenance destination already exists".into()); } - let temporary = path.with_file_name(format!( - "{}.part", - path.file_name() - .ok_or("provenance path has no file name")? - .to_string_lossy() - )); - let result = (|| { - let mut file = fs::OpenOptions::new() + let (temporary, mut file) = create_provenance_temp(path)?; + let result = write_provenance_contents(&mut file, value) + .and_then(|()| publish(&temporary, path).map_err(|error| error.to_string())); + if result.is_err() { + let _ = cleanup(&temporary); + return result; + } + let _ = cleanup(&temporary); + Ok(()) +} + +fn create_provenance_temp(path: &Path) -> Result<(PathBuf, File), String> { + let name = path + .file_name() + .ok_or("provenance path has no file name")? + .to_string_lossy(); + for _ in 0..64 { + let sequence = PROVENANCE_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let temporary = + path.with_file_name(format!("{name}.part-{}-{sequence}", std::process::id())); + match fs::OpenOptions::new() .write(true) .create_new(true) .open(&temporary) - .map_err(|error| error.to_string())?; - serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?; - use std::io::Write; - file.write_all(b"\n").map_err(|error| error.to_string())?; - file.sync_all().map_err(|error| error.to_string())?; - fs::hard_link(&temporary, path).map_err(|error| error.to_string())?; - Ok(()) - })(); - let _ = fs::remove_file(&temporary); - result + { + Ok(file) => return Ok((temporary, file)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.to_string()), + } + } + Err("could not allocate a unique provenance temporary file".into()) +} + +fn write_provenance_contents(file: &mut File, value: &serde_json::Value) -> Result<(), String> { + serde_json::to_writer_pretty(&mut *file, value).map_err(|error| error.to_string())?; + file.write_all(b"\n").map_err(|error| error.to_string())?; + file.sync_all().map_err(|error| error.to_string()) } fn hash_file(path: &Path) -> Result<[u8; 32], String> { @@ -1440,6 +2010,51 @@ mod tests { gguf } + fn two_f32_shard_manifest(directory: &Path) -> Manifest { + let f32_payload = (0..64) + .flat_map(|index| (index as f32).to_le_bytes()) + .collect::>(); + let mut iq3_block = vec![0u8; iq3_s::BLOCK_BYTES]; + iq3_block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let files = [ + ("a-f32.gguf", one_shard("dense", 0, 64, &f32_payload)), + ("z-iq3.gguf", one_shard("expert", 21, 256, &iq3_block)), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + Manifest { + schema_version: 1, + files, + } + } + + fn fail_archive_hash(_: &Path) -> Result<[u8; 32], String> { + Err("injected archive hash failure".into()) + } + + fn fail_sidecar(_: &Path, _: &serde_json::Value) -> Result<(), String> { + Err("injected provenance publication failure".into()) + } + + fn fail_intent_cleanup(_: &Path) -> Result<(), String> { + Err("injected intent cleanup failure".into()) + } + + fn fail_provenance_temp_cleanup(_: &Path) -> std::io::Result<()> { + Err(std::io::Error::other( + "injected provenance temporary cleanup failure", + )) + } + fn ple_shard(payload: &[u8]) -> Vec { let mut gguf = b"GGUF".to_vec(); gguf.extend_from_slice(&3u32.to_le_bytes()); @@ -2059,7 +2674,15 @@ mod tests { .all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite()) ); assert_eq!( - verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(), + verify_sharded_inner(StreamVerifyRequest { + manifest: &manifest, + source_dir: &directory, + archive_path: &archive, + streamed_levels: Some(2), + max_part_elements: 256, + ple_part_elements: None, + }) + .unwrap(), result.archive ); assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); @@ -2088,6 +2711,119 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } + #[tokio::test] + async fn streamed_publication_recovers_only_its_matching_archive_after_faults() { + let directory = std::env::temp_dir().join(format!( + "strata-stream-recovery-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&directory).unwrap(); + let manifest = two_f32_shard_manifest(&directory); + let archive = directory.join("recover.kar"); + let provenance = provenance_path(&archive).unwrap(); + let pending = streamed_publish_intent_path(&archive).unwrap(); + let prepared = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); + let expected_summary = prepared.archive; + fs::remove_file(&provenance).unwrap(); + let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); + let parts = stream_parts::plan_shards(&identity, &directory).unwrap(); + let intent = streamed_publish_intent(&identity, &parts, 2, None); + write_provenance(&pending, &intent).unwrap(); + let verify_request = StreamVerifyRequest { + manifest: &manifest, + source_dir: &directory, + archive_path: &archive, + streamed_levels: Some(2), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + }; + + let hash_failure = StreamPublicationOps { + hash_archive: fail_archive_hash, + write_sidecar: write_provenance, + remove_intent: remove_pending_intent, + }; + assert!(recover_streamed_publication(&verify_request, &hash_failure).is_err()); + assert!(archive.is_file() && pending.is_file() && !provenance.exists()); + + let provenance_failure = StreamPublicationOps { + hash_archive: hash_file, + write_sidecar: fail_sidecar, + remove_intent: remove_pending_intent, + }; + assert!(recover_streamed_publication(&verify_request, &provenance_failure).is_err()); + assert!(pending.is_file() && !provenance.exists()); + + fs::write(&provenance, b"unrelated reservation").unwrap(); + assert!(recover_streamed_publication(&verify_request, &FILE_PUBLICATION_OPS).is_err()); + assert_eq!(fs::read(&provenance).unwrap(), b"unrelated reservation"); + assert!(pending.is_file()); + fs::remove_file(&provenance).unwrap(); + + assert!(matches!( + crate::model_pipeline::ensure_sharded_streamed(&manifest, &directory, &archive, 2) + .await + .unwrap(), + crate::model_pipeline::PreviewOutcome::Reused(summary) if summary == expected_summary + )); + assert!(!pending.exists()); + fs::remove_file(&provenance).unwrap(); + write_provenance(&pending, &intent).unwrap(); + + let cleanup_failure = StreamPublicationOps { + hash_archive: hash_file, + write_sidecar: write_provenance, + remove_intent: fail_intent_cleanup, + }; + let recovered = recover_streamed_publication(&verify_request, &cleanup_failure).unwrap(); + assert_eq!(recovered.as_ref(), Some(&expected_summary)); + assert!(pending.is_file()); + assert_eq!( + verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), + expected_summary + ); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn published_provenance_remains_valid_when_its_temporary_link_cleanup_fails() { + let directory = std::env::temp_dir().join(format!( + "strata-provenance-cleanup-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&directory).unwrap(); + let destination = directory.join("artifact.provenance.json"); + let expected = serde_json::json!({"schema": "test/v1", "digest": "bound"}); + + write_provenance_with_ops( + &destination, + &expected, + hard_link_path, + fail_provenance_temp_cleanup, + ) + .unwrap(); + + let recorded: serde_json::Value = + serde_json::from_reader(File::open(&destination).unwrap()).unwrap(); + assert_eq!(recorded, expected); + let temporary = fs::read_dir(&directory) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| path != &destination) + .expect("injected cleanup failure should leave the hard-link name"); + fs::remove_file(temporary).unwrap(); + fs::remove_file(destination).unwrap(); + fs::remove_dir(directory).unwrap(); + } + #[test] fn ple_partition_policy_is_versioned_and_verified() { let directory = std::env::temp_dir().join(format!( diff --git a/control-plane/src/stream_parts.rs b/control-plane/src/stream_parts.rs index 7752baed..943f4a52 100644 --- a/control-plane/src/stream_parts.rs +++ b/control-plane/src/stream_parts.rs @@ -171,7 +171,14 @@ pub(crate) fn plan_shards_with_limit( source_dir: &Path, max_part_elements: u64, ) -> Result>, String> { - plan_shards_with_limits(identity, source_dir, max_part_elements, None) + plan_shards_with_limits( + identity, + source_dir, + PlanLimits { + max_part_elements, + ple_part_elements: None, + }, + ) } pub fn plan_shards_with_ple_limit( @@ -183,117 +190,269 @@ pub fn plan_shards_with_ple_limit( plan_shards_with_limits( identity, source_dir, - MAX_PART_ELEMENTS, - Some(ple_part_elements), + PlanLimits { + max_part_elements: MAX_PART_ELEMENTS, + ple_part_elements: Some(ple_part_elements), + }, ) } fn plan_shards_with_limits( identity: &derived_mixed::ShardedIdentity, source_dir: &Path, + limits: PlanLimits, +) -> Result>, String> { + ShardPlanner::new(identity, source_dir, limits).plan() +} + +#[derive(Clone, Copy)] +struct PlanLimits { max_part_elements: u64, ple_part_elements: Option, -) -> Result>, String> { - let mut result = Vec::with_capacity(identity.tensors.len()); - let mut names = HashSet::new(); - let mut number = 0usize; - let mut saw_ple = false; - for shard in &identity.shards { - let path = source_dir.join(&shard.name); +} + +struct ShardPlanner<'a> { + identity: &'a derived_mixed::ShardedIdentity, + source_dir: &'a Path, + limits: PlanLimits, + result: Vec>, + names: HashSet, + number: usize, + saw_ple: bool, +} + +struct ParentHashes { + source: Sha256, + f32: Sha256, +} + +struct PartBuildContext<'a> { + index: &'a gguf::TensorIndex, + tensor: &'a gguf::TensorInfo, + original: &'a derived_mixed::TensorIdentity, + split: bool, +} + +impl<'a> ShardPlanner<'a> { + fn new( + identity: &'a derived_mixed::ShardedIdentity, + source_dir: &'a Path, + limits: PlanLimits, + ) -> Self { + Self { + identity, + source_dir, + limits, + result: Vec::with_capacity(identity.tensors.len()), + names: HashSet::new(), + number: 0, + saw_ple: false, + } + } + + fn plan(mut self) -> Result>, String> { + for shard in &self.identity.shards { + self.plan_shard(shard)?; + } + if self.number != self.identity.tensors.len() { + return Err("GGUF tensor count differs from virtual source".into()); + } + if self.limits.ple_part_elements.is_some() && !self.saw_ple { + return Err("PLE partition policy requires per_layer_token_embd.weight".into()); + } + Ok(self.result) + } + + fn plan_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> { + let path = self.source_dir.join(&shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; if index.tensors.len() != shard.tensor_count { return Err("GGUF shard changed during KAR part planning".into()); } - let mut source = File::open(&path).map_err(|error| error.to_string())?; + let mut source = File::open(path).map_err(|error| error.to_string())?; for tensor in &index.tensors { - let original = identity - .tensors - .get(number) - .ok_or("GGUF tensor count differs from virtual source")?; - if original.name != tensor.name || original.source_kind != tensor.kind { - return Err("GGUF tensor differs from virtual source".into()); - } - let part_limit = if tensor.name == PLE_TENSOR_NAME { - saw_ple = true; - ple_part_elements.unwrap_or(max_part_elements) - } else { - max_part_elements - }; - let layouts = layout_with_limit(tensor, original.derived_offset, part_limit)?; - if tensor.name == PLE_TENSOR_NAME && ple_part_elements.is_some() && layouts.len() < 2 { - return Err("PLE part limit must split the PLE tensor".into()); - } - let split = layouts.len() > 1; - let mut parent_source = Sha256::new(); - let mut parent_f32 = Sha256::new(); - let mut parts = Vec::with_capacity(layouts.len()); - for part in layouts { - if !names.insert(part.name.clone()) { - return Err(format!("duplicate KAR part name: {}", part.name)); - } - let (source_sha256, f32_sha256) = if split { - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|n| n.checked_add(part.source_byte_offset)) - .ok_or("GGUF part offset overflow")?; - let mut source_hash = Sha256::new(); - let mut f32_hash = Sha256::new(); - let count = gguf_f32_stream::visit( - &mut source, - absolute, - tensor.kind, - part.source_bytes, - |raw, f32_bytes| { - source_hash.update(raw); - f32_hash.update(f32_bytes); - parent_source.update(raw); - parent_f32.update(f32_bytes); - Ok(()) - }, - )?; - if count != part.derived_bytes { - return Err("GGUF part derived byte count mismatch".into()); - } - (source_hash.finalize().into(), f32_hash.finalize().into()) - } else { - (original.source_sha256, original.f32_sha256) - }; - parts.push(PartIdentity { - name: part.name, - parent_name: tensor.name.clone(), - parent_dimensions: tensor.dimensions.clone(), - dimensions: part.dimensions, - source_kind: tensor.kind, - source_byte_offset: part.source_byte_offset, - source_bytes: part.source_bytes, - source_sha256, - derived_offset: part.derived_offset, - derived_bytes: part.derived_bytes, - f32_sha256, - }); - } - if split - && (parent_source.finalize().as_slice() != original.source_sha256 - || parent_f32.finalize().as_slice() != original.f32_sha256) - { - return Err(format!( - "{}: KAR part hashes differ from source", - tensor.name - )); - } - result.push(parts); - number += 1; + self.plan_tensor(&index, &mut source, tensor)?; + } + Ok(()) + } + + fn plan_tensor( + &mut self, + index: &gguf::TensorIndex, + source: &mut File, + tensor: &gguf::TensorInfo, + ) -> Result<(), String> { + self.validate_original_tensor(tensor)?; + let derived_offset = self.identity.tensors[self.number].derived_offset; + let part_limit = self.part_limit(tensor); + let layouts = layout_with_limit(tensor, derived_offset, part_limit)?; + self.require_ple_split(tensor, &layouts)?; + let original = &self.identity.tensors[self.number]; + let context = PartBuildContext { + index, + tensor, + original, + split: layouts.len() > 1, + }; + let parts = self.build_parts(source, layouts, context)?; + self.register_parts(parts) + } + + fn validate_original_tensor(&self, tensor: &gguf::TensorInfo) -> Result<(), String> { + let original = self + .identity + .tensors + .get(self.number) + .ok_or("GGUF tensor count differs from virtual source")?; + if original.name != tensor.name || original.source_kind != tensor.kind { + return Err("GGUF tensor differs from virtual source".into()); + } + Ok(()) + } + + fn part_limit(&mut self, tensor: &gguf::TensorInfo) -> u64 { + if tensor.name == PLE_TENSOR_NAME { + self.saw_ple = true; + self.limits + .ple_part_elements + .unwrap_or(self.limits.max_part_elements) + } else { + self.limits.max_part_elements } } - if number != identity.tensors.len() { - return Err("GGUF tensor count differs from virtual source".into()); + + fn require_ple_split( + &self, + tensor: &gguf::TensorInfo, + layouts: &[Layout], + ) -> Result<(), String> { + if tensor.name == PLE_TENSOR_NAME + && self.limits.ple_part_elements.is_some() + && layouts.len() < 2 + { + return Err("PLE part limit must split the PLE tensor".into()); + } + Ok(()) } - if ple_part_elements.is_some() && !saw_ple { - return Err("PLE partition policy requires per_layer_token_embd.weight".into()); + + fn build_parts( + &self, + source: &mut File, + layouts: Vec, + context: PartBuildContext<'_>, + ) -> Result, String> { + let mut hashes = ParentHashes { + source: Sha256::new(), + f32: Sha256::new(), + }; + let mut parts = Vec::with_capacity(layouts.len()); + for layout in layouts { + parts.push(self.build_part(source, &layout, &context, &mut hashes)?); + } + self.verify_parent_hashes(context.tensor, context.original, context.split, hashes)?; + Ok(parts) } - Ok(result) + + fn build_part( + &self, + source: &mut File, + layout: &Layout, + context: &PartBuildContext<'_>, + hashes: &mut ParentHashes, + ) -> Result { + let tensor = context.tensor; + let (source_sha256, f32_sha256) = if context.split { + hash_layout( + source, + context.index.summary.data_start, + tensor, + layout, + hashes, + )? + } else { + (context.original.source_sha256, context.original.f32_sha256) + }; + Ok(PartIdentity { + name: layout.name.clone(), + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: layout.dimensions.clone(), + source_kind: tensor.kind, + source_byte_offset: layout.source_byte_offset, + source_bytes: layout.source_bytes, + source_sha256, + derived_offset: layout.derived_offset, + derived_bytes: layout.derived_bytes, + f32_sha256, + }) + } + + fn verify_parent_hashes( + &self, + tensor: &gguf::TensorInfo, + original: &derived_mixed::TensorIdentity, + split: bool, + hashes: ParentHashes, + ) -> Result<(), String> { + if split + && (hashes.source.finalize().as_slice() != original.source_sha256 + || hashes.f32.finalize().as_slice() != original.f32_sha256) + { + return Err(format!( + "{}: KAR part hashes differ from source", + tensor.name + )); + } + Ok(()) + } + + fn register_parts(&mut self, parts: Vec) -> Result<(), String> { + for part in &parts { + if !self.names.insert(part.name.clone()) { + return Err(format!("duplicate KAR part name: {}", part.name)); + } + } + self.result.push(parts); + self.number += 1; + Ok(()) + } +} + +fn hash_layout( + source: &mut File, + data_start: u64, + tensor: &gguf::TensorInfo, + layout: &Layout, + parent: &mut ParentHashes, +) -> Result<([u8; 32], [u8; 32]), String> { + let absolute = data_start + .checked_add(tensor.offset) + .and_then(|offset| offset.checked_add(layout.source_byte_offset)) + .ok_or("GGUF part offset overflow")?; + let mut hashes = ParentHashes { + source: Sha256::new(), + f32: Sha256::new(), + }; + let count = gguf_f32_stream::visit( + source, + absolute, + tensor.kind, + layout.source_bytes, + |raw, f32_bytes| { + hashes.source.update(raw); + hashes.f32.update(f32_bytes); + parent.source.update(raw); + parent.f32.update(f32_bytes); + Ok(()) + }, + )?; + if count != layout.derived_bytes { + return Err("GGUF part derived byte count mismatch".into()); + } + Ok(( + hashes.source.finalize().into(), + hashes.f32.finalize().into(), + )) } #[cfg(test)] diff --git a/docs/build-validation.md b/docs/build-validation.md index c3c12131..693a2a2d 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -139,6 +139,7 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Command: `strata-next model prepare-sharded-streamed qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --output /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --levels 2`. - The complete archive has **55,295,529,472 bytes** (51.49797487 GiB) across 1,225 KAR records; the two GGUF shards have 83,617,662,656 bytes. Archive/source ratio is 0.66129006, saving 28,322,133,184 bytes (33.87099%). Accounted rate is 2.500025 bits per derived F32 weight. Archive SHA-256 is `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; derived F32 SHA-256 is `c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479`. - The writer's full payload CRC verification passed before atomic publication, and a versioned provenance sidecar was written. The maximum tensor relative L2 error measured during encoding was 0.68008092. This is **not** a model-level quality result or permission to serve with KAR-2. No Linux GPU inference, GPU decode, or paired end-to-end throughput result exists yet. +- Archive publication keeps a source/policy-bound pending intent until the provenance sidecar is atomically linked. Deterministic fault tests cover destination hash failure, sidecar publication failure, provenance and pending-intent temporary cleanup failure, and archive temporary-link cleanup failure. Retry verifies source shards, KAR records and payload CRCs before recovering the matching sidecar; no existing archive or provenance file is replaced. This makes an interrupted publication recoverable, but does not change the archive's lossy quality status. - A separate `model verify-sharded-streamed /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --manifest qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --levels 2` run exited successfully. It recomputed the derived F32 source identity, checked both manifest shards, all 1,225 KAR source records and payload CRCs, the archive SHA-256, and the v4 provenance policy. The provenance sidecar SHA-256 is `3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5`. Temporary section files, old real-data slices, local header fixtures, and superseded local Docker images were removed; both verified GGUF shards, the final KAR, and its provenance remain outside Git. ## 2026-10-03 — outer block codec and selective precision probes diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 5c027abc..755177c4 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -139,6 +139,20 @@ The CPU quality oracle can decode up to one million values from an arbitrary nes `model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The measured level-2 real-model archive is 55,295,529,472 bytes (51.50 GiB); its model quality remains unmeasured. Use an external model volume or the Linux GPU host for preparation. +Streamed publication is retry-safe across the archive/provenance boundary. Before +the no-replace archive link, preparation publishes a `.pending.json` intent that +binds the verified source identity and exact partition/level policy. If hashing +the published archive or publishing its provenance sidecar fails, the archive +and intent are retained. A later `ensure-sharded-streamed` may recover only +when that intent matches the current pinned shards and policy and a fresh +independent archive verification succeeds; it then writes the sidecar with a +no-replace link. An archive without a matching intent is never adopted, and an +existing sidecar or archive is never overwritten. Temporary-link cleanup after +a successful archive or provenance publication can fail without invalidating +the atomically linked destination; any leftover `.part` file is not treated as +an archive or sidecar. Recovery proves artifact integrity only, not lossy model +quality or serving readiness. + `model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally. The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape. -- 2.54.0 From 30d2867aeaafa87bc9ec91375ca42f6546bfbf7e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 00:57:08 +0200 Subject: [PATCH 34/58] STRA-8 add Linux changed-scope coverage gate --- .github/workflows/linux.yml | 42 + control-plane/src/kar_overlay.rs | 1879 +++++++-- control-plane/src/kar_stream_encode.rs | 1024 ++++- control-plane/src/kar_writer.rs | 4595 +++++++++++++++++++---- control-plane/src/model_pipeline.rs | 276 +- control-plane/src/prepare_preview.rs | 4479 +++++++++++++++++----- control-plane/src/stream_parts.rs | 518 ++- docs/build-validation.md | 7 + docs/compressed-runtime.md | 20 +- scripts/check-changed-scope-coverage.py | 617 +++ scripts/test-changed-scope-coverage.py | 139 + 11 files changed, 11558 insertions(+), 2038 deletions(-) create mode 100644 scripts/check-changed-scope-coverage.py create mode 100644 scripts/test-changed-scope-coverage.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index f9e2065b..b28d792a 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -15,6 +15,10 @@ on: description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact) type: boolean default: false + changed_scope_coverage: + description: Run exact changed-production Rust line, function and branch coverage on Linux CPU + type: boolean + default: false permissions: contents: read @@ -37,6 +41,44 @@ jobs: - name: Local checks run: scripts/check-local.sh + changed-scope-coverage: + if: github.event_name == 'workflow_dispatch' && inputs.changed_scope_coverage + needs: verify + runs-on: ubuntu-latest + timeout-minutes: 120 + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Install parser runtime + run: apt-get update && apt-get install -y ca-certificates curl python3 + - name: Install pinned Rust nightly with LLVM coverage tools + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" + rustup toolchain install nightly-2026-10-05 --profile minimal --component llvm-tools-preview + - name: Test coverage parser and workflow contract + run: python3 scripts/test-changed-scope-coverage.py + - name: Run exact changed-production coverage gate + run: python3 scripts/check-changed-scope-coverage.py --root "$GITHUB_WORKSPACE" --output-dir "$RUNNER_TEMP/changed-scope-coverage" + - name: Archive raw LCOV and machine-readable summary + if: always() + uses: actions/upload-artifact@v4.4.3 + with: + name: changed-scope-coverage-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/changed-scope-coverage/coverage.raw.lcov + ${{ runner.temp }}/changed-scope-coverage/summary.json + ${{ runner.temp }}/changed-scope-coverage/summary.txt + ${{ runner.temp }}/changed-scope-coverage/cargo.stderr + ${{ runner.temp }}/changed-scope-coverage/llvm-cov.stderr + ${{ runner.temp }}/changed-scope-coverage/llvm-profdata.stderr + if-no-files-found: warn + retention-days: 14 + keyless-cuda: if: github.event_name == 'workflow_dispatch' && github.event.inputs.keyless_gpu == 'true' needs: verify diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index 2c62b8f6..efe40bf1 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -8,6 +8,9 @@ use std::{ path::{Component, Path, PathBuf}, }; +#[cfg(test)] +use std::cell::{Cell, RefCell}; + use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -296,17 +299,52 @@ impl Drop for Staging { } } -struct PendingArchive { - path: PathBuf, - committed: bool, +#[cfg(test)] +thread_local! { + static OVERLAY_PUBLICATION_FAILURE: Cell = const { Cell::new(0) }; + static OVERLAY_DESTINATION_RETARGET: RefCell> = const { RefCell::new(None) }; } -impl Drop for PendingArchive { - fn drop(&mut self) { - if !self.committed { - let _ = fs::remove_file(&self.path); +#[cfg(test)] +pub(crate) fn fail_overlay_publication_at(stage: u8) { + OVERLAY_PUBLICATION_FAILURE.with(|failure| failure.set(stage)); +} + +#[cfg(test)] +pub(crate) fn retarget_overlay_parent_at_publish(link: PathBuf, target: PathBuf) { + OVERLAY_DESTINATION_RETARGET.with(|retarget| *retarget.borrow_mut() = Some((link, target))); +} + +#[cfg(test)] +fn overlay_publication_checkpoint(stage: u8) -> Result<(), String> { + apply_overlay_destination_retarget(stage)?; + OVERLAY_PUBLICATION_FAILURE.with(|failure| { + if failure.get() != stage { + return Ok(()); } + failure.set(0); + Err(format!( + "injected overlay publication interruption at stage {stage}" + )) + }) +} + +#[cfg(test)] +fn apply_overlay_destination_retarget(stage: u8) -> Result<(), String> { + if stage != 1 { + return Ok(()); } + let retarget = OVERLAY_DESTINATION_RETARGET.with(|value| value.borrow_mut().take()); + let Some((link, target)) = retarget else { + return Ok(()); + }; + fs::remove_file(&link).map_err(|error| error.to_string())?; + std::os::unix::fs::symlink(target, link).map_err(|error| error.to_string()) +} + +#[cfg(not(test))] +fn overlay_publication_checkpoint(_: u8) -> Result<(), String> { + Ok(()) } pub struct Summary { @@ -320,16 +358,18 @@ pub struct Summary { /// Verify both complete archives and bind every replacement to the same /// virtual-F32 source record before a loader selects an archive by tensor name. pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result { + let base_archive = kar_writer::canonical_archive_destination(base_archive)?; + let overlay_archive = kar_writer::canonical_archive_destination(overlay_archive)?; let sidecar = |path: &Path| -> Result { let name = path.file_name().ok_or("KAR archive has no file name")?; Ok(path.with_file_name(format!("{}.provenance.json", name.to_string_lossy()))) }; let base: BaseProvenance = serde_json::from_reader( - File::open(sidecar(base_archive)?).map_err(|error| error.to_string())?, + File::open(sidecar(&base_archive)?).map_err(|error| error.to_string())?, ) .map_err(|error| error.to_string())?; let overlay: OverlayProvenance = serde_json::from_reader( - File::open(sidecar(overlay_archive)?).map_err(|error| error.to_string())?, + File::open(sidecar(&overlay_archive)?).map_err(|error| error.to_string())?, ) .map_err(|error| error.to_string())?; if !base.supported_partition_policy() @@ -338,13 +378,13 @@ pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result 8 || overlay.records.is_empty() - || hex::encode(hash_file(base_archive)?) != base.archive_sha256 - || hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256 + || hex::encode(hash_file(&base_archive)?) != base.archive_sha256 + || hex::encode(hash_file(&overlay_archive)?) != overlay.overlay_archive_sha256 { return Err("base or overlay archive differs from its provenance".into()); } - let (base_summary, base_sources) = kar::verify_with_sources(base_archive)?; - let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?; + let (base_summary, base_sources) = kar::verify_with_sources(&base_archive)?; + let (overlay_summary, overlay_sources) = kar::verify_with_sources(&overlay_archive)?; if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)? || overlay_summary.source_digest != base_summary.source_digest || base_summary.source_bytes != base.derived_f32_bytes @@ -537,186 +577,661 @@ pub fn prepare( candidate_path: &Path, destination: &Path, ) -> Result { - let sidecar = destination.with_file_name(format!( - "{}.provenance.json", - destination - .file_name() - .ok_or("overlay destination has no file name")? - .to_string_lossy() - )); - if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(&sidecar).is_ok() { - return Err("overlay archive or provenance destination already exists".into()); + let destination = kar_writer::canonical_archive_destination(destination)?; + let sidecar = overlay_sidecar(&destination)?; + let input = OverlayInput::load(OverlayLoadRequest { + manifest, + source_dir, + base_archive, + candidate_path, + destination: &destination, + sidecar, + })?; + let staging = create_overlay_staging(&destination)?; + let prepared = encode_candidates(&input, &staging)?; + publish_overlay(&input, &prepared) +} + +fn overlay_sidecar(destination: &Path) -> Result { + let name = destination + .file_name() + .ok_or("overlay destination has no file name")?; + Ok(destination.with_file_name(format!("{}.provenance.json", name.to_string_lossy()))) +} + +struct OverlayInput<'a> { + destination: &'a Path, + sidecar: PathBuf, + candidate_bytes: Vec, + candidates: Candidates, + base: VerifiedOverlayBase, + sources: OverlaySourceMap, +} + +struct VerifiedOverlayBase { + provenance: BaseProvenance, + digest: [u8; 32], + source_digest: [u8; 32], + summary: kar::Summary, + records: Vec, +} + +struct OverlaySourceMap { + locations: HashMap, + architecture: Option, +} + +impl<'a> OverlayInput<'a> { + fn load(request: OverlayLoadRequest<'a>) -> Result { + let (candidate_bytes, candidates) = read_candidates(request.candidate_path)?; + let base = read_verified_base(request.base_archive, &candidates)?; + validate_manifest_base(request.manifest, &base.provenance)?; + let sources = load_overlay_sources(request.manifest, request.source_dir, &base.provenance)?; + Ok(Self { + destination: request.destination, + sidecar: request.sidecar, + candidate_bytes, + candidates, + base, + sources, + }) } - let candidates_bytes = fs::read(candidate_path).map_err(|error| error.to_string())?; +} + +struct OverlayLoadRequest<'a> { + manifest: &'a Manifest, + source_dir: &'a Path, + base_archive: &'a Path, + candidate_path: &'a Path, + destination: &'a Path, + sidecar: PathBuf, +} + +fn read_candidates(path: &Path) -> Result<(Vec, Candidates), String> { + let bytes = fs::read(path).map_err(|error| error.to_string())?; let candidates: Candidates = - serde_json::from_slice(&candidates_bytes).map_err(|error| error.to_string())?; - if candidates.schema != "strata-next/proposed-kar-precision-candidates-v1" - || !(1..=8).contains(&candidates.proposed_levels) - || candidates.records.is_empty() - { + serde_json::from_slice(&bytes).map_err(|error| error.to_string())?; + let valid = candidates.schema == "strata-next/proposed-kar-precision-candidates-v1" + && (1..=8).contains(&candidates.proposed_levels) + && !candidates.records.is_empty(); + if !valid { return Err("invalid KAR overlay candidate policy".into()); } - let base_sidecar = base_archive.with_file_name(format!( - "{}.provenance.json", - base_archive - .file_name() - .ok_or("base archive has no file name")? - .to_string_lossy() - )); - let base: BaseProvenance = - serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?) - .map_err(|error| error.to_string())?; - if !base.supported_partition_policy() || candidates.source_archive_sha256 != base.archive_sha256 + Ok((bytes, candidates)) +} + +fn read_verified_base(path: &Path, candidates: &Candidates) -> Result { + let sidecar = overlay_sidecar(path)?; + let provenance = read_base_provenance(&sidecar)?; + if !provenance.supported_partition_policy() + || candidates.source_archive_sha256 != provenance.archive_sha256 { return Err("candidate policy differs from base KAR provenance".into()); } - let base_digest = parse_digest(&base.archive_sha256)?; - let source_digest = parse_digest(&base.derived_f32_sha256)?; - let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?; - if base_summary.source_digest != source_digest - || base_summary.source_bytes != base.derived_f32_bytes + let digest = parse_digest(&provenance.archive_sha256)?; + let source_digest = parse_digest(&provenance.derived_f32_sha256)?; + let (summary, records) = kar::inspect_with_sources(path)?; + if summary.source_digest != source_digest + || summary.source_bytes != provenance.derived_f32_bytes { return Err("base KAR header differs from provenance".into()); } - let mut manifest_files = manifest.files.iter().collect::>(); - manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); - if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() { + ensure_unique_base_tensors(&provenance)?; + Ok(VerifiedOverlayBase { + provenance, + digest, + source_digest, + summary, + records, + }) +} + +fn read_base_provenance(path: &Path) -> Result { + serde_json::from_reader(File::open(path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string()) +} + +fn ensure_unique_base_tensors(base: &BaseProvenance) -> Result<(), String> { + let names = base + .tensors + .iter() + .map(|tensor| tensor.name.as_str()) + .collect::>(); + if names.len() != base.tensors.len() { + return Err("duplicate tensor in base provenance".into()); + } + Ok(()) +} + +fn validate_manifest_base(manifest: &Manifest, base: &BaseProvenance) -> Result<(), String> { + let mut files = manifest.files.iter().collect::>(); + files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || files.len() != base.shards.len() { return Err("source manifest differs from base provenance".into()); } - let mut locations = HashMap::new(); - let mut architecture = None::; - for (entry, recorded) in manifest_files.iter().zip(&base.shards) { + for (entry, recorded) in files.iter().zip(&base.shards) { if entry.name != recorded.name || entry.size != recorded.gguf_bytes || entry.sha256 != recorded.gguf_sha256 - || !matches!( - Path::new(&entry.name).components().next(), - Some(Component::Normal(_)) - ) - || Path::new(&entry.name).components().count() != 1 + || !single_component(&entry.name) { return Err("source manifest differs from base shard identity".into()); } - let path = source_dir.join(&entry.name); - let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - if index.summary.file_size != entry.size { - return Err("source shard length changed since base preparation".into()); + } + Ok(()) +} + +fn single_component(name: &str) -> bool { + let path = Path::new(name); + path.components().count() == 1 && matches!(path.components().next(), Some(Component::Normal(_))) +} + +fn load_overlay_sources( + manifest: &Manifest, + source_dir: &Path, + base: &BaseProvenance, +) -> Result { + let mut sources = OverlaySourceMap { + locations: HashMap::new(), + architecture: None, + }; + for entry in &manifest.files { + load_overlay_shard(entry, source_dir, base, &mut sources)?; + } + Ok(sources) +} + +fn load_overlay_shard( + entry: &crate::model::ModelFile, + source_dir: &Path, + base: &BaseProvenance, + sources: &mut OverlaySourceMap, +) -> Result<(), String> { + let path = source_dir.join(&entry.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != entry.size { + return Err("source shard length changed since base preparation".into()); + } + check_architecture( + &mut sources.architecture, + index.summary.architecture.as_deref(), + )?; + insert_locations(&mut sources.locations, &path, &index)?; + ensure_shard_in_base(entry, base) +} + +fn check_architecture(current: &mut Option, incoming: Option<&str>) -> Result<(), String> { + if let Some(value) = incoming { + if current.as_deref().is_some_and(|old| old != value) { + return Err("GGUF shard architectures differ".into()); } - if let Some(arch) = index.summary.architecture { - if architecture.as_deref().is_some_and(|old| old != arch) { - return Err("GGUF shard architectures differ".into()); - } - architecture.get_or_insert(arch); - } - for tensor in index.tensors { - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - if locations - .insert( - tensor.name, - Location { - path: path.clone(), - absolute, - kind: tensor.kind, - source_bytes: tensor.bytes, - dimensions: tensor.dimensions, - }, - ) - .is_some() - { - return Err("duplicate GGUF tensor name".into()); - } + current.get_or_insert_with(|| value.to_owned()); + } + Ok(()) +} + +fn insert_locations( + locations: &mut HashMap, + path: &Path, + index: &gguf::TensorIndex, +) -> Result<(), String> { + for tensor in &index.tensors { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + let location = Location { + path: path.to_path_buf(), + absolute, + kind: tensor.kind, + source_bytes: tensor.bytes, + dimensions: tensor.dimensions.clone(), + }; + if locations.insert(tensor.name.clone(), location).is_some() { + return Err("duplicate GGUF tensor name".into()); } } - let base_tensors = base - .tensors - .iter() - .map(|tensor| (tensor.name.as_str(), tensor)) - .collect::>(); - if base_tensors.len() != base.tensors.len() { - return Err("duplicate tensor in base provenance".into()); + Ok(()) +} + +fn ensure_shard_in_base( + entry: &crate::model::ModelFile, + base: &BaseProvenance, +) -> Result<(), String> { + if base.shards.iter().any(|shard| { + shard.name == entry.name + && shard.gguf_bytes == entry.size + && shard.gguf_sha256 == entry.sha256 + }) { + return Ok(()); } - let base_records = base_sources - .iter() - .map(|record| (record.name.as_str(), record)) - .collect::>(); - let staging = Staging(destination.with_file_name(format!( - "{}.overlay-sections-{}", - destination.file_name().unwrap().to_string_lossy(), - std::process::id() - ))); - fs::create_dir(&staging.0).map_err(|error| error.to_string())?; - let mut prepared = Vec::with_capacity(candidates.records.len()); + Err("source manifest differs from base shard identity".into()) +} + +fn create_overlay_staging(destination: &Path) -> Result { + let name = destination + .file_name() + .ok_or("overlay destination has no file name")? + .to_string_lossy(); + let path = + destination.with_file_name(format!("{name}.overlay-sections-{}", std::process::id())); + fs::create_dir(&path).map_err(|error| error.to_string())?; + Ok(Staging(path)) +} + +fn encode_candidates(input: &OverlayInput<'_>, staging: &Staging) -> Result, String> { + let mut prepared = Vec::with_capacity(input.candidates.records.len()); let mut seen = HashSet::new(); - for candidate in &candidates.records { + for candidate in &input.candidates.records { if !seen.insert(candidate.name.as_str()) { return Err("duplicate KAR overlay candidate".into()); } - let selected = candidate_source(&base, &locations, &candidate.name)?; - let location = &selected.location; - let elements = location - .dimensions - .iter() - .try_fold(1u64, |n, dim| n.checked_mul(*dim)) - .ok_or("candidate tensor shape overflow")?; - let base_record = base_records - .get(candidate.name.as_str()) - .ok_or("candidate is missing from base KAR directory")?; - if elements != candidate.elements - || selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? - || base_record.offset != selected.derived_offset - || base_record.digest != parse_digest(selected.f32_sha256)? - || base_record.dimensions != location.dimensions - { - return Err(format!( - "{}: candidate geometry differs from base", - candidate.name - )); - } - let source_sha256 = parse_digest(selected.source_sha256)?; - let f32_sha256 = parse_digest(selected.f32_sha256)?; - let mut source = File::open(&location.path).map_err(|error| error.to_string())?; - let sample = kar_sample::sample_normalized( - &mut source, - location.absolute, - location.kind, - location.source_bytes, - elements, - source_sha256, - kar_sample::MAX_SAMPLE_VALUES, - )?; - let calibration = kar_codec::fit_topdown(&sample, candidates.proposed_levels) - .map_err(|error| format!("{}: {error}", candidate.name))?; - let section_path = staging.0.join(format!("{:06}.section", prepared.len())); - let section = kar_stream_encode::encode_section( - &mut source, - &kar_stream_encode::SectionRequest { - absolute_offset: location.absolute, - source_kind: location.kind, - source_bytes: location.source_bytes, - elements, - calibration: &calibration, - destination: §ion_path, - }, - )?; - if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 { - return Err(format!("{}: candidate source changed", candidate.name)); - } - prepared.push(Prepared { - name: candidate.name.clone(), - dimensions: location.dimensions.clone(), - source_offset: selected.derived_offset, - f32_sha256, - section_path, - section_bytes: section.bytes, - section_sha256: section.digest, - relative_l2: section.relative_l2, - }); + prepared.push(encode_candidate(input, staging, candidate, prepared.len())?); } - let tensors = prepared + Ok(prepared) +} + +fn encode_candidate( + input: &OverlayInput<'_>, + staging: &Staging, + candidate: &Candidate, + number: usize, +) -> Result { + let selected = candidate_source( + &input.base.provenance, + &input.sources.locations, + &candidate.name, + )?; + validate_candidate_geometry(candidate, &selected, &input.base)?; + encode_selected_candidate(input, staging, candidate, number, selected) +} + +fn validate_candidate_geometry( + candidate: &Candidate, + selected: &CandidateSource<'_>, + base: &VerifiedOverlayBase, +) -> Result<(), String> { + let record = base + .records + .iter() + .find(|tensor| tensor.name == candidate.name) + .ok_or("candidate is missing from base provenance")?; + let elements = candidate_elements(selected)?; + validate_candidate_record(candidate, selected, record, elements) +} + +fn candidate_elements(selected: &CandidateSource<'_>) -> Result { + let elements = selected + .location + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("candidate tensor shape overflow")?; + Ok(elements) +} + +fn validate_candidate_record( + candidate: &Candidate, + selected: &CandidateSource<'_>, + record: &kar::TensorSource, + elements: u64, +) -> Result<(), String> { + if elements != candidate.elements + || selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + || record.offset != selected.derived_offset + || record.digest != parse_digest(selected.f32_sha256)? + || record.n_elements != elements + || record.dimensions != selected.location.dimensions + || record.name != candidate.name + { + return Err(format!( + "{}: candidate geometry differs from base", + candidate.name + )); + } + Ok(()) +} + +fn encode_selected_candidate( + input: &OverlayInput<'_>, + staging: &Staging, + candidate: &Candidate, + number: usize, + selected: CandidateSource<'_>, +) -> Result { + let (mut source, sample, f32_sha256) = candidate_sample(&selected)?; + let calibration = fit_candidate(&sample, input.candidates.proposed_levels, &candidate.name)?; + write_candidate_section(CandidateSectionRequest { + staging, + candidate, + number, + selected, + source: &mut source, + calibration: &calibration, + f32_sha256, + }) +} + +fn candidate_sample(selected: &CandidateSource<'_>) -> Result<(File, Vec, [u8; 32]), String> { + let source_sha256 = parse_digest(selected.source_sha256)?; + let f32_sha256 = parse_digest(selected.f32_sha256)?; + let location = &selected.location; + let mut source = File::open(&location.path).map_err(|error| error.to_string())?; + let elements = location + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("candidate tensor shape overflow")?; + let sample = kar_sample::sample_normalized( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + elements, + source_sha256, + kar_sample::MAX_SAMPLE_VALUES, + )?; + Ok((source, sample, f32_sha256)) +} + +fn fit_candidate(sample: &[f32], levels: u8, name: &str) -> Result { + kar_codec::fit_topdown(sample, levels).map_err(|error| format!("{name}: {error}")) +} + +struct CandidateSectionRequest<'a, 'b> { + staging: &'a Staging, + candidate: &'a Candidate, + number: usize, + selected: CandidateSource<'b>, + source: &'a mut File, + calibration: &'a kar_codec::Calibration, + f32_sha256: [u8; 32], +} + +fn write_candidate_section(request: CandidateSectionRequest<'_, '_>) -> Result { + let section_path = request + .staging + .0 + .join(format!("{:06}.section", request.number)); + let section = kar_stream_encode::encode_section( + request.source, + &kar_stream_encode::SectionRequest { + absolute_offset: request.selected.location.absolute, + source_kind: request.selected.location.kind, + source_bytes: request.selected.location.source_bytes, + elements: request.selected.derived_bytes / 4, + calibration: request.calibration, + destination: §ion_path, + }, + )?; + verify_candidate_section(&request, §ion)?; + Ok(Prepared { + name: request.candidate.name.clone(), + dimensions: request.selected.location.dimensions.clone(), + source_offset: request.selected.derived_offset, + f32_sha256: request.f32_sha256, + section_path, + section_bytes: section.bytes, + section_sha256: section.digest, + relative_l2: section.relative_l2, + }) +} + +fn verify_candidate_section( + request: &CandidateSectionRequest<'_, '_>, + section: &kar_stream_encode::SectionResult, +) -> Result<(), String> { + if section.source_digest == parse_digest(request.selected.source_sha256)? + && section.derived_digest == request.f32_sha256 + { + return Ok(()); + } + Err(format!( + "{}: candidate source changed", + request.candidate.name + )) +} + +fn publish_overlay(input: &OverlayInput<'_>, prepared: &[Prepared]) -> Result { + let intent_path = overlay_intent_path(input.destination)?; + let intent = overlay_intent_value(input, prepared); + if read_overlay_json(&intent_path)?.is_none() + && (regular_file_exists(input.destination)? || regular_file_exists(&input.sidecar)?) + { + return verify_complete_overlay(input, prepared, &intent); + } + ensure_overlay_intent(&intent_path, &intent)?; + overlay_publication_checkpoint(1)?; + publish_overlay_outputs(input, prepared, &intent_path, &intent) +} + +fn publish_overlay_outputs( + input: &OverlayInput<'_>, + prepared: &[Prepared], + intent_path: &Path, + intent: &serde_json::Value, +) -> Result { + let builder = overlay_builder(&input.candidates, &input.base, &input.candidate_bytes); + let tensors = overlay_tensors(prepared, input.candidates.proposed_levels); + let source = overlay_source(input, &builder)?; + let archive = ensure_overlay_archive(input, prepared, &source, &tensors, intent)?; + overlay_publication_checkpoint(2)?; + let archive_sha256 = hash_file(input.destination)?; + verify_overlay_archive(input.destination, &archive, prepared)?; + let provenance = overlay_provenance_value(input, prepared, archive_sha256); + publish_overlay_provenance(&input.sidecar, &provenance, intent_path)?; + verify_final_sidecar(&input.sidecar, &provenance)?; + overlay_publication_checkpoint(3)?; + remove_overlay_intent(intent_path)?; + overlay_publication_checkpoint(4)?; + Ok(overlay_summary( + archive, + archive_sha256, + prepared, + input.sidecar.clone(), + )) +} + +fn verify_final_sidecar(path: &Path, expected: &serde_json::Value) -> Result<(), String> { + if read_overlay_json(path)? == Some(expected.clone()) { + return Ok(()); + } + Err("overlay provenance failed read-back verification".into()) +} + +fn ensure_overlay_archive( + input: &OverlayInput<'_>, + prepared: &[Prepared], + source: &kar_writer::SourceIdentity<'_>, + tensors: &[kar_writer::Tensor<'_>], + intent: &serde_json::Value, +) -> Result { + if regular_file_exists(input.destination)? { + return verify_existing_overlay(input, prepared, intent); + } + kar_writer::write_archive(input.destination, source, tensors) +} + +fn verify_complete_overlay( + input: &OverlayInput<'_>, + prepared: &[Prepared], + intent: &serde_json::Value, +) -> Result { + let (archive, _) = kar::verify_with_sources(input.destination)?; + verify_overlay_archive(input.destination, &archive, prepared)?; + verify_overlay_summary(input, prepared, &archive)?; + let digest = hash_file(input.destination)?; + let provenance = overlay_provenance_value(input, prepared, digest); + if read_overlay_json(&input.sidecar)? != Some(provenance) { + return Err("existing overlay archive lacks matching provenance".into()); + } + if overlay_intent_value(input, prepared) != *intent { + return Err("existing overlay intent differs from requested source or policy".into()); + } + Ok(overlay_summary( + archive, + digest, + prepared, + input.sidecar.clone(), + )) +} + +fn verify_existing_overlay( + input: &OverlayInput<'_>, + prepared: &[Prepared], + intent: &serde_json::Value, +) -> Result { + let (summary, _) = kar::verify_with_sources(input.destination)?; + verify_overlay_archive(input.destination, &summary, prepared)?; + verify_overlay_summary(input, prepared, &summary)?; + verify_existing_sidecar(input, prepared, intent)?; + Ok(summary) +} + +fn verify_overlay_summary( + input: &OverlayInput<'_>, + prepared: &[Prepared], + summary: &kar::Summary, +) -> Result<(), String> { + if summary.source_digest != input.base.source_digest + || summary.source_bytes != input.base.provenance.derived_f32_bytes + || summary.tensor_count as usize != prepared.len() + || summary.max_planes != input.candidates.proposed_levels + { + return Err("existing overlay archive differs from pending source identity".into()); + } + Ok(()) +} + +fn verify_existing_sidecar( + input: &OverlayInput<'_>, + prepared: &[Prepared], + intent: &serde_json::Value, +) -> Result<(), String> { + let archive_sha = hash_file(input.destination)?; + let expected = overlay_provenance_value(input, prepared, archive_sha); + match read_overlay_json(&input.sidecar)? { + Some(actual) if actual == expected && overlay_intent_value(input, prepared) == *intent => { + Ok(()) + } + Some(_) => Err("existing overlay provenance differs from verified archive".into()), + None => Ok(()), + } +} + +fn publish_overlay_provenance( + sidecar: &Path, + expected: &serde_json::Value, + intent_path: &Path, +) -> Result<(), String> { + match read_overlay_json(sidecar)? { + Some(actual) if actual == *expected => Ok(()), + Some(_) => Err("overlay provenance already exists with different contents".into()), + None if read_overlay_json(intent_path)?.is_some() => { + crate::prepare_preview::write_provenance(sidecar, expected) + } + None => Err("overlay provenance has no matching pending intent".into()), + } +} + +fn overlay_intent_path(destination: &Path) -> Result { + let name = destination + .file_name() + .ok_or("overlay destination has no file name")?; + Ok(destination.with_file_name(format!("{}.pending.json", name.to_string_lossy()))) +} + +fn ensure_overlay_intent(path: &Path, expected: &serde_json::Value) -> Result<(), String> { + ensure_overlay_intent_with_ops( + path, + expected, + regular_file_exists, + crate::prepare_preview::write_provenance, + ) +} + +fn ensure_overlay_intent_with_ops( + path: &Path, + expected: &serde_json::Value, + exists: fn(&Path) -> Result, + publish: fn(&Path, &serde_json::Value) -> Result<(), String>, +) -> Result<(), String> { + match read_overlay_json(path)? { + Some(actual) if actual == *expected => Ok(()), + Some(_) => Err("overlay publish intent differs from requested source or policy".into()), + None => { + if exists(path)? { + return Err("overlay intent path is occupied".into()); + } + publish(path, expected) + } + } +} + +fn read_overlay_json(path: &Path) -> Result, String> { + read_overlay_json_with_open(path, open_overlay_metadata) +} + +fn open_overlay_metadata(path: &Path) -> std::io::Result { + File::open(path) +} + +fn read_overlay_json_with_open( + path: &Path, + open: fn(&Path) -> std::io::Result, +) -> Result, String> { + match fs::symlink_metadata(path) { + Ok(metadata) if !metadata.file_type().is_symlink() && metadata.is_file() => { + serde_json::from_reader(open(path).map_err(|error| error.to_string())?) + .map(Some) + .map_err(|error| error.to_string()) + } + Ok(_) => Err("overlay publication metadata must be a regular file".into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error.to_string()), + } +} + +fn regular_file_exists(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Ok(metadata) if !metadata.file_type().is_symlink() && metadata.is_file() => Ok(true), + Ok(_) => Err("overlay output must be a regular file".into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.to_string()), + } +} + +fn remove_overlay_intent(path: &Path) -> Result<(), String> { + match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error.to_string()), + } +} + +fn overlay_intent_value(input: &OverlayInput<'_>, prepared: &[Prepared]) -> serde_json::Value { + let mut intent = overlay_provenance_value(input, prepared, [0; 32]); + intent + .as_object_mut() + .unwrap() + .remove("overlay_archive_sha256"); + intent["schema"] = serde_json::json!("strata-next/kar-overlay-pending-v1"); + intent +} + +fn overlay_builder(candidates: &Candidates, base: &VerifiedOverlayBase, bytes: &[u8]) -> String { + let digest: [u8; 32] = Sha256::digest(bytes).into(); + format!( + "strata-next/experimental-kar-overlay-v1:l{}:base{}:policy{}", + candidates.proposed_levels, + &base.provenance.archive_sha256[..16], + &hex::encode(digest)[..16] + ) +} + +fn overlay_tensors(prepared: &[Prepared], levels: u8) -> Vec> { + prepared .iter() .map(|entry| kar_writer::Tensor { name: &entry.name, @@ -728,40 +1243,45 @@ pub fn prepare( group: 32, nesting: 0, planes_min: 1, - planes_max: candidates.proposed_levels, - levels: candidates.proposed_levels, + planes_max: levels, + levels, path: &entry.section_path, offset: 0, bytes: entry.section_bytes, digest: entry.section_sha256, }, }) - .collect::>(); - let candidate_sha256: [u8; 32] = Sha256::digest(&candidates_bytes).into(); - let builder = format!( - "strata-next/experimental-kar-overlay-v1:l{}:base{}:policy{}", - candidates.proposed_levels, - &base.archive_sha256[..16], - &hex::encode(candidate_sha256)[..16] - ); - let source = kar_writer::SourceIdentity { + .collect() +} + +fn overlay_source<'a>( + input: &'a OverlayInput<'_>, + builder: &'a str, +) -> Result, String> { + let architecture = input + .sources + .architecture + .as_deref() + .ok_or("GGUF architecture missing")?; + Ok(kar_writer::SourceIdentity { name: "gguf-shards#derived-f32-le-v4-overlay", - architecture: architecture.as_deref().ok_or("GGUF architecture missing")?, - builder: &builder, - digest: source_digest, - total_elements: base.derived_f32_bytes / 4, - bytes: base.derived_f32_bytes, - }; - let archive = kar_writer::write_archive(destination, &source, &tensors)?; - let mut pending = PendingArchive { - path: destination.to_path_buf(), - committed: false, - }; - let archive_sha256 = hash_file(destination)?; - let (verified, records) = kar::verify_with_sources(destination)?; - if verified != archive + architecture, + builder, + digest: input.base.summary.source_digest, + total_elements: input.base.provenance.derived_f32_bytes / 4, + bytes: input.base.provenance.derived_f32_bytes, + }) +} + +fn verify_overlay_archive( + path: &Path, + expected: &kar::Summary, + prepared: &[Prepared], +) -> Result<(), String> { + let (verified, records) = kar::verify_with_sources(path)?; + if verified != *expected || records.len() != prepared.len() - || records.iter().zip(&prepared).any(|(record, entry)| { + || records.iter().zip(prepared).any(|(record, entry)| { record.name != entry.name || record.digest != entry.f32_sha256 || record.offset != entry.source_offset @@ -769,34 +1289,969 @@ pub fn prepare( { return Err("overlay archive source records failed verification".into()); } - let provenance = serde_json::json!({ - "schema": "strata-next/kar-overlay-provenance-v1", - "base_archive_sha256": hex::encode(base_digest), - "candidate_policy_sha256": hex::encode(candidate_sha256), + Ok(()) +} + +fn overlay_provenance_value( + input: &OverlayInput<'_>, + prepared: &[Prepared], + archive_sha256: [u8; 32], +) -> serde_json::Value { + let records = prepared + .iter() + .map(|entry| { + serde_json::json!({ + "name": entry.name, "derived_offset": entry.source_offset, + "f32_sha256": hex::encode(entry.f32_sha256), "section_bytes": entry.section_bytes, + "relative_l2": entry.relative_l2, + }) + }) + .collect::>(); + serde_json::json!({ "schema": "strata-next/kar-overlay-provenance-v1", + "base_archive_sha256": hex::encode(input.base.digest), + "candidate_policy_sha256": hex::encode(Sha256::digest(&input.candidate_bytes)), "overlay_archive_sha256": hex::encode(archive_sha256), - "derived_f32_sha256": hex::encode(source_digest), - "levels": candidates.proposed_levels, - "records": prepared.iter().map(|entry| serde_json::json!({ - "name": entry.name, - "derived_offset": entry.source_offset, - "f32_sha256": hex::encode(entry.f32_sha256), - "section_bytes": entry.section_bytes, - "relative_l2": entry.relative_l2, - })).collect::>(), - "serving_status": "experimental-not-approved", - }); - write_provenance(&sidecar, &provenance)?; - pending.committed = true; - Ok(Summary { + "derived_f32_sha256": hex::encode(input.base.source_digest), + "levels": input.candidates.proposed_levels, "records": records, + "serving_status": "experimental-not-approved" }) +} + +fn overlay_summary( + archive: kar::Summary, + digest: [u8; 32], + prepared: &[Prepared], + sidecar: PathBuf, +) -> Summary { + Summary { archive_bytes: archive.archive_bytes, - archive_sha256, + archive_sha256: digest, record_count: prepared.len(), maximum_relative_l2: prepared .iter() .map(|entry| entry.relative_l2) .fold(0.0f64, f64::max), provenance_path: sidecar, - }) + } +} + +#[cfg(test)] +#[allow(clippy::items_after_test_module)] // comparison helpers remain grouped after this focused test module +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + static TEST_SEQUENCE: AtomicU64 = AtomicU64::new(0); + + struct TestDir(PathBuf); + + impl TestDir { + fn new(label: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "strata-overlay-{label}-{}-{}", + std::process::id(), + TEST_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn candidate_value( + schema: &str, + levels: u8, + records: Vec, + ) -> serde_json::Value { + serde_json::json!({ + "schema": schema, + "source_archive_sha256": "11".repeat(32), + "proposed_levels": levels, + "records": records, + }) + } + + fn one_candidate() -> Vec { + vec![serde_json::json!({"name":"weight", "elements":32})] + } + + fn write_json(path: &Path, value: &serde_json::Value) { + fs::write(path, serde_json::to_vec(value).unwrap()).unwrap(); + } + + fn base_value(tensors: serde_json::Value) -> serde_json::Value { + serde_json::json!({ + "schema":"strata-next/sharded-stream-provenance-v4", + "archive_sha256":"22".repeat(32), + "derived_f32_sha256":"33".repeat(32), + "derived_f32_bytes":128, + "shards":[{"name":"a.gguf","gguf_sha256":"44".repeat(32),"gguf_bytes":192}], + "tensors":tensors, + "partitioned_tensors":[] + }) + } + + fn base_tensor(name: &str) -> serde_json::Value { + serde_json::json!({ + "name":name, "source_kind":0, "source_sha256":"55".repeat(32), + "derived_offset":0, "derived_bytes":128, "f32_sha256":"33".repeat(32) + }) + } + + fn shard_base( + name: &str, + bytes: u64, + digest: &str, + tensor: serde_json::Value, + ) -> BaseProvenance { + serde_json::from_value(base_value_with_shard( + serde_json::json!([tensor]), + name, + bytes, + digest, + )) + .unwrap() + } + + fn two_shard_mapping( + directory: &Path, + second_name: &str, + second_architecture: &str, + ) -> (Manifest, BaseProvenance) { + let mut files = Vec::new(); + let mut shards = Vec::new(); + for (name, tensor, architecture) in [ + ("a.gguf", "weight", "qwen35"), + ("b.gguf", second_name, second_architecture), + ] { + let (file, shard) = two_shard_fixture(directory, name, tensor, architecture); + files.push(file); + shards.push(shard); + } + let mut base = base_value(serde_json::json!([base_tensor("weight")])); + base["shards"] = serde_json::Value::Array(shards); + ( + Manifest { + schema_version: 1, + files, + }, + serde_json::from_value(base).unwrap(), + ) + } + + fn two_shard_fixture( + directory: &Path, + name: &str, + tensor: &str, + architecture: &str, + ) -> (crate::model::ModelFile, serde_json::Value) { + let bytes = gguf_f32(tensor, architecture, &[0; 128]); + fs::write(directory.join(name), &bytes).unwrap(); + let digest = hex::encode(Sha256::digest(&bytes)); + let file = crate::model::ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: digest.clone(), + }; + let shard = + serde_json::json!({"name":name, "gguf_sha256":digest, "gguf_bytes":bytes.len()}); + (file, shard) + } + + fn create_overlay_base(directory: &Path) -> (Manifest, PathBuf, PathBuf, PathBuf) { + let payload = (0..32u32) + .flat_map(|value| (value as f32 / 32.0).to_le_bytes()) + .collect::>(); + let shard = gguf_f32("weight", "qwen35", &payload); + let second = gguf_iq3("extra", "qwen35"); + fs::write(directory.join("a.gguf"), &shard).unwrap(); + fs::write(directory.join("b.gguf"), &second).unwrap(); + let manifest = overlay_base_manifest(&shard, &second); + let base = directory.join("base.kar"); + crate::prepare_preview::prepare_sharded_streamed(&manifest, directory, &base, 2).unwrap(); + let base_info = overlay_base_identity(directory); + let destination = directory.join("overlay.kar"); + let policy = directory.join("candidates.json"); + let mut value = candidate_value( + "strata-next/proposed-kar-precision-candidates-v1", + 3, + one_candidate(), + ); + value["source_archive_sha256"] = base_info["archive_sha256"].clone(); + write_json(&policy, &value); + (manifest, base, policy, destination) + } + + fn overlay_base_manifest(shard: &[u8], second: &[u8]) -> Manifest { + Manifest { + schema_version: 1, + files: [("a.gguf", shard), ("b.gguf", second)] + .into_iter() + .map(|(name, bytes)| crate::model::ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(bytes)), + }) + .collect(), + } + } + + fn overlay_base_identity(directory: &Path) -> serde_json::Value { + let bytes = fs::read(directory.join("base.kar.provenance.json")).unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + fn base_value_with_shard( + tensors: serde_json::Value, + name: &str, + bytes: u64, + digest: &str, + ) -> serde_json::Value { + let mut value = base_value(tensors); + value["shards"] = serde_json::json!([{ + "name":name, "gguf_sha256":digest, "gguf_bytes":bytes + }]); + value + } + + fn gguf_f32(name: &str, architecture: &str, payload: &[u8]) -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + put_gguf_string(&mut bytes, "general.architecture"); + bytes.extend_from_slice(&8u32.to_le_bytes()); + put_gguf_string(&mut bytes, architecture); + put_gguf_string(&mut bytes, name); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&32u64.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend_from_slice(payload); + bytes + } + + fn gguf_iq3(name: &str, architecture: &str) -> Vec { + let mut payload = vec![0u8; crate::iq3_s::BLOCK_BYTES]; + payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + put_gguf_string(&mut bytes, "general.architecture"); + bytes.extend_from_slice(&8u32.to_le_bytes()); + put_gguf_string(&mut bytes, architecture); + put_gguf_string(&mut bytes, name); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&256u64.to_le_bytes()); + bytes.extend_from_slice(&21u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(payload); + bytes + } + + fn put_gguf_string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); + } + + fn candidate_record_fixture() -> (Candidate, CandidateSource<'static>, kar::TensorSource) { + ( + fixture_candidate(), + fixture_candidate_source(), + fixture_archive_record(), + ) + } + + fn fixture_candidate() -> Candidate { + Candidate { + name: "weight".into(), + elements: 32, + } + } + + fn fixture_candidate_source() -> CandidateSource<'static> { + const DIGEST: &str = "0707070707070707070707070707070707070707070707070707070707070707"; + CandidateSource { + location: Location { + path: PathBuf::from("unused.gguf"), + absolute: 0, + kind: 0, + source_bytes: 128, + dimensions: vec![32], + }, + source_sha256: DIGEST, + f32_sha256: DIGEST, + derived_offset: 64, + derived_bytes: 128, + } + } + + fn fixture_archive_record() -> kar::TensorSource { + kar::TensorSource { + name: "weight".into(), + dimensions: vec![32], + dtype: 0, + digest: [7; 32], + offset: 64, + section_bytes: 256, + storage_class: 0, + n_elements: 32, + planes_min: 0, + planes_max: 0, + section_offset: 0, + planes_offset: 0, + plane_stride_bytes: 0, + } + } + + fn rejected_candidate_record( + candidate: &Candidate, + selected: &CandidateSource<'_>, + record: &kar::TensorSource, + elements: u64, + ) { + assert!(validate_candidate_record(candidate, selected, record, elements).is_err()); + } + + fn summary_input(destination: &Path) -> OverlayInput<'_> { + let provenance: BaseProvenance = + serde_json::from_value(base_value(serde_json::json!([]))).unwrap(); + let source_digest = [3; 32]; + let summary = test_summary(source_digest, provenance.derived_f32_bytes, 0, 3); + OverlayInput { + destination, + sidecar: destination.with_extension("json"), + candidate_bytes: Vec::new(), + candidates: Candidates { + schema: "strata-next/proposed-kar-precision-candidates-v1".into(), + source_archive_sha256: provenance.archive_sha256.clone(), + proposed_levels: 3, + records: Vec::new(), + }, + base: VerifiedOverlayBase { + provenance, + digest: [4; 32], + source_digest, + summary, + records: Vec::new(), + }, + sources: OverlaySourceMap { + locations: HashMap::new(), + architecture: None, + }, + } + } + + fn test_summary(digest: [u8; 32], bytes: u64, tensors: u32, planes: u8) -> kar::Summary { + kar::Summary { + archive_bytes: 256, + tensor_count: tensors, + total_elements: 0, + source_total_elements: 0, + accounted_bpw: 0.0, + source_digest: digest, + source_bytes: bytes, + max_planes: planes, + } + } + + #[test] + fn candidate_policy_parser_rejects_invalid_schema_levels_records_and_json() { + let dir = TestDir::new("candidate-policy"); + let path = dir.0.join("candidates.json"); + assert_valid_candidate_policy(&path); + assert_invalid_candidate_policies(&path); + assert_unreadable_candidate_policies(&dir.0, &path); + } + + fn assert_valid_candidate_policy(path: &Path) { + let valid = candidate_value( + "strata-next/proposed-kar-precision-candidates-v1", + 1, + one_candidate(), + ); + write_json(path, &valid); + assert_eq!(read_candidates(path).unwrap().1.proposed_levels, 1); + } + + fn assert_invalid_candidate_policies(path: &Path) { + let schema = "strata-next/proposed-kar-precision-candidates-v1"; + let invalid = [ + candidate_value("wrong", 3, one_candidate()), + candidate_value(schema, 0, one_candidate()), + candidate_value(schema, 9, one_candidate()), + candidate_value(schema, 3, vec![]), + ]; + for value in invalid { + write_json(path, &value); + assert!( + matches!(read_candidates(path), Err(error) if error.contains("invalid KAR overlay")) + ); + } + } + + fn assert_unreadable_candidate_policies(directory: &Path, path: &Path) { + fs::write(path, b"{").unwrap(); + assert!(read_candidates(path).is_err()); + assert!(read_candidates(&directory.join("missing.json")).is_err()); + } + + #[test] + fn base_provenance_and_manifest_identity_fail_closed() { + let dir = TestDir::new("base-validation"); + let path = dir.0.join("base.json"); + let tensors = serde_json::json!([base_tensor("weight")]); + write_json(&path, &base_value(tensors.clone())); + let base = read_base_provenance(&path).unwrap(); + assert!(base.supported_partition_policy()); + ensure_unique_base_tensors(&base).unwrap(); + assert_valid_and_rejected_manifest_identities(&base); + assert_rejected_base_tensor_metadata(&path); + assert_unreadable_base_provenance(&dir.0, &path); + } + + fn assert_valid_and_rejected_manifest_identities(base: &BaseProvenance) { + assert!(validate_manifest_base(&manifest("a.gguf", 192, "44".repeat(32)), base).is_ok()); + assert!( + validate_manifest_base(&manifest("../a.gguf", 192, "44".repeat(32)), base).is_err() + ); + assert!(validate_manifest_base(&manifest("a.gguf", 191, "44".repeat(32)), base).is_err()); + assert!(validate_manifest_base(&manifest("a.gguf", 192, "00".repeat(32)), base).is_err()); + let mut wrong_schema = manifest("a.gguf", 192, "44".repeat(32)); + wrong_schema.schema_version = 2; + assert!(validate_manifest_base(&wrong_schema, base).is_err()); + let empty = Manifest { + schema_version: 1, + files: Vec::new(), + }; + assert!(validate_manifest_base(&empty, base).is_err()); + } + + fn assert_rejected_base_tensor_metadata(path: &Path) { + let unsafe_base: BaseProvenance = serde_json::from_value(base_value_with_shard( + serde_json::json!([]), + "../a.gguf", + 192, + &"44".repeat(32), + )) + .unwrap(); + assert!( + validate_manifest_base(&manifest("../a.gguf", 192, "44".repeat(32)), &unsafe_base) + .is_err() + ); + let duplicates = base_value(serde_json::json!([ + base_tensor("same"), + base_tensor("same") + ])); + write_json(path, &duplicates); + assert!(ensure_unique_base_tensors(&read_base_provenance(path).unwrap()).is_err()); + } + + fn assert_unreadable_base_provenance(directory: &Path, path: &Path) { + fs::write(path, b"not-json").unwrap(); + assert!(read_base_provenance(path).is_err()); + assert!(read_base_provenance(&directory.join("missing.json")).is_err()); + } + + #[test] + fn verified_base_rejects_policy_digest_and_archive_identity_mismatches() { + let dir = TestDir::new("verified-base"); + let (_, archive, _, _) = create_overlay_base(&dir.0); + let sidecar = overlay_sidecar(&archive).unwrap(); + let original: serde_json::Value = + serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); + let candidates = valid_overlay_candidates(&original); + assert!(read_verified_base(&archive, &candidates).is_ok()); + assert_rejected_overlay_candidate_digest(&archive, &original); + let candidates = valid_overlay_candidates(&original); + assert_rejected_overlay_sidecar_identity(&archive, &sidecar, &original, &candidates); + } + + fn valid_overlay_candidates(sidecar: &serde_json::Value) -> Candidates { + Candidates { + schema: "strata-next/proposed-kar-precision-candidates-v1".into(), + source_archive_sha256: sidecar["archive_sha256"].as_str().unwrap().into(), + proposed_levels: 3, + records: vec![Candidate { + name: "weight".into(), + elements: 32, + }], + } + } + + fn assert_rejected_overlay_candidate_digest(archive: &Path, sidecar: &serde_json::Value) { + let mut candidates = valid_overlay_candidates(sidecar); + candidates.source_archive_sha256 = "00".repeat(32); + assert!(read_verified_base(archive, &candidates).is_err()); + candidates.source_archive_sha256 = sidecar["archive_sha256"].as_str().unwrap().into(); + } + + fn assert_rejected_overlay_sidecar_identity( + archive: &Path, + sidecar: &Path, + original: &serde_json::Value, + candidates: &Candidates, + ) { + let mut wrong_size = original.clone(); + wrong_size["derived_f32_bytes"] = serde_json::json!(127); + write_json(sidecar, &wrong_size); + assert!(read_verified_base(archive, candidates).is_err()); + let mut wrong_size = original.clone(); + wrong_size["schema"] = serde_json::json!("unsupported-policy"); + write_json(sidecar, &wrong_size); + assert!(read_verified_base(archive, candidates).is_err()); + let mut wrong_source = original.clone(); + wrong_source["derived_f32_sha256"] = serde_json::json!("00".repeat(32)); + write_json(sidecar, &wrong_source); + assert!(read_verified_base(archive, candidates).is_err()); + } + + fn manifest(name: &str, size: u64, digest: String) -> Manifest { + Manifest { + schema_version: 1, + files: vec![crate::model::ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size, + sha256: digest, + }], + } + } + + #[test] + fn component_and_architecture_validation_cover_matching_and_mismatch_cases() { + assert!(single_component("a.gguf")); + for invalid in ["../a.gguf", "folder/a.gguf", "", "."] { + assert!(!single_component(invalid)); + } + let mut architecture = None; + assert!(check_architecture(&mut architecture, None).is_ok()); + assert!(check_architecture(&mut architecture, Some("qwen35")).is_ok()); + assert!(check_architecture(&mut architecture, Some("qwen35")).is_ok()); + assert!(check_architecture(&mut architecture, Some("other")).is_err()); + } + + #[test] + fn overlay_metadata_paths_distinguish_absent_regular_and_occupied_files() { + let dir = TestDir::new("metadata-paths"); + let destination = dir.0.join("overlay.kar"); + let sidecar = overlay_sidecar(&destination).unwrap(); + let intent = overlay_intent_path(&destination).unwrap(); + let value = serde_json::json!({"schema":"pending"}); + assert_metadata_intent_contract(&intent, &sidecar, &value); + assert_metadata_path_errors(&intent, &sidecar, &value); + #[cfg(unix)] + assert_metadata_symlinks(&dir.0, &value); + } + + fn assert_metadata_intent_contract(intent: &Path, sidecar: &Path, value: &serde_json::Value) { + assert_eq!(read_overlay_json(sidecar).unwrap(), None); + assert!(!regular_file_exists(sidecar).unwrap()); + ensure_overlay_intent(intent, value).unwrap(); + ensure_overlay_intent(intent, value).unwrap(); + assert_eq!(read_overlay_json(intent).unwrap(), Some(value.clone())); + assert!(ensure_overlay_intent(intent, &serde_json::json!({"schema":"other"})).is_err()); + assert!(publish_overlay_provenance(sidecar, value, intent).is_ok()); + assert!(publish_overlay_provenance(sidecar, &serde_json::json!({}), intent).is_err()); + assert!(regular_file_exists(sidecar).unwrap()); + remove_overlay_intent(intent).unwrap(); + remove_overlay_intent(intent).unwrap(); + } + + fn assert_metadata_path_errors(intent: &Path, sidecar: &Path, value: &serde_json::Value) { + fs::create_dir(intent).unwrap(); + assert!(ensure_overlay_intent(intent, value).is_err()); + assert!(regular_file_exists(intent).is_err()); + assert!(read_overlay_json(intent).is_err()); + assert!(overlay_sidecar(Path::new("/")).is_err()); + assert!(overlay_intent_path(Path::new("/")).is_err()); + assert!(regular_file_exists(sidecar).unwrap()); + } + + #[cfg(unix)] + fn assert_metadata_symlinks(directory: &Path, value: &serde_json::Value) { + let target = directory.join("metadata-target.json"); + write_json(&target, value); + let link = directory.join("metadata-link.json"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert!(read_overlay_json(&link).is_err()); + assert!(regular_file_exists(&link).is_err()); + } + + #[test] + fn overlay_metadata_errors_preserve_fail_closed_behavior() { + let dir = TestDir::new("metadata-errors"); + let malformed = dir.0.join("malformed.json"); + fs::write(&malformed, b"not-json").unwrap(); + assert!(read_overlay_json(&malformed).is_err()); + let intent = dir.0.join("occupied.pending.json"); + fs::create_dir(&intent).unwrap(); + assert!(read_overlay_json(&intent).is_err()); + assert!(remove_overlay_intent(&intent).is_err()); + let absent_intent = dir.0.join("absent.pending.json"); + assert!( + publish_overlay_provenance( + &dir.0.join("x.json"), + &serde_json::json!({}), + &absent_intent + ) + .is_err() + ); + #[cfg(unix)] + { + let invalid = Path::new("bad\0path"); + assert!(read_overlay_json(invalid).is_err()); + assert!(regular_file_exists(invalid).is_err()); + } + } + + fn insert_intent_race_file(path: &Path) -> Result { + fs::write(path, b"concurrent owner").map_err(|error| error.to_string())?; + Ok(true) + } + + fn reject_intent_publish(_: &Path, _: &serde_json::Value) -> Result<(), String> { + panic!("occupied raced path must never be published over") + } + + fn fail_overlay_open(_: &Path) -> std::io::Result { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + + #[test] + fn overlay_metadata_races_fail_closed_without_replacing_the_winner() { + let dir = TestDir::new("metadata-race"); + let intent = dir.0.join("overlay.pending.json"); + let value = serde_json::json!({"schema":"pending"}); + assert!( + ensure_overlay_intent_with_ops( + &intent, + &value, + insert_intent_race_file, + reject_intent_publish, + ) + .is_err() + ); + assert_eq!(fs::read(intent).unwrap(), b"concurrent owner"); + let metadata = dir.0.join("valid.json"); + write_json(&metadata, &value); + assert!(read_overlay_json_with_open(&metadata, fail_overlay_open).is_err()); + } + + #[test] + fn candidate_sampling_fails_when_verified_source_disappears() { + let (_, mut selected, _) = candidate_record_fixture(); + selected.location.path = PathBuf::from("missing-verified-source.gguf"); + assert!(candidate_sample(&selected).is_err()); + } + + #[test] + fn overlay_verification_helpers_reject_stale_summaries_and_sidecars() { + let dir = TestDir::new("verify-metadata"); + let archive = dir.0.join("overlay.kar"); + let input = summary_input(&archive); + verify_overlay_summary(&input, &[], &input.base.summary).unwrap(); + for stale in [ + test_summary([9; 32], 128, 0, 3), + test_summary(input.base.source_digest, 4, 0, 3), + test_summary(input.base.source_digest, 128, 1, 3), + test_summary(input.base.source_digest, 128, 0, 2), + ] { + assert!(verify_overlay_summary(&input, &[], &stale).is_err()); + } + verify_final_sidecar(&input.sidecar, &serde_json::json!({})).unwrap_err(); + fs::write(&archive, b"archive").unwrap(); + let intent = overlay_intent_value(&input, &[]); + let expected = overlay_provenance_value(&input, &[], hash_file(&archive).unwrap()); + write_json(&input.sidecar, &expected); + assert!(verify_existing_sidecar(&input, &[], &intent).is_ok()); + assert!(verify_existing_sidecar(&input, &[], &serde_json::json!({})).is_err()); + write_json(&input.sidecar, &serde_json::json!({"schema":"wrong"})); + assert!(verify_existing_sidecar(&input, &[], &intent).is_err()); + assert!(remove_overlay_intent(&dir.0).is_err()); + } + + #[test] + fn complete_overlay_recovery_checks_archive_and_intent_identity() { + let dir = TestDir::new("complete-overlay"); + let (manifest, base, policy, destination) = create_overlay_base(&dir.0); + let input = OverlayInput::load(OverlayLoadRequest { + manifest: &manifest, + source_dir: &dir.0, + base_archive: &base, + candidate_path: &policy, + destination: &destination, + sidecar: overlay_sidecar(&destination).unwrap(), + }) + .unwrap(); + let staging = create_overlay_staging(&destination).unwrap(); + let mut prepared = encode_candidates(&input, &staging).unwrap(); + let intent = overlay_intent_value(&input, &prepared); + publish_overlay(&input, &prepared).unwrap(); + assert_archive_identity_rejections(&destination, &mut prepared); + verify_complete_overlay(&input, &prepared, &intent).unwrap(); + assert_intent_identity_rejections(&input, &prepared, &intent); + } + + fn verified_overlay_summary(destination: &Path) -> kar::Summary { + kar::verify_with_sources(destination).unwrap().0 + } + + fn assert_archive_identity_rejections(destination: &Path, prepared: &mut [Prepared]) { + let mut wrong_summary = verified_overlay_summary(destination); + wrong_summary.source_bytes += 1; + assert!(verify_overlay_archive(destination, &wrong_summary, prepared).is_err()); + let archive_summary = verified_overlay_summary(destination); + assert!(verify_overlay_archive(destination, &archive_summary, &[]).is_err()); + let expected_name = prepared[0].name.clone(); + prepared[0].name.push_str("-changed"); + assert!(verify_overlay_archive(destination, &archive_summary, prepared).is_err()); + prepared[0].name = expected_name; + prepared[0].f32_sha256[0] ^= 1; + assert!(verify_overlay_archive(destination, &archive_summary, prepared).is_err()); + prepared[0].f32_sha256[0] ^= 1; + prepared[0].source_offset += 1; + assert!(verify_overlay_archive(destination, &archive_summary, prepared).is_err()); + prepared[0].source_offset -= 1; + } + + fn assert_intent_identity_rejections( + input: &OverlayInput<'_>, + prepared: &[Prepared], + intent: &serde_json::Value, + ) { + let mut stale = intent.clone(); + stale["schema"] = serde_json::json!("wrong-intent"); + assert!(verify_complete_overlay(input, prepared, &stale).is_err()); + fs::remove_file(&input.sidecar).unwrap(); + assert!(verify_complete_overlay(input, prepared, intent).is_err()); + } + + #[test] + fn overlay_staging_collision_and_base_shard_mismatch_fail_closed() { + let dir = TestDir::new("staging-collision"); + let destination = dir.0.join("overlay.kar"); + let staging = create_overlay_staging(&destination).unwrap(); + assert!(create_overlay_staging(&destination).is_err()); + + let base: BaseProvenance = serde_json::from_value(base_value_with_shard( + serde_json::json!([]), + "base.gguf", + 1, + "aa", + )) + .unwrap(); + let entry = crate::model::ModelFile { + name: "other.gguf".into(), + url: String::new(), + size: 1, + sha256: "aa".into(), + }; + assert!(ensure_shard_in_base(&entry, &base).is_err()); + let mut wrong_identity = entry; + wrong_identity.name = "base.gguf".into(); + wrong_identity.size = 2; + assert!(ensure_shard_in_base(&wrong_identity, &base).is_err()); + wrong_identity.size = 1; + wrong_identity.sha256 = "bb".into(); + assert!(ensure_shard_in_base(&wrong_identity, &base).is_err()); + drop(staging); + } + + #[test] + fn duplicate_overlay_candidate_names_are_rejected_before_encoding() { + let dir = TestDir::new("duplicate-candidates"); + let (manifest, base, policy, destination) = create_overlay_base(&dir.0); + let mut input = OverlayInput::load(OverlayLoadRequest { + manifest: &manifest, + source_dir: &dir.0, + base_archive: &base, + candidate_path: &policy, + destination: &destination, + sidecar: overlay_sidecar(&destination).unwrap(), + }) + .unwrap(); + input.candidates.records = vec![ + Candidate { + name: "weight".into(), + elements: 32, + }, + Candidate { + name: "weight".into(), + elements: 32, + }, + ]; + let staging = create_overlay_staging(&destination).unwrap(); + assert!(matches!( + encode_candidates(&input, &staging), + Err(error) if error.contains("duplicate KAR overlay candidate") + )); + } + + #[test] + fn candidate_section_verification_rejects_changed_source_and_derived_hashes() { + let dir = TestDir::new("candidate-section-digest"); + let (candidate, selected, _) = candidate_record_fixture(); + let source_path = dir.0.join("source.gguf"); + fs::write(&source_path, b"fixture").unwrap(); + let mut source = File::open(source_path).unwrap(); + let staging = Staging(dir.0.clone()); + let calibration = kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], + }; + let request = CandidateSectionRequest { + staging: &staging, + candidate: &candidate, + number: 0, + selected, + source: &mut source, + calibration: &calibration, + f32_sha256: [7; 32], + }; + assert_candidate_section_hash_rejections(&request); + } + + fn assert_candidate_section_hash_rejections(request: &CandidateSectionRequest<'_, '_>) { + let section = kar_stream_encode::SectionResult { + bytes: 0, + digest: [0; 32], + source_digest: [7; 32], + derived_digest: [7; 32], + relative_l2: 0.0, + }; + assert!(verify_candidate_section(request, §ion).is_ok()); + let changed_source = kar_stream_encode::SectionResult { + bytes: 0, + digest: [0; 32], + source_digest: [8; 32], + derived_digest: [7; 32], + relative_l2: 0.0, + }; + assert!(verify_candidate_section(request, &changed_source).is_err()); + let changed_derived = kar_stream_encode::SectionResult { + bytes: 0, + digest: [0; 32], + source_digest: [7; 32], + derived_digest: [8; 32], + relative_l2: 0.0, + }; + assert!(verify_candidate_section(request, &changed_derived).is_err()); + } + + #[test] + fn source_mapping_rejects_duplicate_names_and_architectures() { + let duplicate = TestDir::new("duplicate-shard-name"); + let (manifest, base) = two_shard_mapping(&duplicate.0, "weight", "qwen35"); + assert!(matches!( + load_overlay_sources(&manifest, &duplicate.0, &base), + Err(error) if error.contains("duplicate GGUF tensor") + )); + + let mismatch = TestDir::new("shard-architecture"); + let (manifest, base) = two_shard_mapping(&mismatch.0, "other", "llama"); + assert!(matches!( + load_overlay_sources(&manifest, &mismatch.0, &base), + Err(error) if error.contains("architectures differ") + )); + } + + #[test] + fn shard_loading_candidate_sampling_and_calibration_verify_source_identity() { + let dir = TestDir::new("source-map"); + let payload = (0..32u32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let shard = gguf_f32("weight", "qwen35", &payload); + let shard_path = dir.0.join("a.gguf"); + fs::write(&shard_path, &shard).unwrap(); + let shard_digest = hex::encode(Sha256::digest(&shard)); + let source_digest = hex::encode(Sha256::digest(&payload)); + let tensor = serde_json::json!({ + "name":"weight", "source_kind":0, "source_sha256":source_digest, + "derived_offset":0, "derived_bytes":128, "f32_sha256":source_digest + }); + let base = shard_base("a.gguf", shard.len() as u64, &shard_digest, tensor); + let source_manifest = manifest("a.gguf", shard.len() as u64, shard_digest.clone()); + let sources = load_overlay_sources(&source_manifest, &dir.0, &base).unwrap(); + assert_eq!(sources.architecture.as_deref(), Some("qwen35")); + assert!(sources.locations.contains_key("weight")); + let selected = candidate_source(&base, &sources.locations, "weight").unwrap(); + let (_, sample, digest) = candidate_sample(&selected).unwrap(); + let expected_digest: [u8; 32] = Sha256::digest(&payload).into(); + assert_eq!(digest, expected_digest); + assert_eq!(sample.len(), 32); + assert!(fit_candidate(&sample, 3, "weight").is_ok()); + assert!(fit_candidate(&[], 3, "weight").is_err()); + assert!(candidate_source(&base, &sources.locations, "missing").is_err()); + assert!(candidate_source(&base, &HashMap::new(), "weight").is_err()); + assert_shard_mapping_failures(&dir.0, &base, shard_digest); + } + + fn assert_shard_mapping_failures(directory: &Path, base: &BaseProvenance, digest: String) { + assert!(load_overlay_sources(&manifest("a.gguf", 1, digest), directory, base).is_err()); + let missing = manifest("missing.gguf", 1, "00".repeat(32)); + assert!(load_overlay_sources(&missing, directory, base).is_err()); + } + + #[test] + fn candidate_record_validation_checks_every_source_mapping_field() { + let (candidate, selected, record) = candidate_record_fixture(); + assert!(validate_candidate_record(&candidate, &selected, &record, 32).is_ok()); + rejected_candidate_record( + &Candidate { + name: "weight".into(), + elements: 31, + }, + &selected, + &record, + 32, + ); + } + + #[test] + fn candidate_record_validation_rejects_mismatched_source_mapping() { + let (candidate, selected, mut record) = candidate_record_fixture(); + record.offset += 1; + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, selected, mut record) = candidate_record_fixture(); + record.digest[0] ^= 1; + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, selected, mut record) = candidate_record_fixture(); + record.n_elements += 1; + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, selected, mut record) = candidate_record_fixture(); + record.dimensions[0] += 1; + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, selected, mut record) = candidate_record_fixture(); + record.name = "other".into(); + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, mut selected, record) = candidate_record_fixture(); + selected.derived_bytes += 4; + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, mut selected, record) = candidate_record_fixture(); + selected.derived_offset += 1; + rejected_candidate_record(&candidate, &selected, &record, 32); + let (candidate, mut selected, record) = candidate_record_fixture(); + selected.f32_sha256 = "not-a-digest"; + rejected_candidate_record(&candidate, &selected, &record, 32); + } + + #[test] + fn candidate_record_validation_rejects_element_count_overflow() { + let (mut candidate, selected, record) = candidate_record_fixture(); + candidate.elements = u64::MAX; + rejected_candidate_record(&candidate, &selected, &record, u64::MAX); + } } /// Compare complete selected tensors against the verified source bytes. diff --git a/control-plane/src/kar_stream_encode.rs b/control-plane/src/kar_stream_encode.rs index 830a28fd..2cfbdf3c 100644 --- a/control-plane/src/kar_stream_encode.rs +++ b/control-plane/src/kar_stream_encode.rs @@ -37,6 +37,13 @@ struct SectionLayout { section_bytes: u64, } +struct SectionLayoutValues { + books_start: u64, + planes_start: u64, + plane_stride: u64, + section_bytes: u64, +} + struct SectionEncoder<'a> { path: std::path::PathBuf, calibration: &'a kar_codec::Calibration, @@ -53,6 +60,14 @@ struct SectionEncoder<'a> { pub fn encode_section( reader: &mut R, request: &SectionRequest<'_>, +) -> Result { + encode_section_with_set_len(reader, request, File::set_len) +} + +fn encode_section_with_set_len( + reader: &mut R, + request: &SectionRequest<'_>, + set_len: fn(&File, u64) -> std::io::Result<()>, ) -> Result { let layout = SectionLayout::new(request.elements, request.calibration)?; let section = OpenOptions::new() @@ -61,8 +76,7 @@ pub fn encode_section( .create_new(true) .open(request.destination) .map_err(|error| error.to_string())?; - let result = section - .set_len(layout.section_bytes) + let result = set_len(§ion, layout.section_bytes) .map_err(|error| error.to_string()) .and_then(|()| encode_section_contents(reader, request, &layout)); drop(section); @@ -77,39 +91,51 @@ impl SectionLayout { validate_calibration(elements, calibration)?; let levels = calibration.books.len(); let words = elements.div_ceil(32); - let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?; - let books_start = round_up(scales_bytes, 16)?; - let books_bytes = (1u64 << (levels + 2)) - 4; - let planes_start = round_up( - books_start - .checked_add(books_bytes) - .ok_or("KAR books overflow")?, - 16, - )?; - let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?; - if plane_stride > u32::MAX as u64 { - return Err("KAR plane stride exceeds format limit".into()); - } - let planes_bytes = plane_stride - .checked_mul(levels as u64) - .ok_or("KAR planes overflow")?; - let section_bytes = round_up( - planes_start - .checked_add(planes_bytes) - .ok_or("KAR section overflow")?, - 256, - )?; + let values = SectionLayoutValues::calculate(words, levels)?; Ok(Self { levels, words, + books_start: values.books_start, + planes_start: values.planes_start, + plane_stride: values.plane_stride, + section_bytes: values.section_bytes, + }) + } +} + +impl SectionLayoutValues { + fn calculate(words: u64, levels: usize) -> Result { + let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?; + let books_start = round_up(scales_bytes, 16)?; + let books_bytes = (1u64 << (levels + 2)) - 4; + let books_end = books_start + .checked_add(books_bytes) + .ok_or("KAR books overflow")?; + let planes_start = round_up(books_end, 16)?; + let plane_stride = plane_stride(words)?; + let planes_bytes = plane_stride + .checked_mul(levels as u64) + .ok_or("KAR planes overflow")?; + let planes_end = planes_start + .checked_add(planes_bytes) + .ok_or("KAR section overflow")?; + Ok(Self { books_start, planes_start, plane_stride, - section_bytes, + section_bytes: round_up(planes_end, 256)?, }) } } +fn plane_stride(words: u64) -> Result { + let stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?; + if stride > u32::MAX as u64 { + return Err("KAR plane stride exceeds format limit".into()); + } + Ok(stride) +} + fn validate_calibration(elements: u64, calibration: &kar_codec::Calibration) -> Result<(), String> { let levels = calibration.books.len(); if elements == 0 @@ -231,14 +257,14 @@ impl<'a> SectionEncoder<'a> { } fn write_pending(&mut self, count: usize) -> Result<(), String> { - write_group( - &self.pending[..count], - self.calibration, - &mut self.scale_writer, - &mut self.plane_writers, - &mut self.error_sum, - &mut self.reference_sum, - )?; + let mut output = GroupOutput { + calibration: self.calibration, + scales: &mut self.scale_writer, + planes: &mut self.plane_writers, + error_sum: &mut self.error_sum, + reference_sum: &mut self.reference_sum, + }; + write_group(&self.pending[..count], &mut output)?; self.filled = 0; self.groups += 1; Ok(()) @@ -277,57 +303,106 @@ impl<'a> SectionEncoder<'a> { fn write_books(&self, offset: u64) -> Result<(), String> { let mut writer = writer_at(&self.path, offset)?; - for book in &self.calibration.books { - for bits in book { - writer - .write_all(&bits.to_le_bytes()) - .map_err(|error| error.to_string())?; - } - } + write_book_values(&mut writer, &self.calibration.books)?; writer.flush().map_err(|error| error.to_string())?; Ok(()) } } -fn write_group( - weights: &[f32], - calibration: &kar_codec::Calibration, - scales: &mut BufWriter, - planes: &mut [BufWriter], - error_sum: &mut f64, - reference_sum: &mut f64, -) -> Result<(), String> { - let mut normalized = [0.0f32; 32]; - let scale = kar_codec::normalize_group_into(weights, &mut normalized)?; - scales - .write_all(&scale.to_le_bytes()) - .map_err(|error| error.to_string())?; - let mut words = [0u32; 8]; - let final_book = calibration.books.last().ok_or("missing KAR codebook")?; - let rounded_scale = kar_codec::f16_bits_to_f32(scale); - for (position, value) in normalized.iter().enumerate() { - let index = calibration - .boundaries - .partition_point(|boundary| *boundary < *value); - for (level, word) in words[..planes.len()].iter_mut().enumerate() { - let bit = (index >> (planes.len() - 1 - level)) & 1; - *word |= (bit as u32) << position; - } - if let Some(original) = weights.get(position) { - let rebuilt = kar_codec::f16_bits_to_f32(final_book[index]) * rounded_scale; - let delta = f64::from(*original) - f64::from(rebuilt); - *error_sum += delta * delta; - *reference_sum += f64::from(*original).powi(2); - } - } - for (writer, word) in planes.iter_mut().zip(words) { +fn write_book_values(writer: &mut W, books: &[Vec]) -> Result<(), String> { + for bits in books.iter().flatten() { writer - .write_all(&word.to_le_bytes()) + .write_all(&bits.to_le_bytes()) .map_err(|error| error.to_string())?; } Ok(()) } +struct GroupOutput<'a> { + calibration: &'a kar_codec::Calibration, + scales: &'a mut BufWriter, + planes: &'a mut [BufWriter], + error_sum: &'a mut f64, + reference_sum: &'a mut f64, +} + +struct PackValue<'a> { + position: usize, + value: f32, + weights: &'a [f32], + final_book: &'a [u16], + rounded_scale: f32, + words: &'a mut [u32; 8], +} + +fn write_group(weights: &[f32], output: &mut GroupOutput<'_>) -> Result<(), String> { + output.write(weights) +} + +impl GroupOutput<'_> { + fn write(&mut self, weights: &[f32]) -> Result<(), String> { + let mut normalized = [0.0f32; 32]; + let scale = kar_codec::normalize_group_into(weights, &mut normalized)?; + self.scales + .write_all(&scale.to_le_bytes()) + .map_err(|error| error.to_string())?; + let words = self.pack_words(weights, &normalized, scale)?; + self.write_words(words) + } + + fn pack_words( + &mut self, + weights: &[f32], + normalized: &[f32; 32], + scale: u16, + ) -> Result<[u32; 8], String> { + let mut words = [0u32; 8]; + let final_book = self + .calibration + .books + .last() + .ok_or("missing KAR codebook")?; + let rounded_scale = kar_codec::f16_bits_to_f32(scale); + for (position, value) in normalized.iter().enumerate() { + self.pack_value(PackValue { + position, + value: *value, + weights, + final_book, + rounded_scale, + words: &mut words, + }); + } + Ok(words) + } + + fn pack_value(&mut self, value: PackValue<'_>) { + let index = self + .calibration + .boundaries + .partition_point(|boundary| *boundary < value.value); + for (level, word) in value.words[..self.planes.len()].iter_mut().enumerate() { + let bit = (index >> (self.planes.len() - 1 - level)) & 1; + *word |= (bit as u32) << value.position; + } + if let Some(original) = value.weights.get(value.position) { + let rebuilt = kar_codec::f16_bits_to_f32(value.final_book[index]) * value.rounded_scale; + let delta = f64::from(*original) - f64::from(rebuilt); + *self.error_sum += delta * delta; + *self.reference_sum += f64::from(*original).powi(2); + } + } + + fn write_words(&mut self, words: [u32; 8]) -> Result<(), String> { + for (writer, word) in self.planes.iter_mut().zip(words) { + writer + .write_all(&word.to_le_bytes()) + .map_err(|error| error.to_string())?; + } + Ok(()) + } +} + fn writer_at(path: &Path, offset: u64) -> Result, String> { let mut file = OpenOptions::new() .write(true) @@ -366,10 +441,24 @@ mod tests { use std::io::Cursor; use std::time::{SystemTime, UNIX_EPOCH}; + fn reject_section_size(_: &File, _: u64) -> std::io::Result<()> { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + #[test] - fn streamed_section_matches_existing_writer_and_forms_verified_archive() { + fn plane_stride_rejects_overflow_and_format_limit() { + assert_eq!(plane_stride(1), Ok(16)); + assert_eq!(plane_stride(u64::MAX), Err("KAR planes overflow".into())); + assert_eq!( + plane_stride(1_073_741_824), + Err("KAR plane stride exceeds format limit".into()) + ); + } + + #[test] + fn failed_stream_encode_removes_partial_section() { let root = std::env::temp_dir().join(format!( - "strata-stream-section-{}-{}", + "strata-stream-failure-{}-{}", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) @@ -377,19 +466,595 @@ mod tests { .as_nanos() )); fs::create_dir(&root).unwrap(); - let weights = (0..33) - .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) - .collect::>(); - let source = weights - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect::>(); + let output = root.join("partial.section"); let calibration = kar_codec::Calibration { boundaries: vec![-0.5, 0.0, 0.5], books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], }; + let result = encode_section( + &mut Cursor::new(vec![0; 4]), + &SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 8, + elements: 2, + calibration: &calibration, + destination: &output, + }, + ); + assert!(result.is_err()); + assert!(!output.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn all_zero_stream_has_defined_error_and_extra_values_are_rejected() { + let root = test_dir("zero-and-overrun"); + let calibration = test_calibration(); + assert_zero_encoding_is_finite(&root, &calibration); + assert_invalid_stream_shape(&root, &calibration, 12, 2, "beyond its shape"); + assert_invalid_stream_shape(&root, &calibration, 4, 2, "shape mismatch"); + assert!(sync_file(&root.join("missing.section")).is_err()); + assert_set_len_failure_for_zero_fixture(&root, &calibration); + fs::remove_dir_all(root).unwrap(); + } + + fn assert_zero_encoding_is_finite(root: &Path, calibration: &kar_codec::Calibration) { + let path = root.join("zero.section"); + let summary = + encode_fixture(Cursor::new(vec![0u8; 128]), &path, calibration, 128, 32).unwrap(); + assert!(summary.relative_l2.is_finite() && summary.relative_l2 < 1e-6); + assert!(sync_file(&path).is_ok()); + } + + fn assert_invalid_stream_shape( + root: &Path, + calibration: &kar_codec::Calibration, + bytes: u64, + elements: u64, + expected: &str, + ) { + let path = root.join(format!("invalid-{elements}-{bytes}.section")); + let error = encode_fixture( + Cursor::new(vec![0u8; bytes as usize]), + &path, + calibration, + bytes, + elements, + ) + .err() + .unwrap(); + assert!(error.contains(expected)); + assert!(!path.exists()); + } + + fn encode_fixture( + mut reader: R, + destination: &Path, + calibration: &kar_codec::Calibration, + source_bytes: u64, + elements: u64, + ) -> Result { + encode_section( + &mut reader, + &SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes, + elements, + calibration, + destination, + }, + ) + } + + fn assert_set_len_failure_for_zero_fixture(root: &Path, calibration: &kar_codec::Calibration) { + let path = root.join("cannot-size.section"); + let mut source = Cursor::new(vec![0u8; 128]); + let request = SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 128, + elements: 32, + calibration, + destination: &path, + }; + assert!(encode_section_with_set_len(&mut source, &request, reject_section_size).is_err()); + assert!(!path.exists()); + } + + #[test] + fn section_encoder_accepts_borrowed_and_file_readers() { + let root = test_dir("reader-types"); + let calibration = test_calibration(); + let bytes = vec![0u8; 128]; + let mut borrowed = Cursor::new(&bytes); + assert!(encode_reader(&mut borrowed, &root.join("borrowed.section"), &calibration).is_ok()); + let source = root.join("source.bin"); + fs::write(&source, &bytes).unwrap(); + let mut file = File::open(source).unwrap(); + assert!(encode_reader(&mut file, &root.join("file.section"), &calibration).is_ok()); + fs::remove_dir_all(root).unwrap(); + } + + fn encode_reader( + reader: &mut R, + path: &Path, + calibration: &kar_codec::Calibration, + ) -> Result { + encode_section( + reader, + &SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 128, + elements: 32, + calibration, + destination: path, + }, + ) + } + + fn assert_section_size_failure( + reader: &mut R, + destination: &Path, + calibration: &kar_codec::Calibration, + ) { + let error = encode_section_with_set_len( + reader, + &SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 128, + elements: 32, + calibration, + destination, + }, + reject_section_size, + ) + .err() + .unwrap(); + assert!(error.to_lowercase().contains("denied"), "{error}"); + assert!(!destination.exists()); + } + + #[test] + fn section_sizing_errors_clean_up_for_each_supported_reader() { + let root = test_dir("set-len-errors"); + let bytes = vec![0u8; 128]; + let calibration = test_calibration(); + let mut owned = Cursor::new(bytes.clone()); + assert_section_size_failure(&mut owned, &root.join("owned.section"), &calibration); + let mut borrowed = Cursor::new(&bytes); + assert_section_size_failure(&mut borrowed, &root.join("borrowed.section"), &calibration); + let input = root.join("source.bin"); + fs::write(&input, bytes).unwrap(); + let mut file = File::open(input).unwrap(); + assert_section_size_failure(&mut file, &root.join("file.section"), &calibration); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn file_backed_encoder_matches_cursor_bytes() { + let root = test_dir("file-parity"); + let calibration = test_calibration(); + let request = |destination| SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 128, + elements: 32, + calibration: &calibration, + destination, + }; + let mut cursor = Cursor::new(vec![0u8; 128]); + let cursor_path = root.join("cursor.section"); + let memory = encode_section(&mut cursor, &request(&cursor_path)).unwrap(); + let source = root.join("source.bin"); + fs::write(&source, [0u8; 128]).unwrap(); + let disk_path = root.join("file.section"); + let disk = encode_section(&mut File::open(source).unwrap(), &request(&disk_path)).unwrap(); + assert_eq!(disk.bytes, memory.bytes); + assert_eq!(disk.digest, memory.digest); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn encoder_rejects_decoded_byte_count_mismatch() { + let root = test_dir("decoded-size"); + let calibration = test_calibration(); + let layout = SectionLayout::new(1, &calibration).unwrap(); + let path = root.join("section.bin"); + File::create(&path) + .unwrap() + .set_len(layout.section_bytes) + .unwrap(); + let mut encoder = SectionEncoder::new(&path, &calibration, &layout).unwrap(); + encoder.push(&1.0f32.to_le_bytes(), 1).unwrap(); + assert_eq!( + encoder.finish(1, 0, &layout).unwrap_err(), + "GGUF decoded tensor shape mismatch" + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn section_encoder_finishes_and_writes_canonical_codebooks() { + let root = test_dir("finish-success"); + let path = root.join("section.bin"); + let calibration = test_calibration(); + let layout = SectionLayout::new(32, &calibration).unwrap(); + File::create(&path) + .unwrap() + .set_len(layout.section_bytes) + .unwrap(); + let mut encoder = SectionEncoder::new(&path, &calibration, &layout).unwrap(); + let values = (0..32).map(|index| (index as f32 - 15.5) / 16.0); + let bytes = values.flat_map(f32::to_le_bytes).collect::>(); + encoder.push(&bytes, 32).unwrap(); + assert!( + encoder + .finish(32, bytes.len() as u64, &layout) + .unwrap() + .is_finite() + ); + + let archive = fs::read(&path).unwrap(); + let expected = calibration + .books + .iter() + .flatten() + .flat_map(|bits| bits.to_le_bytes()) + .collect::>(); + let end = layout.books_start as usize + expected.len(); + assert_eq!(&archive[layout.books_start as usize..end], expected); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn plane_writer_offset_failure_is_returned() { + let root = test_dir("plane-open"); + let calibration = test_calibration(); + let path = root.join("section.bin"); + File::create(&path).unwrap(); + let layout = SectionLayout { + levels: 2, + words: 1, + books_start: 16, + planes_start: u64::MAX, + plane_stride: 16, + section_bytes: 256, + }; + assert!(SectionEncoder::new(&path, &calibration, &layout).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + struct FailingWriter; + + impl Write for FailingWriter { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("injected book write failure")) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn book_value_writer_propagates_io_errors() { + let error = write_book_values(&mut FailingWriter, &test_calibration().books).unwrap_err(); + assert!(error.contains("injected book write failure")); + } + + #[cfg(unix)] + #[test] + fn file_book_writer_propagates_device_write_errors() { + let Ok(file) = OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::with_capacity(1, file); + assert!(write_book_values(&mut writer, &test_calibration().books).is_err()); + } + + #[cfg(unix)] + #[test] + fn encoder_reports_plane_flush_failure_after_buffered_group_write() { + let Ok(first) = OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let Ok(second) = OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let root = test_dir("plane-flush"); + let calibration = test_calibration(); + let layout = SectionLayout::new(32, &calibration).unwrap(); + let mut encoder = flush_failure_encoder(&root, &calibration, first, second); + let bytes = (0..32) + .flat_map(|n| (n as f32).to_le_bytes()) + .collect::>(); + encoder.push(&bytes, 32).unwrap(); + assert!(encoder.finish(32, bytes.len() as u64, &layout).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn flush_failure_encoder<'a>( + root: &Path, + calibration: &'a kar_codec::Calibration, + first: File, + second: File, + ) -> SectionEncoder<'a> { + let path = root.join("section.bin"); + let layout = SectionLayout::new(32, calibration).unwrap(); + File::create(&path) + .unwrap() + .set_len(layout.section_bytes) + .unwrap(); + SectionEncoder { + path, + calibration, + scale_writer: BufWriter::new(File::create(root.join("scales.bin")).unwrap()), + plane_writers: vec![BufWriter::new(first), BufWriter::new(second)], + pending: [0.0; 32], + filled: 0, + seen: 0, + groups: 0, + error_sum: 0.0, + reference_sum: 0.0, + } + } + + #[cfg(unix)] + #[test] + fn group_output_propagates_scale_and_plane_write_failures() { + let Some(full) = OpenOptions::new().write(true).open("/dev/full").ok() else { + return; + }; + let root = test_dir("group-output-errors"); + let calibration = test_calibration(); + let weights = [0.25f32; 32]; + assert_scale_writer_error(full, &root, &calibration, &weights); + assert_plane_writer_error(&root, &calibration, &weights); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn assert_scale_writer_error( + full: File, + root: &Path, + calibration: &kar_codec::Calibration, + weights: &[f32; 32], + ) { + let mut scales = BufWriter::with_capacity(1, full); + let mut planes = vec![BufWriter::new( + File::create(root.join("planes.bin")).unwrap(), + )]; + let mut error_sum = 0.0; + let mut reference_sum = 0.0; + assert!( + GroupOutput { + calibration, + scales: &mut scales, + planes: &mut planes, + error_sum: &mut error_sum, + reference_sum: &mut reference_sum + } + .write(weights) + .is_err() + ); + } + + #[cfg(unix)] + fn assert_plane_writer_error( + root: &Path, + calibration: &kar_codec::Calibration, + weights: &[f32; 32], + ) { + let full = OpenOptions::new().write(true).open("/dev/full").unwrap(); + let mut scales = BufWriter::new(File::create(root.join("scales.bin")).unwrap()); + let mut planes = vec![BufWriter::with_capacity(1, full)]; + let mut error_sum = 0.0; + let mut reference_sum = 0.0; + assert!( + GroupOutput { + calibration, + scales: &mut scales, + planes: &mut planes, + error_sum: &mut error_sum, + reference_sum: &mut reference_sum + } + .write(weights) + .is_err() + ); + } + + fn test_dir(label: &str) -> std::path::PathBuf { + let path = + std::env::temp_dir().join(format!("strata-stream-{label}-{}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).unwrap(); + path + } + + fn test_calibration() -> kar_codec::Calibration { + kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], + } + } + + #[test] + fn calibration_validation_rejects_each_invalid_stream_shape() { + let valid = test_calibration(); + assert!(validate_calibration(1, &valid).is_ok()); + assert!(validate_calibration(0, &valid).is_err()); + assert_invalid_calibrations(&valid); + assert_excessive_calibration_levels(); + } + + fn assert_invalid_calibrations(valid: &kar_codec::Calibration) { + for calibration in [ + kar_codec::Calibration { + boundaries: vec![], + books: vec![], + }, + kar_codec::Calibration { + boundaries: vec![f32::NAN], + books: vec![vec![0x3c00, 0x3c00]], + }, + kar_codec::Calibration { + boundaries: vec![1.0, 0.0, 2.0], + books: valid.books.clone(), + }, + kar_codec::Calibration { + boundaries: valid.boundaries.clone(), + books: vec![vec![0x3c00]], + }, + kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0x7c00, 0x3800], valid.books[1].clone()], + }, + ] { + assert!(validate_calibration(1, &calibration).is_err()); + } + } + + fn assert_excessive_calibration_levels() { + let too_many = (0..9).map(|level| vec![0x3c00; 1 << (level + 1)]).collect(); + assert!( + validate_calibration( + 1, + &kar_codec::Calibration { + boundaries: vec![0.0; 511], + books: too_many, + } + ) + .is_err() + ); + } + + #[test] + fn calibration_validation_rejects_wrong_sized_book_on_valid_boundaries() { + let mut calibration = test_calibration(); + calibration.books[0].pop(); + assert_eq!( + validate_calibration(1, &calibration).unwrap_err(), + "invalid streamed KAR calibration" + ); + } + + fn rejects_existing_destination( + reader: &mut R, + path: &Path, + calibration: &kar_codec::Calibration, + ) { + fs::write(path, b"owned output").unwrap(); + let result = encode_section( + reader, + &SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 4, + elements: 1, + calibration, + destination: path, + }, + ); + assert!(result.is_err()); + assert_eq!(fs::read(path).unwrap(), b"owned output"); + fs::remove_file(path).unwrap(); + } + + #[test] + fn existing_destination_is_rejected_for_supported_reader_shapes() { + let root = test_dir("existing-destination"); + let calibration = test_calibration(); + let borrowed = vec![0u8; 4]; + rejects_existing_destination( + &mut Cursor::new(vec![0u8; 4]), + &root.join("owned-vector.section"), + &calibration, + ); + rejects_existing_destination( + &mut Cursor::new(&borrowed), + &root.join("borrowed-vector.section"), + &calibration, + ); + let source = root.join("source.bin"); + fs::write(&source, [0u8; 4]).unwrap(); + rejects_existing_destination( + &mut File::open(source).unwrap(), + &root.join("file-reader.section"), + &calibration, + ); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn section_encoder_surfaces_flush_and_group_count_failures() { + if OpenOptions::new().write(true).open("/dev/full").is_err() { + return; + } + let calibration = test_calibration(); + let correct = SectionLayout::new(32, &calibration).unwrap(); + let mut wrong = SectionLayout::new(32, &calibration).unwrap(); + wrong.words += 1; + let mut count_encoder = + SectionEncoder::new(Path::new("/dev/null"), &calibration, &wrong).unwrap(); + count_encoder.push(&[0u8; 128], 32).unwrap(); + assert!( + count_encoder + .finish(32, 128, &wrong) + .unwrap_err() + .contains("group count") + ); + let mut failing = + SectionEncoder::new(Path::new("/dev/full"), &calibration, &correct).unwrap(); + failing.push(&[0u8; 128], 32).unwrap(); + assert!(failing.finish(32, 128, &correct).is_err()); + assert!(failing.write_books(0).is_err()); + } + + #[test] + fn streamed_section_matches_existing_writer_and_forms_verified_archive() { + let root = test_dir("parity-archive"); + let weights = parity_weights(); + let source = raw_f32_bytes(&weights); + let calibration = test_calibration(); let expected = kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap(); + let source_digest: [u8; 32] = Sha256::digest(&source).into(); + let reference = + create_reference_nested_section(&root, source_digest, &calibration, &expected); + let output = root.join("streamed.section"); + let streamed = encode_parity_section(&source, &output, &weights, &calibration); + assert_parity_output(&output, &reference, &streamed, source_digest); + let archive = root.join("model.kar"); + write_parity_archive(&archive, &output, &streamed, source_digest, &source); + assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); + fs::remove_dir_all(root).unwrap(); + } + + fn parity_weights() -> Vec { + (0..33) + .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) + .collect() + } + + fn raw_f32_bytes(weights: &[f32]) -> Vec { + weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect() + } + + fn create_reference_nested_section( + root: &Path, + source_digest: [u8; 32], + calibration: &kar_codec::Calibration, + expected: &kar_codec::EncodedPlanes, + ) -> std::path::PathBuf { let books = calibration .books .iter() @@ -400,89 +1065,116 @@ mod tests { .iter() .map(Vec::as_slice) .collect::>(); - let source_digest: [u8; 32] = Sha256::digest(&source).into(); - let reference = root.join("reference.section"); - kar_writer::write_nested_section( - &reference, - &kar_writer::Tensor { - name: "expert", - dims: &[33], - source_dtype: 0, - source_digest, - source_offset: 0, - data: kar_writer::TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &expected.scales, - books: &books, - planes: &planes, - }, + let path = root.join("reference.section"); + let tensor = parity_reference_tensor(source_digest, expected, &books, &planes); + kar_writer::write_nested_section(&path, &tensor).unwrap(); + path + } + + fn parity_reference_tensor<'a>( + source_digest: [u8; 32], + expected: &'a kar_codec::EncodedPlanes, + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], + ) -> kar_writer::Tensor<'a> { + kar_writer::Tensor { + name: "expert", + dims: &[33], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &expected.scales, + books, + planes, }, - ) - .unwrap(); - let output = root.join("streamed.section"); - let streamed = encode_section( - &mut Cursor::new(&source), + } + } + + fn encode_parity_section( + source: &[u8], + output: &Path, + weights: &[f32], + calibration: &kar_codec::Calibration, + ) -> SectionResult { + encode_section( + &mut Cursor::new(source), &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: source.len() as u64, elements: weights.len() as u64, - calibration: &calibration, - destination: &output, + calibration, + destination: output, }, ) - .unwrap(); - assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap()); + .unwrap() + } + + fn assert_parity_output( + output: &Path, + reference: &Path, + streamed: &SectionResult, + source_digest: [u8; 32], + ) { + assert_eq!(fs::read(output).unwrap(), fs::read(reference).unwrap()); assert_eq!(streamed.source_digest, source_digest); assert_eq!(streamed.derived_digest, source_digest); assert!(streamed.relative_l2.is_finite()); - let archive = root.join("model.kar"); - kar_writer::write_archive( - &archive, - &kar_writer::SourceIdentity { - name: "streamed-test", - architecture: "synthetic", - builder: "test-streamed-g32-l2", - digest: source_digest, - total_elements: 33, - bytes: source.len() as u64, + } + + fn write_parity_archive( + archive: &Path, + output: &Path, + streamed: &SectionResult, + source_digest: [u8; 32], + source: &[u8], + ) { + let identity = kar_writer::SourceIdentity { + name: "streamed-test", + architecture: "synthetic", + builder: "test-streamed-g32-l2", + digest: source_digest, + total_elements: 33, + bytes: source.len() as u64, + }; + let tensor = parity_file_tensor(output, streamed, source_digest); + kar_writer::write_archive(archive, &identity, &[tensor]).unwrap(); + } + + fn parity_file_tensor<'a>( + output: &'a Path, + streamed: &SectionResult, + source_digest: [u8; 32], + ) -> kar_writer::Tensor<'a> { + kar_writer::Tensor { + name: "expert", + dims: &[33], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: output, + offset: 0, + bytes: streamed.bytes, + digest: streamed.digest, }, - &[kar_writer::Tensor { - name: "expert", - dims: &[33], - source_dtype: 0, - source_digest, - source_offset: 0, - data: kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - levels: 2, - path: &output, - offset: 0, - bytes: streamed.bytes, - digest: streamed.digest, - }, - }], - ) - .unwrap(); - assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); - fs::remove_dir_all(root).unwrap(); + } } #[test] fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() { - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - let source = block.repeat(257); - let calibration = kar_codec::Calibration { - boundaries: vec![-0.5, 0.0, 0.5], - books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], - }; + let source = iq3_source_blocks(257); + let calibration = test_calibration(); let path = std::env::temp_dir().join(format!( "strata-iq3-stream-{}-{}.section", std::process::id(), @@ -491,28 +1183,46 @@ mod tests { .unwrap() .as_nanos() )); - let result = encode_section( - &mut Cursor::new(&source), + let result = encode_iq3_section(&path, &source, &calibration); + assert_iq3_identity(&result, &source, 257); + fs::remove_file(path).unwrap(); + } + + fn iq3_source_blocks(blocks: usize) -> Vec { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + block.repeat(blocks) + } + + fn encode_iq3_section( + path: &Path, + source: &[u8], + calibration: &kar_codec::Calibration, + ) -> SectionResult { + encode_section( + &mut Cursor::new(source), &SectionRequest { absolute_offset: 0, source_kind: 21, source_bytes: source.len() as u64, elements: (257 * iq3_s::BLOCK_ELEMENTS) as u64, - calibration: &calibration, - destination: &path, + calibration, + destination: path, }, ) - .unwrap(); + .unwrap() + } + + fn assert_iq3_identity(result: &SectionResult, source: &[u8], blocks: usize) { assert_eq!( result.source_digest.as_slice(), - Sha256::digest(&source).as_slice() + Sha256::digest(source).as_slice() ); - let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS); + let virtual_f32 = 1.0f32.to_le_bytes().repeat(blocks * iq3_s::BLOCK_ELEMENTS); assert_eq!( result.derived_digest.as_slice(), Sha256::digest(&virtual_f32).as_slice() ); assert_eq!(result.relative_l2, 0.25); - fs::remove_file(path).unwrap(); } } diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 92161080..a4ad4603 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -4,14 +4,34 @@ use std::{ collections::HashSet, fs::{self, File, OpenOptions}, - io::{Read, Seek, SeekFrom, Write}, - path::Path, + io::{self, Read, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, }; +#[cfg(unix)] +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; + +#[cfg(test)] +use std::sync::atomic::{AtomicU64, Ordering}; + use sha2::{Digest, Sha256}; use crate::kar; +#[cfg(test)] +static ARCHIVE_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); +const ARCHIVE_TEMP_SLOTS: u8 = 8; + +#[cfg(test)] +thread_local! { + static ARCHIVE_CLEANUP_FAILURES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +pub(crate) fn fail_next_archive_temp_cleanup() { + ARCHIVE_CLEANUP_FAILURES.with(|failures| failures.set(failures.get() + 1)); +} + pub struct SourceIdentity<'a> { pub name: &'a str, pub architecture: &'a str, @@ -30,6 +50,97 @@ pub struct Tensor<'a> { pub data: TensorData<'a>, } +trait ArchiveOutput: Read + Write + Seek { + fn set_archive_len(&mut self, len: u64) -> io::Result<()>; + fn archive_len(&self) -> io::Result; + fn sync_archive(&self) -> io::Result<()>; + + fn seek_archive(&mut self, position: SeekFrom) -> io::Result { + self.seek(position) + } + + fn write_archive_all(&mut self, bytes: &[u8]) -> io::Result<()> { + self.write_all(bytes) + } +} + +#[cfg(test)] +#[derive(Clone, Copy, PartialEq, Eq)] +enum ArchiveOutputOperation { + SetLength, + Length, + Sync, + Seek, + Write, +} + +#[cfg(test)] +thread_local! { + static ARCHIVE_OUTPUT_FAILURE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn fail_archive_output_at(operation: ArchiveOutputOperation, call: usize) { + ARCHIVE_OUTPUT_FAILURE.with(|failure| failure.set(Some((operation, call)))); +} + +#[cfg(test)] +fn archive_output_should_fail(operation: ArchiveOutputOperation) -> bool { + ARCHIVE_OUTPUT_FAILURE.with(|failure| match failure.get() { + Some((current, 1)) if current == operation => { + failure.set(None); + true + } + Some((current, remaining)) if current == operation => { + failure.set(Some((current, remaining - 1))); + false + } + _ => false, + }) +} + +impl ArchiveOutput for File { + fn set_archive_len(&mut self, len: u64) -> io::Result<()> { + #[cfg(test)] + if archive_output_should_fail(ArchiveOutputOperation::SetLength) { + return Err(io::ErrorKind::Other.into()); + } + self.set_len(len) + } + + fn archive_len(&self) -> io::Result { + #[cfg(test)] + if archive_output_should_fail(ArchiveOutputOperation::Length) { + return Err(io::ErrorKind::Other.into()); + } + self.metadata().map(|metadata| metadata.len()) + } + + fn sync_archive(&self) -> io::Result<()> { + #[cfg(test)] + if archive_output_should_fail(ArchiveOutputOperation::Sync) { + return Err(io::ErrorKind::Other.into()); + } + self.sync_all() + } + + fn seek_archive(&mut self, position: SeekFrom) -> io::Result { + #[cfg(test)] + if archive_output_should_fail(ArchiveOutputOperation::Seek) { + return Err(io::ErrorKind::Other.into()); + } + self.seek(position) + } + + fn write_archive_all(&mut self, bytes: &[u8]) -> io::Result<()> { + #[cfg(test)] + if archive_output_should_fail(ArchiveOutputOperation::Write) { + return Err(io::ErrorKind::Other.into()); + } + self.write_all(bytes) + } +} + pub enum TensorData<'a> { Raw(&'a [u8]), RawFile { @@ -118,250 +229,359 @@ fn write_archive_inner( tensors: &[Tensor<'_>], consume_files: bool, ) -> Result { + let destination = private_archive_destination(destination)?; + reap_stale_archive_temps(&destination)?; + validate_archive_request(&destination, source, tensors)?; + let mut plan = ArchivePlan::build(source, tensors)?; + let (temporary, mut file) = create_archive_temp(&destination)?; + let result = plan.write(&mut file, source, tensors, consume_files); + if let Err(error) = result { + let _ = remove_archive_temp_locked(&temporary, &file); + drop(file); + return Err(error); + } + let published = verify_and_publish(&temporary, &destination, remove_archive_temp); + drop(file); + published +} + +fn validate_archive_request( + destination: &Path, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], +) -> Result<(), String> { if fs::symlink_metadata(destination).is_ok() || tensors.is_empty() || tensors.len() > 100_000 { return Err("KAR destination exists or tensor count is invalid".into()); } if source.bytes == 0 || source.total_elements == 0 { return Err("KAR source identity needs nonzero bytes and elements".into()); } - let mut names = Vec::new(); - let mut name_offsets = Vec::with_capacity(tensors.len()); - let mut unique = HashSet::new(); - for tensor in tensors { - if tensor.name.is_empty() || !unique.insert(tensor.name) { - return Err("KAR tensor names must be nonempty and unique".into()); - } - name_offsets.push(u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?); - push_cstr(&mut names, tensor.name)?; - } - let source_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?; - push_cstr(&mut names, source.name)?; - let source_arch = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?; - push_cstr(&mut names, source.architecture)?; - let builder_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?; - push_cstr(&mut names, source.builder)?; - if names.len() > 64 * 1024 * 1024 { - return Err("KAR string table exceeds inspector limit".into()); - } + Ok(()) +} - let directory_offset = 256u64; - let directory_bytes = (tensors.len() as u64) - .checked_mul(192) - .ok_or("KAR directory overflow")?; - let string_offset = round_up(directory_offset + directory_bytes, 64)?; - let payload_offset = round_up(string_offset + names.len() as u64, 256)?; - let mut cursor = payload_offset; - let mut total_elements = 0u64; - let mut payload_bits = 0u64; - let mut min_planes = u8::MAX; - let mut max_planes = 0u8; - let mut placed = Vec::with_capacity(tensors.len()); - for (tensor, &name_offset) in tensors.iter().zip(&name_offsets) { - let n_elements = validate_shape(tensor)?; - total_elements = total_elements - .checked_add(n_elements) - .ok_or("KAR element count overflow")?; - let (n_padded, section_bytes, scales_offset, books_offset, planes_offset, plane_stride) = - match &tensor.data { - TensorData::Raw(raw) => { - let width = if tensor.source_dtype == 0 { 4 } else { 2 }; - if raw.len() as u64 - != n_elements - .checked_mul(width) - .ok_or("KAR RAW byte count overflow")? - { - return Err(format!( - "{}: RAW byte count differs from tensor shape", - tensor.name - )); - } - (n_elements, round_up(raw.len() as u64, 256)?, 0, 0, 0, 0) - } - TensorData::RawFile { bytes, .. } => { - let width = if tensor.source_dtype == 0 { 4 } else { 2 }; - if *bytes - != n_elements - .checked_mul(width) - .ok_or("KAR RAW byte count overflow")? - { - return Err(format!( - "{}: RAW file byte count differs from tensor shape", - tensor.name - )); - } - (n_elements, round_up(*bytes, 256)?, 0, 0, 0, 0) - } - TensorData::Nested { - group, - nesting, - planes_min, - planes_max, - scales, - books, - planes, - } => { - let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?; - let layout = nested_layout( - cursor, - n_elements, - *group, - *nesting, - *planes_min, - *planes_max, - levels, - )?; - validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?; - payload_bits = payload_bits - .checked_add(layout.payload_bits) - .ok_or("KAR payload bit count overflow")?; - min_planes = min_planes.min(*planes_min); - max_planes = max_planes.max(*planes_max); - ( - layout.n_padded, - layout.section_bytes, - layout.scales_offset, - layout.books_offset, - layout.planes_offset, - layout.plane_stride, - ) - } - TensorData::NestedFile { - group, - nesting, - planes_min, - planes_max, - levels, - bytes, - .. - } => { - let layout = nested_layout( - cursor, - n_elements, - *group, - *nesting, - *planes_min, - *planes_max, - *levels, - )?; - if *bytes != layout.section_bytes { - return Err(format!( - "{}: nested file section size mismatch", - tensor.name - )); - } - payload_bits = payload_bits - .checked_add(layout.payload_bits) - .ok_or("KAR payload bit count overflow")?; - min_planes = min_planes.min(*planes_min); - max_planes = max_planes.max(*planes_max); - ( - layout.n_padded, - layout.section_bytes, - layout.scales_offset, - layout.books_offset, - layout.planes_offset, - layout.plane_stride, - ) - } - }; - placed.push(Placed { - tensor, - name_offset, - n_elements, - n_padded, - section_offset: cursor, - section_bytes, - scales_offset, - books_offset, - planes_offset, - plane_stride, - payload_crc32: 0, - }); - cursor = cursor - .checked_add(section_bytes) - .ok_or("KAR archive size overflow")?; +fn private_archive_destination(destination: &Path) -> Result { + let name = destination + .file_name() + .ok_or_else(|| "KAR destination needs a file name".to_owned())?; + let parent = destination + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + #[cfg(unix)] + { + let parent = fs::canonicalize(parent).map_err(|error| error.to_string())?; + validate_private_archive_parent(&parent)?; + Ok(parent.join(name)) } - if total_elements > source.total_elements { - return Err("KAR tensors exceed source element count".into()); + #[cfg(not(unix))] + { + Ok(parent.join(name)) } - let archive_bytes = cursor; - let temporary = archive_temporary_path(destination)?; - let mut file = OpenOptions::new() +} + +pub(crate) fn canonical_archive_destination(destination: &Path) -> Result { + private_archive_destination(destination) +} + +#[cfg(unix)] +fn validate_private_archive_parent(parent: &Path) -> Result<(), String> { + let uid = unsafe { libc::geteuid() }; + for directory in parent.ancestors().collect::>().into_iter().rev() { + let metadata = fs::symlink_metadata(directory).map_err(|error| error.to_string())?; + if !metadata.file_type().is_dir() || (metadata.uid() != 0 && metadata.uid() != uid) { + return Err("KAR parent is not owned by the service or root".into()); + } + let mode = metadata.mode(); + let sticky = mode & libc::S_ISVTX as u32 != 0; + if mode & 0o022 != 0 && !sticky { + return Err("KAR parent allows untrusted path replacement".into()); + } + } + Ok(()) +} + +fn private_archive_pair( + temporary: &Path, + destination: &Path, +) -> Result<(PathBuf, PathBuf), String> { + let temporary = private_archive_destination(temporary)?; + let destination = private_archive_destination(destination)?; + if temporary.parent() != destination.parent() { + return Err("KAR temporary and destination must share a private directory".into()); + } + Ok((temporary, destination)) +} + +fn create_archive_temp(destination: &Path) -> Result<(PathBuf, File), String> { + let destination = private_archive_destination(destination)?; + create_archive_temp_with( + &destination, + |path| archive_temp_options().open(path), + |file| file.try_lock(), + archive_temp_path_matches, + ) +} + +fn create_archive_temp_with( + destination: &Path, + mut open: impl FnMut(&Path) -> io::Result, + mut lock: impl FnMut(&File) -> Result<(), std::fs::TryLockError>, + mut matches: impl FnMut(&Path, &File) -> bool, +) -> Result<(PathBuf, File), String> { + for slot in 0..ARCHIVE_TEMP_SLOTS { + let temporary = archive_temp_path(destination, slot); + match open(&temporary) { + Ok(file) => match lock(&file) { + Ok(()) if matches(&temporary, &file) => { + return Ok((temporary, file)); + } + Ok(()) | Err(std::fs::TryLockError::WouldBlock) => drop(file), + Err(std::fs::TryLockError::Error(error)) => return Err(error.to_string()), + }, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error.to_string()), + } + } + Err("all eight KAR temporary slots are occupied".into()) +} + +fn archive_temp_path_matches(path: &Path, file: &File) -> bool { + #[cfg(unix)] + { + archive_temp_metadata_matches(file.metadata(), fs::symlink_metadata(path)) + } + #[cfg(not(unix))] + { + path.exists() + } +} + +#[cfg(unix)] +fn archive_temp_metadata_matches( + opened: io::Result, + current: io::Result, +) -> bool { + match (opened, current) { + (Ok(opened), Ok(current)) => same_inode(&opened, ¤t), + _ => false, + } +} + +fn remove_archive_temp_locked(path: &Path, file: &File) -> Result<(), String> { + let path = private_archive_destination(path)?; + if !archive_temp_path_matches(&path, file) { + return Ok(()); + } + fs::remove_file(path).map_err(|error| error.to_string()) +} + +fn archive_temp_options() -> OpenOptions { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + options.mode(0o600); + options +} + +fn archive_temp_path(destination: &Path, slot: u8) -> PathBuf { + let destination = + private_archive_destination(destination).unwrap_or_else(|_| destination.to_path_buf()); + let key = hex::encode(Sha256::digest(destination.as_os_str().as_encoded_bytes())); + destination.with_file_name(format!(".strata-kar-{key}-{slot}.part")) +} + +fn reap_stale_archive_temps(destination: &Path) -> Result<(), String> { + let destination = private_archive_destination(destination)?; + #[cfg(unix)] + { + let parent = destination.parent().unwrap_or_else(|| Path::new(".")); + for entry in fs::read_dir(parent).map_err(|error| error.to_string())? { + reap_archive_temp_entry(&destination, entry.map_err(|error| error.to_string())?)?; + } + } + #[cfg(not(unix))] + let _ = &destination; + Ok(()) +} + +#[cfg(unix)] +fn reap_archive_temp_entry(destination: &Path, entry: fs::DirEntry) -> Result<(), String> { + if !is_archive_temp_name(destination, &entry.file_name()) { + return Ok(()); + } + reap_archive_temp(&entry.path(), destination) +} + +#[cfg(unix)] +fn is_archive_temp_name(destination: &Path, name: &std::ffi::OsStr) -> bool { + let destination = + private_archive_destination(destination).unwrap_or_else(|_| destination.to_path_buf()); + let key = hex::encode(Sha256::digest(destination.as_os_str().as_encoded_bytes())); + let prefix = format!(".strata-kar-{key}-"); + let Some(suffix) = name.to_str().and_then(|name| name.strip_prefix(&prefix)) else { + return false; + }; + let Some(slot) = suffix.strip_suffix(".part") else { + return false; + }; + slot.parse::() + .is_ok_and(|slot| slot < ARCHIVE_TEMP_SLOTS) +} + +#[cfg(unix)] +fn reap_archive_temp(path: &Path, destination: &Path) -> Result<(), String> { + let (path, destination) = private_archive_pair(path, destination)?; + let before = match fs::symlink_metadata(&path) { + Ok(meta) + if meta.file_type().is_file() + && (meta.nlink() == 1 || is_published_temp(&meta, &destination)) => + { + meta + } + _ => return Ok(()), + }; + if before.uid() != unsafe { libc::geteuid() } { + return Ok(()); + } + let mut options = OpenOptions::new(); + options + .read(true) .write(true) - .create_new(true) - .open(&temporary) - .map_err(|error| error.to_string())?; - let result = (|| -> Result<(), String> { - file.set_len(payload_offset) - .map_err(|error| error.to_string())?; - file.seek(SeekFrom::Start(string_offset)) - .map_err(|error| error.to_string())?; - file.write_all(&names).map_err(|error| error.to_string())?; - for entry in &mut placed { - entry.payload_crc32 = write_section(&mut file, entry)?; - if consume_files { - let path = match &entry.tensor.data { - TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path, - _ => unreachable!(), - }; - fs::remove_file(path).map_err(|error| error.to_string())?; - } - } - if file.metadata().map_err(|error| error.to_string())?.len() != archive_bytes { - return Err("KAR writer produced the wrong archive length".into()); - } - let mut directory = vec![0u8; directory_bytes as usize]; - let (records, remainder) = directory.as_chunks_mut::<192>(); - debug_assert!(remainder.is_empty()); - for (entry, record) in placed.iter().zip(records) { - write_record(record, entry)?; - } - file.seek(SeekFrom::Start(directory_offset)) - .map_err(|error| error.to_string())?; - file.write_all(&directory) - .map_err(|error| error.to_string())?; - let mut digest = Sha256::new(); - digest.update(&names); - digest.update(&directory); - let mut header = [0u8; 256]; - header[..8].copy_from_slice(b"KARCHIV2"); - put_u32(&mut header, 8, 2); - put_u32(&mut header, 12, 0x0403_0201); - put_u32(&mut header, 16, 256); - put_u32(&mut header, 20, 192); - put_u64(&mut header, 24, directory_offset); - put_u32(&mut header, 32, tensors.len() as u32); - put_u64(&mut header, 40, string_offset); - put_u64(&mut header, 48, names.len() as u64); - put_u64(&mut header, 56, payload_offset); - put_u64(&mut header, 64, archive_bytes); - put_u64(&mut header, 72, total_elements); - put_u64(&mut header, 80, payload_bits); - put_u64(&mut header, 88, source.total_elements); - header[96..104] - .copy_from_slice(&(archive_bytes as f64 * 8.0 / total_elements as f64).to_le_bytes()); - header[104] = if min_planes == u8::MAX { 0 } else { min_planes }; - header[105] = max_planes; - header[106] = 1; - put_u32(&mut header, 108, source_name); - put_u32(&mut header, 112, source_arch); - put_u32(&mut header, 116, builder_name); - put_u64(&mut header, 120, source.bytes); - header[128..160].copy_from_slice(&source.digest); - header[160..192].copy_from_slice(&digest.finalize()); - let header_crc = kar::crc32(&header[..192]); - put_u32(&mut header, 192, header_crc); - file.seek(SeekFrom::Start(0)) - .map_err(|error| error.to_string())?; - file.write_all(&header).map_err(|error| error.to_string())?; - file.sync_all().map_err(|error| error.to_string())?; + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + reap_locked_archive_temp(&path, &destination, &before, options) +} + +#[cfg(unix)] +fn reap_locked_archive_temp( + path: &Path, + destination: &Path, + before: &fs::Metadata, + options: OpenOptions, +) -> Result<(), String> { + let file = match options.open(path) { + Ok(file) => file, + Err(error) => return handle_reap_archive_temp_open_error(error), + }; + finish_reap_archive_temp_lock(path, destination, before, &file, file.try_lock()) +} + +#[cfg(unix)] +fn handle_reap_archive_temp_open_error(error: io::Error) -> Result<(), String> { + if error.kind() == io::ErrorKind::NotFound { Ok(()) - })(); - drop(file); - if let Err(error) = result { - let _ = fs::remove_file(&temporary); - return Err(error); + } else { + Err(error.to_string()) } +} + +#[cfg(unix)] +fn finish_reap_archive_temp_lock( + path: &Path, + destination: &Path, + before: &fs::Metadata, + file: &File, + result: Result<(), std::fs::TryLockError>, +) -> Result<(), String> { + match result { + Ok(()) => unlink_if_same_archive_temp(path, destination, before, file), + Err(std::fs::TryLockError::WouldBlock) => Ok(()), + Err(error) => Err(error.to_string()), + } +} + +#[cfg(unix)] +fn unlink_if_same_archive_temp( + path: &Path, + destination: &Path, + before: &fs::Metadata, + file: &File, +) -> Result<(), String> { + unlink_if_same_archive_temp_with( + path, + destination, + before, + file, + ArchiveTempPathOps::system(), + ) +} + +#[cfg(unix)] +#[derive(Clone, Copy)] +struct ArchiveTempPathOps { + metadata: fn(&Path) -> io::Result, + remove: fn(&Path) -> io::Result<()>, +} + +#[cfg(unix)] +impl ArchiveTempPathOps { + fn system() -> Self { + Self { + metadata: archive_temp_symlink_metadata, + remove: archive_temp_remove_file, + } + } +} + +#[cfg(unix)] +fn archive_temp_symlink_metadata(path: &Path) -> io::Result { + fs::symlink_metadata(path) +} + +#[cfg(unix)] +fn archive_temp_remove_file(path: &Path) -> io::Result<()> { + fs::remove_file(path) +} + +#[cfg(unix)] +fn unlink_if_same_archive_temp_with( + path: &Path, + destination: &Path, + before: &fs::Metadata, + file: &File, + operations: ArchiveTempPathOps, +) -> Result<(), String> { + let (path, destination) = private_archive_pair(path, destination)?; + let opened = file.metadata().map_err(|error| error.to_string())?; + let current = match (operations.metadata)(&path) { + Ok(meta) => meta, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.to_string()), + }; + if !same_inode(before, &opened) || !same_inode(before, ¤t) { + return Ok(()); + } + if current.nlink() != 1 && !is_published_temp_with(¤t, &destination, operations) { + return Ok(()); + } + (operations.remove)(&path).map_err(|error| error.to_string()) +} + +#[cfg(unix)] +fn is_published_temp(temporary: &fs::Metadata, destination: &Path) -> bool { + is_published_temp_with(temporary, destination, ArchiveTempPathOps::system()) +} + +#[cfg(unix)] +fn is_published_temp_with( + temporary: &fs::Metadata, + destination: &Path, + operations: ArchiveTempPathOps, +) -> bool { + (operations.metadata)(destination) + .is_ok_and(|published| same_inode(temporary, &published) && temporary.nlink() == 2) +} + +#[cfg(unix)] +fn same_inode(left: &fs::Metadata, right: &fs::Metadata) -> bool { + left.dev() == right.dev() && left.ino() == right.ino() +} + +fn verify_and_publish( + temporary: &Path, + destination: &Path, + cleanup: fn(&Path) -> Result<(), String>, +) -> Result { + let (temporary, destination) = private_archive_pair(temporary, destination)?; let summary = match kar::verify(&temporary) { Ok(summary) => summary, Err(error) => { @@ -369,32 +589,582 @@ fn write_archive_inner( return Err(error); } }; - publish_verified_archive(&temporary, destination, summary, remove_archive_temp) + publish_verified_archive(&temporary, &destination, summary, cleanup) } -fn archive_temporary_path(destination: &Path) -> Result { - let name = destination - .file_name() - .ok_or("KAR destination has no filename")? - .to_string_lossy(); - Ok(destination.with_file_name(format!("{name}.part"))) +struct ArchiveNames { + bytes: Vec, + tensor_offsets: Vec, + source: u32, + architecture: u32, + builder: u32, +} + +impl ArchiveNames { + fn build(source: &SourceIdentity<'_>, tensors: &[Tensor<'_>]) -> Result { + let mut bytes = Vec::new(); + let mut tensor_offsets = Vec::with_capacity(tensors.len()); + let mut unique = HashSet::new(); + for tensor in tensors { + if tensor.name.is_empty() || !unique.insert(tensor.name) { + return Err("KAR tensor names must be nonempty and unique".into()); + } + tensor_offsets.push(append_name(&mut bytes, tensor.name)?); + } + let source_offset = append_name(&mut bytes, source.name)?; + let architecture = append_name(&mut bytes, source.architecture)?; + let builder = append_name(&mut bytes, source.builder)?; + if bytes.len() > 64 * 1024 * 1024 { + return Err("KAR string table exceeds inspector limit".into()); + } + Ok(Self { + bytes, + tensor_offsets, + source: source_offset, + architecture, + builder, + }) + } +} + +fn append_name(bytes: &mut Vec, name: &str) -> Result { + let offset = u32::try_from(bytes.len()).map_err(|_| "KAR string table is too large")?; + push_cstr(bytes, name)?; + Ok(offset) +} + +struct ArchivePlan<'a> { + names: ArchiveNames, + placed: Vec>, + directory_offset: u64, + directory_bytes: u64, + string_offset: u64, + payload_offset: u64, + archive_bytes: u64, + total_elements: u64, + payload_bits: u64, + min_planes: u8, + max_planes: u8, +} + +struct Placement { + padded: u64, + bytes: u64, + scales: u64, + books: u64, + planes: u64, + stride: u32, + payload_bits: u64, + min_planes: u8, + max_planes: u8, +} + +#[derive(Clone, Copy)] +struct PlacementRequest<'a> { + tensor: &'a Tensor<'a>, + elements: u64, + cursor: u64, +} + +struct NestedMemoryPlacement<'a> { + request: PlacementRequest<'a>, + group: u16, + nesting: u8, + min: u8, + max: u8, + scales: &'a [u16], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], +} + +struct NestedFilePlacement<'a> { + request: PlacementRequest<'a>, + group: u16, + nesting: u8, + min: u8, + max: u8, + levels: u8, + bytes: u64, +} + +struct ArchiveOffsets { + directory: u64, + directory_bytes: u64, + strings: u64, + payload: u64, +} + +struct PlacementList<'a> { + entries: Vec>, + cursor: u64, + total_elements: u64, + payload_bits: u64, + min_planes: u8, + max_planes: u8, +} + +impl<'a> PlacementList<'a> { + fn build(tensors: &'a [Tensor<'a>], names: &[u32], start: u64) -> Result { + let mut list = Self { + entries: Vec::with_capacity(tensors.len()), + cursor: start, + total_elements: 0, + payload_bits: 0, + min_planes: u8::MAX, + max_planes: 0, + }; + for (tensor, &name_offset) in tensors.iter().zip(names) { + list.push(tensor, name_offset)?; + } + Ok(list) + } + + fn push(&mut self, tensor: &'a Tensor<'a>, name_offset: u32) -> Result<(), String> { + let elements = validate_shape(tensor)?; + self.total_elements = self + .total_elements + .checked_add(elements) + .ok_or("KAR element count overflow")?; + let layout = placement_for_tensor(PlacementRequest { + tensor, + elements, + cursor: self.cursor, + })?; + self.update_totals(&layout)?; + let section_bytes = layout.bytes; + self.entries.push(placed_tensor( + tensor, + name_offset, + elements, + self.cursor, + layout, + )); + self.cursor = self + .cursor + .checked_add(section_bytes) + .ok_or("KAR archive size overflow")?; + Ok(()) + } + + fn update_totals(&mut self, layout: &Placement) -> Result<(), String> { + self.payload_bits = self + .payload_bits + .checked_add(layout.payload_bits) + .ok_or("KAR payload bit count overflow")?; + if layout.min_planes != u8::MAX { + self.min_planes = self.min_planes.min(layout.min_planes); + } + self.max_planes = self.max_planes.max(layout.max_planes); + Ok(()) + } +} + +fn placed_tensor<'a>( + tensor: &'a Tensor<'a>, + name: u32, + elements: u64, + offset: u64, + layout: Placement, +) -> Placed<'a> { + Placed { + tensor, + name_offset: name, + n_elements: elements, + n_padded: layout.padded, + section_offset: offset, + section_bytes: layout.bytes, + scales_offset: layout.scales, + books_offset: layout.books, + planes_offset: layout.planes, + plane_stride: layout.stride, + payload_crc32: 0, + } +} + +fn placement_for_tensor(request: PlacementRequest<'_>) -> Result { + match &request.tensor.data { + TensorData::Raw(raw) => raw_placement(&request, raw.len() as u64), + TensorData::RawFile { bytes, .. } => raw_placement(&request, *bytes), + data => nested_placement(request, data), + } +} + +fn nested_placement( + request: PlacementRequest<'_>, + data: &TensorData<'_>, +) -> Result { + match data { + TensorData::Nested { .. } => { + nested_memory_placement(memory_placement_request(request, data)?) + } + TensorData::NestedFile { .. } => { + nested_file_placement(file_placement_request(request, data)?) + } + _ => unreachable!("raw tensor data was dispatched separately"), + } +} + +fn memory_placement_request<'a>( + request: PlacementRequest<'a>, + data: &'a TensorData<'a>, +) -> Result, String> { + let TensorData::Nested { + group, + nesting, + planes_min, + planes_max, + scales, + books, + planes, + } = data + else { + return Err("expected in-memory NESTED tensor".into()); + }; + Ok(NestedMemoryPlacement { + request, + group: *group, + nesting: *nesting, + min: *planes_min, + max: *planes_max, + scales, + books, + planes, + }) +} + +fn file_placement_request<'a>( + request: PlacementRequest<'a>, + data: &'a TensorData<'a>, +) -> Result, String> { + let TensorData::NestedFile { + group, + nesting, + planes_min, + planes_max, + levels, + bytes, + .. + } = data + else { + return Err("expected file-backed NESTED tensor".into()); + }; + Ok(NestedFilePlacement { + request, + group: *group, + nesting: *nesting, + min: *planes_min, + max: *planes_max, + levels: *levels, + bytes: *bytes, + }) +} + +fn raw_placement(request: &PlacementRequest<'_>, bytes: u64) -> Result { + let width = if request.tensor.source_dtype == 0 { + 4 + } else { + 2 + }; + if bytes + != request + .elements + .checked_mul(width) + .ok_or("KAR RAW byte count overflow")? + { + return Err(format!( + "{}: RAW byte count differs from tensor shape", + request.tensor.name + )); + } + Ok(Placement { + padded: request.elements, + bytes: round_up(bytes, 256)?, + scales: 0, + books: 0, + planes: 0, + stride: 0, + payload_bits: 0, + min_planes: u8::MAX, + max_planes: 0, + }) +} + +fn nested_memory_placement(request: NestedMemoryPlacement<'_>) -> Result { + let levels = u8::try_from(request.planes.len()).map_err(|_| "too many KAR planes")?; + let layout = nested_layout(NestedLayoutRequest { + cursor: request.request.cursor, + n_elements: request.request.elements, + group: request.group, + nesting: request.nesting, + planes_min: request.min, + planes_max: request.max, + levels, + })?; + validate_nested_slices(NestedSliceValidation { + name: request.request.tensor.name, + layout: &layout, + group: request.group, + scales: request.scales, + books: request.books, + planes: request.planes, + })?; + Ok(placement_from_nested(layout, request.min, request.max)) +} + +fn nested_file_placement(request: NestedFilePlacement<'_>) -> Result { + let layout = nested_layout(NestedLayoutRequest { + cursor: request.request.cursor, + n_elements: request.request.elements, + group: request.group, + nesting: request.nesting, + planes_min: request.min, + planes_max: request.max, + levels: request.levels, + })?; + if request.bytes != layout.section_bytes { + return Err(format!( + "{}: nested file section size mismatch", + request.request.tensor.name + )); + } + Ok(placement_from_nested(layout, request.min, request.max)) +} + +fn placement_from_nested(layout: NestedLayout, min: u8, max: u8) -> Placement { + Placement { + padded: layout.n_padded, + bytes: layout.section_bytes, + scales: layout.scales_offset, + books: layout.books_offset, + planes: layout.planes_offset, + stride: layout.plane_stride, + payload_bits: layout.payload_bits, + min_planes: min, + max_planes: max, + } +} + +impl<'a> ArchivePlan<'a> { + fn build(source: &SourceIdentity<'_>, tensors: &'a [Tensor<'a>]) -> Result { + let names = ArchiveNames::build(source, tensors)?; + let directory_offset = 256; + let directory_bytes = (tensors.len() as u64) + .checked_mul(192) + .ok_or("KAR directory overflow")?; + let string_offset = round_up(directory_offset + directory_bytes, 64)?; + let payload_offset = round_up(string_offset + names.bytes.len() as u64, 256)?; + Self::finish( + source, + tensors, + names, + ArchiveOffsets { + directory: directory_offset, + directory_bytes, + strings: string_offset, + payload: payload_offset, + }, + ) + } + + fn finish( + source: &SourceIdentity<'_>, + tensors: &'a [Tensor<'a>], + names: ArchiveNames, + offsets: ArchiveOffsets, + ) -> Result { + let placement = PlacementList::build(tensors, &names.tensor_offsets, offsets.payload)?; + if placement.total_elements > source.total_elements { + return Err("KAR tensors exceed source element count".into()); + } + Ok(Self { + names, + placed: placement.entries, + directory_offset: offsets.directory, + directory_bytes: offsets.directory_bytes, + string_offset: offsets.strings, + payload_offset: offsets.payload, + archive_bytes: placement.cursor, + total_elements: placement.total_elements, + payload_bits: placement.payload_bits, + min_planes: placement.min_planes, + max_planes: placement.max_planes, + }) + } + + fn write( + &mut self, + file: &mut W, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], + consume: bool, + ) -> Result<(), String> { + file.set_archive_len(self.payload_offset) + .map_err(|error| error.to_string())?; + file.seek_archive(SeekFrom::Start(self.string_offset)) + .map_err(|error| error.to_string())?; + file.write_archive_all(&self.names.bytes) + .map_err(|error| error.to_string())?; + write_payloads(file, &mut self.placed, self.archive_bytes, consume)?; + let directory = archive_directory(&self.placed, self.directory_bytes)?; + write_archive_header(file, source, tensors.len(), self, &directory) + } +} + +fn write_payloads( + file: &mut W, + entries: &mut [Placed<'_>], + expected_bytes: u64, + consume: bool, +) -> Result<(), String> { + for entry in entries { + entry.payload_crc32 = write_section(file, entry)?; + if consume { + remove_staged_tensor(entry)?; + } + } + if file.archive_len().map_err(|error| error.to_string())? != expected_bytes { + return Err("KAR writer produced the wrong archive length".into()); + } + Ok(()) +} + +fn remove_staged_tensor(entry: &Placed<'_>) -> Result<(), String> { + let path = match &entry.tensor.data { + TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path, + _ => unreachable!(), + }; + fs::remove_file(path).map_err(|error| error.to_string()) +} + +fn archive_directory(entries: &[Placed<'_>], bytes: u64) -> Result, String> { + let mut directory = vec![0u8; bytes as usize]; + let (records, remainder) = directory.as_chunks_mut::<192>(); + debug_assert!(remainder.is_empty()); + for (entry, record) in entries.iter().zip(records) { + write_record(record, entry)?; + } + Ok(directory) +} + +fn write_archive_header( + file: &mut W, + source: &SourceIdentity<'_>, + count: usize, + plan: &ArchivePlan<'_>, + directory: &[u8], +) -> Result<(), String> { + file.seek_archive(SeekFrom::Start(plan.directory_offset)) + .map_err(|error| error.to_string())?; + file.write_archive_all(directory) + .map_err(|error| error.to_string())?; + let digest = archive_directory_digest(&plan.names.bytes, directory); + let header = archive_header(source, count, plan, digest); + file.seek_archive(SeekFrom::Start(0)) + .map_err(|error| error.to_string())?; + file.write_archive_all(&header) + .map_err(|error| error.to_string())?; + file.sync_archive().map_err(|error| error.to_string()) +} + +fn archive_directory_digest(names: &[u8], directory: &[u8]) -> [u8; 32] { + let mut digest = Sha256::new(); + digest.update(names); + digest.update(directory); + digest.finalize().into() +} + +fn archive_header( + source: &SourceIdentity<'_>, + count: usize, + plan: &ArchivePlan<'_>, + digest: [u8; 32], +) -> [u8; 256] { + let mut header = [0u8; 256]; + write_header_counts(&mut header, source, count, plan); + write_header_names(&mut header, plan); + header[160..192].copy_from_slice(&digest); + let crc = kar::crc32(&header[..192]); + put_u32(&mut header, 192, crc); + header +} + +fn write_header_counts( + header: &mut [u8; 256], + source: &SourceIdentity<'_>, + count: usize, + plan: &ArchivePlan<'_>, +) { + header[..8].copy_from_slice(b"KARCHIV2"); + put_u32(header, 8, 2); + put_u32(header, 12, 0x0403_0201); + put_u32(header, 16, 256); + put_u32(header, 20, 192); + put_u64(header, 24, plan.directory_offset); + put_u32(header, 32, count as u32); + put_u64(header, 40, plan.string_offset); + put_u64(header, 48, plan.names.bytes.len() as u64); + put_u64(header, 56, plan.payload_offset); + put_u64(header, 64, plan.archive_bytes); + put_u64(header, 72, plan.total_elements); + put_u64(header, 80, plan.payload_bits); + put_u64(header, 88, source.total_elements); + write_header_rates(header, source, plan); +} + +fn write_header_rates(header: &mut [u8; 256], source: &SourceIdentity<'_>, plan: &ArchivePlan<'_>) { + let bits_per_element = plan.archive_bytes as f64 * 8.0 / plan.total_elements as f64; + header[96..104].copy_from_slice(&bits_per_element.to_le_bytes()); + header[104] = if plan.min_planes == u8::MAX { + 0 + } else { + plan.min_planes + }; + header[105] = plan.max_planes; + header[106] = 1; + put_u64(header, 120, source.bytes); + header[128..160].copy_from_slice(&source.digest); +} + +fn write_header_names(header: &mut [u8; 256], plan: &ArchivePlan<'_>) { + put_u32(header, 108, plan.names.source); + put_u32(header, 112, plan.names.architecture); + put_u32(header, 116, plan.names.builder); } fn remove_archive_temp(path: &Path) -> Result<(), String> { + let path = private_archive_destination(path)?; + #[cfg(test)] + if consume_archive_cleanup_failure() { + return Err("injected temporary cleanup failure".into()); + } fs::remove_file(path).map_err(|error| error.to_string()) } +#[cfg(test)] +fn consume_archive_cleanup_failure() -> bool { + ARCHIVE_CLEANUP_FAILURES.with(|failures| { + let count = failures.get(); + failures.set(count.saturating_sub(1)); + count > 0 + }) +} + fn publish_verified_archive( temporary: &Path, destination: &Path, summary: kar::Summary, cleanup: fn(&Path) -> Result<(), String>, ) -> Result { - if let Err(error) = fs::hard_link(temporary, destination) { - let _ = cleanup(temporary); + let (temporary, destination) = private_archive_pair(temporary, destination)?; + if let Err(error) = fs::hard_link(&temporary, &destination) { + let _ = cleanup(&temporary); return Err(error.to_string()); } - cleanup(temporary)?; + for _ in 0..2 { + if cleanup(&temporary).is_ok() { + break; + } + } Ok(summary) } @@ -409,7 +1179,73 @@ pub fn write_nested_section( destination: &Path, tensor: &Tensor<'_>, ) -> Result { - let n_elements = validate_shape(tensor)?; + write_nested_section_with_verifier(destination, tensor, verify_nested_spool) +} + +fn write_nested_section_with_verifier( + destination: &Path, + tensor: &Tensor<'_>, + verify: fn(&Path, &NestedSectionPlan<'_>) -> Result, +) -> Result { + let plan = NestedSectionPlan::new(tensor)?; + write_nested_spool(destination, &plan)?; + let verified = verify(destination, &plan); + if verified.is_err() { + let _ = fs::remove_file(destination); + } + verified +} + +struct NestedSectionPlan<'a> { + entry: Placed<'a>, + layout: NestedLayout, + group: u16, + levels: u8, +} + +impl<'a> NestedSectionPlan<'a> { + fn new(tensor: &'a Tensor<'a>) -> Result { + let n_elements = validate_shape(tensor)?; + let nested = nested_slices(tensor)?; + let levels = u8::try_from(nested.planes.len()).map_err(|_| "too many KAR planes")?; + let layout = nested_layout(NestedLayoutRequest { + cursor: 0, + n_elements, + group: nested.group, + nesting: nested.nesting, + planes_min: nested.min, + planes_max: nested.max, + levels, + })?; + validate_nested_slices(NestedSliceValidation { + name: tensor.name, + layout: &layout, + group: nested.group, + scales: nested.scales, + books: nested.books, + planes: nested.planes, + })?; + let entry = placed_nested_tensor(tensor, n_elements, &layout); + Ok(Self { + entry, + layout, + group: nested.group, + levels, + }) + } +} + +struct NestedSlices<'a> { + group: u16, + nesting: u8, + min: u8, + max: u8, + scales: &'a [u16], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], +} + +fn nested_slices<'a>(tensor: &'a Tensor<'a>) -> Result, String> { let TensorData::Nested { group, nesting, @@ -422,18 +1258,23 @@ pub fn write_nested_section( else { return Err("KAR section spool requires in-memory NESTED tensor".into()); }; - let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?; - let layout = nested_layout( - 0, - n_elements, - *group, - *nesting, - *planes_min, - *planes_max, - levels, - )?; - validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?; - let entry = Placed { + Ok(NestedSlices { + group: *group, + nesting: *nesting, + min: *planes_min, + max: *planes_max, + scales, + books, + planes, + }) +} + +fn placed_nested_tensor<'a>( + tensor: &'a Tensor<'a>, + n_elements: u64, + layout: &NestedLayout, +) -> Placed<'a> { + Placed { tensor, name_offset: 0, n_elements, @@ -445,48 +1286,78 @@ pub fn write_nested_section( planes_offset: layout.planes_offset, plane_stride: layout.plane_stride, payload_crc32: 0, - }; + } +} + +fn write_nested_spool(destination: &Path, plan: &NestedSectionPlan<'_>) -> Result<(), String> { let mut output = OpenOptions::new() .write(true) .create_new(true) .open(destination) .map_err(|error| error.to_string())?; - let result = (|| -> Result<(), String> { - write_section(&mut output, &entry)?; - if output.metadata().map_err(|error| error.to_string())?.len() != layout.section_bytes { - return Err("KAR section spool size mismatch".into()); - } - output.sync_all().map_err(|error| error.to_string())?; - Ok(()) - })(); + let result = write_nested_spool_output(&mut output, plan); drop(output); if let Err(error) = result { let _ = fs::remove_file(destination); return Err(error); } - let verified = (|| -> Result { - let mut file = File::open(destination).map_err(|error| error.to_string())?; - validate_nested_file(&mut file, &entry, 0, *group, levels)?; - file.seek(SeekFrom::Start(0)) - .map_err(|error| error.to_string())?; - let mut digest = Sha256::new(); - let mut buffer = [0u8; 1024 * 1024]; - loop { - let count = file.read(&mut buffer).map_err(|error| error.to_string())?; - if count == 0 { - break; - } - digest.update(&buffer[..count]); - } - Ok(SectionSummary { - bytes: layout.section_bytes, - digest: digest.finalize().into(), - }) - })(); - if verified.is_err() { - let _ = fs::remove_file(destination); + Ok(()) +} + +fn write_nested_spool_output( + output: &mut impl ArchiveOutput, + plan: &NestedSectionPlan<'_>, +) -> Result<(), String> { + write_section(output, &plan.entry)?; + if output.archive_len().map_err(|error| error.to_string())? != plan.layout.section_bytes { + return Err("KAR section spool size mismatch".into()); } - verified + output.sync_archive().map_err(|error| error.to_string()) +} + +fn verify_nested_spool( + destination: &Path, + plan: &NestedSectionPlan<'_>, +) -> Result { + let mut file = File::open(destination).map_err(|error| error.to_string())?; + verify_nested_spool_reader(&mut file, plan) +} + +fn verify_nested_spool_reader( + file: &mut R, + plan: &NestedSectionPlan<'_>, +) -> Result { + validate_nested_file( + file, + NestedValidation { + entry: &plan.entry, + source_offset: 0, + group: plan.group, + levels: plan.levels, + }, + )?; + file.seek(SeekFrom::Start(0)) + .map_err(|error| error.to_string())?; + let digest = hash_reader(file)?; + Ok(SectionSummary { + bytes: plan.layout.section_bytes, + digest, + }) +} + +fn hash_reader(reader: &mut R) -> Result<[u8; 32], String> { + let mut digest = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = reader + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + Ok(digest.finalize().into()) } fn validate_shape(tensor: &Tensor<'_>) -> Result { @@ -507,14 +1378,24 @@ fn validate_shape(tensor: &Tensor<'_>) -> Result { Ok(n) } -fn validate_nested_slices( - name: &str, - layout: &NestedLayout, +struct NestedSliceValidation<'a> { + name: &'a str, + layout: &'a NestedLayout, group: u16, - scales: &[u16], - books: &[&[u16]], - planes: &[&[u32]], -) -> Result<(), String> { + scales: &'a [u16], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], +} + +fn validate_nested_slices(request: NestedSliceValidation<'_>) -> Result<(), String> { + let NestedSliceValidation { + name, + layout, + group, + scales, + books, + planes, + } = request; if books.len() != planes.len() { return Err(format!("{name}: level book count mismatch")); } @@ -524,6 +1405,17 @@ fn validate_nested_slices( if scales.iter().any(|bits| bits & 0x7c00 == 0x7c00) { return Err(format!("{name}: non-finite f16 scale")); } + validate_nested_books(name, books)?; + if planes + .iter() + .any(|plane| plane.len() as u64 != layout.n_padded / 32) + { + return Err(format!("{name}: plane word count mismatch")); + } + Ok(()) +} + +fn validate_nested_books(name: &str, books: &[&[u16]]) -> Result<(), String> { for (index, book) in books.iter().enumerate() { if book.len() != 1usize << (index + 1) { return Err(format!("{name}: level book size mismatch")); @@ -532,12 +1424,6 @@ fn validate_nested_slices( return Err(format!("{name}: non-finite f16 codebook")); } } - if planes - .iter() - .any(|plane| plane.len() as u64 != layout.n_padded / 32) - { - return Err(format!("{name}: plane word count mismatch")); - } Ok(()) } @@ -557,7 +1443,8 @@ fn round_up(value: u64, alignment: u64) -> Result { .ok_or("KAR aligned offset overflow".into()) } -fn nested_layout( +#[derive(Clone, Copy)] +struct NestedLayoutRequest { cursor: u64, n_elements: u64, group: u16, @@ -565,7 +1452,59 @@ fn nested_layout( planes_min: u8, planes_max: u8, levels: u8, +} + +fn nested_layout(request: NestedLayoutRequest) -> Result { + let NestedLayoutRequest { + cursor, + n_elements, + group, + nesting, + planes_min, + planes_max, + levels, + } = request; + let group = validate_nested_parameters(group, nesting, planes_min, planes_max, levels)?; + let n_padded = padded_nested_elements(n_elements, group)?; + let groups = n_padded / group; + let words = n_padded / 32; + let offsets = nested_layout_offsets(cursor, groups, words, levels)?; + finish_nested_layout(cursor, n_padded, groups, levels, offsets) +} + +fn finish_nested_layout( + cursor: u64, + n_padded: u64, + groups: u64, + levels: u8, + offsets: NestedOffsets, ) -> Result { + let section_bytes = round_up( + offsets + .end + .checked_sub(cursor) + .ok_or("KAR section offset underflow")?, + 256, + )?; + let payload_bits = nested_payload_bits(levels, n_padded, groups)?; + Ok(NestedLayout { + n_padded, + section_bytes, + scales_offset: cursor, + books_offset: offsets.books, + planes_offset: offsets.planes, + plane_stride: offsets.stride, + payload_bits, + }) +} + +fn validate_nested_parameters( + group: u16, + nesting: u8, + planes_min: u8, + planes_max: u8, + levels: u8, +) -> Result { let group = u64::from(group); if group == 0 || group > 1024 @@ -578,176 +1517,339 @@ fn nested_layout( { return Err("invalid nested KAR parameters".into()); } - let n_padded = n_elements + Ok(group) +} + +fn padded_nested_elements(elements: u64, group: u64) -> Result { + elements .div_ceil(group) .checked_mul(group) - .ok_or("KAR padded size overflow")?; - let groups = n_padded / group; - let words = n_padded / 32; + .ok_or("KAR padded size overflow".into()) +} + +struct NestedOffsets { + books: u64, + planes: u64, + stride: u32, + end: u64, +} + +fn nested_layout_offsets( + cursor: u64, + groups: u64, + words: u64, + levels: u8, +) -> Result { let scales_bytes = groups.checked_mul(2).ok_or("KAR scales overflow")?; - let books_offset = round_up( + let books_offset = nested_books_offset(cursor, scales_bytes)?; + let planes_offset = nested_planes_offset(books_offset, levels)?; + let stride = nested_stride(words)?; + let end = nested_planes_end(planes_offset, stride, levels)?; + Ok(NestedOffsets { + books: books_offset, + planes: planes_offset, + stride: u32::try_from(stride).map_err(|_| "KAR plane stride exceeds u32")?, + end, + }) +} + +fn nested_books_offset(cursor: u64, scales_bytes: u64) -> Result { + round_up( cursor .checked_add(scales_bytes) .ok_or("KAR scales overflow")?, 16, - )?; + ) +} + +fn nested_planes_offset(books_offset: u64, levels: u8) -> Result { let book_bytes = (1u64 << (levels as u32 + 2)) - 4; - let planes_offset = round_up( + round_up( books_offset .checked_add(book_bytes) .ok_or("KAR books overflow")?, 16, - )?; - let stride = round_up(words.checked_mul(4).ok_or("KAR plane size overflow")?, 16)?; - let plane_stride = u32::try_from(stride).map_err(|_| "KAR plane stride exceeds u32")?; - let end = planes_offset + ) +} + +fn nested_stride(words: u64) -> Result { + round_up(words.checked_mul(4).ok_or("KAR plane size overflow")?, 16) +} + +fn nested_planes_end(planes_offset: u64, stride: u64, levels: u8) -> Result { + planes_offset .checked_add( (levels as u64) .checked_mul(stride) .ok_or("KAR planes overflow")?, ) - .ok_or("KAR planes overflow")?; - let section_bytes = round_up( - end.checked_sub(cursor) - .ok_or("KAR section offset underflow")?, - 256, - )?; + .ok_or("KAR planes overflow".into()) +} + +fn nested_payload_bits(levels: u8, n_padded: u64, groups: u64) -> Result { let payload_bits = (levels as u64) .checked_mul(n_padded) .and_then(|value| value.checked_add(groups.checked_mul(16)?)) .ok_or("KAR payload bit count overflow")?; - Ok(NestedLayout { - n_padded, - section_bytes, - scales_offset: cursor, - books_offset, - planes_offset, - plane_stride, - payload_bits, - }) + Ok(payload_bits) } -fn write_section(file: &mut File, entry: &Placed<'_>) -> Result { - file.seek(SeekFrom::Start(entry.section_offset)) +fn write_section(file: &mut W, entry: &Placed<'_>) -> Result { + file.seek_archive(SeekFrom::Start(entry.section_offset)) .map_err(|error| error.to_string())?; - let mut crc = !0u32; - let mut written = 0u64; + let mut state = SectionWriteState::new(file); + write_section_payload(&mut state, entry)?; + state.pad(entry.section_bytes)?; + Ok(!state.crc) +} + +struct SectionWriteState<'a> { + file: &'a mut dyn ArchiveOutput, + crc: u32, + written: u64, +} + +impl<'a> SectionWriteState<'a> { + fn new(file: &'a mut dyn ArchiveOutput) -> Self { + Self { + file, + crc: !0u32, + written: 0, + } + } + + fn bytes(&mut self, bytes: &[u8]) -> Result<(), String> { + write_bytes(self.file, bytes, &mut self.crc, &mut self.written) + } + + fn pad(&mut self, target: u64) -> Result<(), String> { + pad_to(self.file, target, &mut self.crc, &mut self.written) + } +} + +fn write_section_payload( + state: &mut SectionWriteState<'_>, + entry: &Placed<'_>, +) -> Result<(), String> { match &entry.tensor.data { - TensorData::Raw(raw) => write_bytes(file, raw, &mut crc, &mut written)?, - TensorData::RawFile { + TensorData::Raw(raw) => state.bytes(raw), + TensorData::RawFile { .. } => write_raw_file_payload(state, entry), + TensorData::NestedFile { .. } => write_nested_file_payload(state, entry), + TensorData::Nested { .. } => write_nested_memory_payload(state, entry), + } +} + +fn write_raw_file_payload( + state: &mut SectionWriteState<'_>, + entry: &Placed<'_>, +) -> Result<(), String> { + let TensorData::RawFile { + path, + offset, + bytes, + } = &entry.tensor.data + else { + unreachable!("raw file data was dispatched by variant"); + }; + copy_raw_file( + state, + RawFileCopy { path, - offset, - bytes, - } => { - let mut source = File::open(path).map_err(|error| error.to_string())?; - let source_len = source.metadata().map_err(|error| error.to_string())?.len(); - if offset - .checked_add(*bytes) - .is_none_or(|end| end > source_len) - { - return Err("KAR RAW source file is truncated".into()); - } - source - .seek(SeekFrom::Start(*offset)) - .map_err(|error| error.to_string())?; - let mut remaining = *bytes; - let mut buffer = vec![0u8; 1024 * 1024]; - let mut digest = Sha256::new(); - while remaining > 0 { - let count = remaining.min(buffer.len() as u64) as usize; - source - .read_exact(&mut buffer[..count]) - .map_err(|error| error.to_string())?; - digest.update(&buffer[..count]); - write_bytes(file, &buffer[..count], &mut crc, &mut written)?; - remaining -= count as u64; - } - if digest.finalize().as_slice() != entry.tensor.source_digest { - return Err(format!("{}: RAW source digest mismatch", entry.tensor.name)); - } - } - TensorData::NestedFile { - group, - levels, + offset: *offset, + bytes: *bytes, + name: entry.tensor.name, + digest: &entry.tensor.source_digest, + }, + ) +} + +fn write_nested_file_payload( + state: &mut SectionWriteState<'_>, + entry: &Placed<'_>, +) -> Result<(), String> { + let TensorData::NestedFile { + group, + levels, + path, + offset, + bytes, + digest, + .. + } = &entry.tensor.data + else { + unreachable!("nested file data was dispatched by variant"); + }; + copy_nested_file( + state, + NestedFileCopy { path, - offset, - bytes, + offset: *offset, + bytes: *bytes, digest, - .. - } => { - let mut source = File::open(path).map_err(|error| error.to_string())?; - let source_len = source.metadata().map_err(|error| error.to_string())?.len(); - if offset - .checked_add(*bytes) - .is_none_or(|end| end > source_len) - { - return Err("KAR nested source file is truncated".into()); - } - validate_nested_file(&mut source, entry, *offset, *group, *levels)?; - source - .seek(SeekFrom::Start(*offset)) - .map_err(|error| error.to_string())?; - let mut remaining = *bytes; - let mut buffer = vec![0u8; 1024 * 1024]; - let mut actual_digest = Sha256::new(); - while remaining > 0 { - let count = remaining.min(buffer.len() as u64) as usize; - source - .read_exact(&mut buffer[..count]) - .map_err(|error| error.to_string())?; - actual_digest.update(&buffer[..count]); - write_bytes(file, &buffer[..count], &mut crc, &mut written)?; - remaining -= count as u64; - } - if actual_digest.finalize().as_slice() != *digest { - return Err(format!( - "{}: nested section digest mismatch", - entry.tensor.name - )); - } - } - TensorData::Nested { + entry, + group: *group, + levels: *levels, + }, + ) +} + +fn write_nested_memory_payload( + state: &mut SectionWriteState<'_>, + entry: &Placed<'_>, +) -> Result<(), String> { + let TensorData::Nested { + scales, + books, + planes, + .. + } = &entry.tensor.data + else { + unreachable!("nested memory data was dispatched by variant"); + }; + write_nested_memory( + state, + NestedMemoryData { scales, books, planes, - .. - } => { - for value in *scales { - write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?; - } - pad_to( - file, - entry.books_offset - entry.section_offset, - &mut crc, - &mut written, - )?; - for book in *books { - for value in *book { - write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?; - } - } - pad_to( - file, - entry.planes_offset - entry.section_offset, - &mut crc, - &mut written, - )?; - for plane in *planes { - let base = written; - for value in *plane { - write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?; - } - pad_to( - file, - base + entry.plane_stride as u64, - &mut crc, - &mut written, - )?; - } + entry, + }, + ) +} + +struct RawFileCopy<'a> { + path: &'a Path, + offset: u64, + bytes: u64, + name: &'a str, + digest: &'a [u8; 32], +} + +fn copy_raw_file( + state: &mut SectionWriteState<'_>, + request: RawFileCopy<'_>, +) -> Result<(), String> { + let mut source = open_source_region(request.path, request.offset, request.bytes, "KAR RAW")?; + let digest = copy_region(state, &mut source, request.bytes)?; + if digest.as_slice() != request.digest { + return Err(format!("{}: RAW source digest mismatch", request.name)); + } + Ok(()) +} + +struct NestedFileCopy<'a, 'b, 't> { + path: &'a Path, + offset: u64, + bytes: u64, + digest: &'a [u8; 32], + entry: &'b Placed<'t>, + group: u16, + levels: u8, +} + +fn copy_nested_file( + state: &mut SectionWriteState<'_>, + request: NestedFileCopy<'_, '_, '_>, +) -> Result<(), String> { + let mut source = open_source_region(request.path, request.offset, request.bytes, "KAR nested")?; + copy_nested_file_from(state, request, &mut source) +} + +fn copy_nested_file_from( + state: &mut SectionWriteState<'_>, + request: NestedFileCopy<'_, '_, '_>, + source: &mut R, +) -> Result<(), String> { + validate_nested_file( + source, + NestedValidation { + entry: request.entry, + source_offset: request.offset, + group: request.group, + levels: request.levels, + }, + )?; + seek_source_offset(source, request.offset).map_err(|error| error.to_string())?; + let actual = copy_region(state, source, request.bytes)?; + if actual.as_slice() != request.digest { + return Err(format!( + "{}: nested section digest mismatch", + request.entry.tensor.name + )); + } + Ok(()) +} + +fn open_source_region(path: &Path, offset: u64, bytes: u64, label: &str) -> Result { + let mut source = File::open(path).map_err(|error| error.to_string())?; + let end = offset.checked_add(bytes); + let source_len = source.metadata().map_err(|error| error.to_string())?.len(); + if end.is_none_or(|end| end > source_len) { + return Err(format!("{label} source file is truncated")); + } + seek_source_offset(&mut source, offset).map_err(|error| error.to_string())?; + Ok(source) +} + +fn seek_source_offset(source: &mut impl Seek, offset: u64) -> io::Result<()> { + source.seek(SeekFrom::Start(offset)).map(|_| ()) +} + +fn copy_region( + state: &mut SectionWriteState<'_>, + source: &mut R, + bytes: u64, +) -> Result<[u8; 32], String> { + let mut remaining = bytes; + let mut buffer = vec![0u8; 1024 * 1024]; + let mut digest = Sha256::new(); + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + source + .read_exact(&mut buffer[..count]) + .map_err(|error| error.to_string())?; + digest.update(&buffer[..count]); + state.bytes(&buffer[..count])?; + remaining -= count as u64; + } + Ok(digest.finalize().into()) +} + +struct NestedMemoryData<'a, 'b, 't> { + scales: &'a [u16], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], + entry: &'b Placed<'t>, +} + +fn write_nested_memory( + state: &mut SectionWriteState<'_>, + data: NestedMemoryData<'_, '_, '_>, +) -> Result<(), String> { + for value in data.scales { + state.bytes(&value.to_le_bytes())?; + } + data.pad_to_books(state)?; + for book in data.books { + for value in *book { + state.bytes(&value.to_le_bytes())?; } } - pad_to(file, entry.section_bytes, &mut crc, &mut written)?; - Ok(!crc) + state.pad(data.entry.planes_offset - data.entry.section_offset)?; + for plane in data.planes { + let base = state.written; + for value in *plane { + state.bytes(&value.to_le_bytes())?; + } + state.pad(base + u64::from(data.entry.plane_stride))?; + } + Ok(()) +} + +impl NestedMemoryData<'_, '_, '_> { + fn pad_to_books(&self, state: &mut SectionWriteState<'_>) -> Result<(), String> { + state.pad(self.entry.books_offset - self.entry.section_offset) + } } #[derive(Clone, Copy)] @@ -758,57 +1860,136 @@ enum RegionRule { } fn validate_nested_file( - source: &mut File, - entry: &Placed<'_>, + source: &mut (impl Read + Seek), + request: NestedValidation<'_, '_>, +) -> Result<(), String> { + let layout = NestedFileRegions::new(&request)?; + validate_nested_prefix(source, &request, &layout)?; + validate_nested_padding(source, &request, &layout) +} + +struct NestedValidation<'a, 'b> { + entry: &'a Placed<'b>, source_offset: u64, group: u16, levels: u8, +} + +struct NestedFileRegions { + scales: u64, + books: u64, + book_bytes: u64, + planes: u64, + plane_bytes: u64, + stride: u64, + used_end: u64, +} + +impl NestedFileRegions { + fn new(request: &NestedValidation<'_, '_>) -> Result { + let entry = request.entry; + let scales = (entry.n_padded / u64::from(request.group)) * 2; + let books = entry.books_offset - entry.section_offset; + let book_bytes = (1u64 << (u32::from(request.levels) + 2)) - 4; + let planes = entry.planes_offset - entry.section_offset; + let plane_bytes = (entry.n_padded / 32) * 4; + let stride = u64::from(entry.plane_stride); + let used_end = planes + .checked_add( + u64::from(request.levels) + .checked_mul(stride) + .ok_or("nested plane range overflow")?, + ) + .ok_or("nested plane range overflow")?; + if books < scales || planes < books + book_bytes || entry.section_bytes < used_end { + return Err("invalid nested file layout".into()); + } + Ok(Self { + scales, + books, + book_bytes, + planes, + plane_bytes, + stride, + used_end, + }) + } +} + +fn validate_nested_prefix( + source: &mut (impl Read + Seek), + request: &NestedValidation<'_, '_>, + layout: &NestedFileRegions, +) -> Result<(), String> { + validate_scale_region(source, request, layout)?; + validate_book_region(source, request, layout) +} + +fn validate_scale_region( + source: &mut (impl Read + Seek), + request: &NestedValidation<'_, '_>, + layout: &NestedFileRegions, ) -> Result<(), String> { - let scales_bytes = (entry.n_padded / u64::from(group)) * 2; - let books_start = entry.books_offset - entry.section_offset; - let books_bytes = (1u64 << (u32::from(levels) + 2)) - 4; - let planes_start = entry.planes_offset - entry.section_offset; - let plane_bytes = (entry.n_padded / 32) * 4; - let stride = u64::from(entry.plane_stride); - check_file_region(source, source_offset, scales_bytes, RegionRule::FiniteScale)?; check_file_region( source, - source_offset + scales_bytes, - books_start - scales_bytes, - RegionRule::ZeroPadding, + request.source_offset, + layout.scales, + RegionRule::FiniteScale, )?; check_file_region( source, - source_offset + books_start, - books_bytes, + request.source_offset + layout.scales, + layout.books - layout.scales, + RegionRule::ZeroPadding, + ) +} + +fn validate_book_region( + source: &mut (impl Read + Seek), + request: &NestedValidation<'_, '_>, + layout: &NestedFileRegions, +) -> Result<(), String> { + check_file_region( + source, + request.source_offset + layout.books, + layout.book_bytes, RegionRule::FiniteBook, )?; + let padding = layout.planes - layout.books - layout.book_bytes; check_file_region( source, - source_offset + books_start + books_bytes, - planes_start - books_start - books_bytes, + request.source_offset + layout.books + layout.book_bytes, + padding, RegionRule::ZeroPadding, - )?; - for level in 0..u64::from(levels) { + ) +} + +fn validate_nested_padding( + source: &mut (impl Read + Seek), + request: &NestedValidation<'_, '_>, + layout: &NestedFileRegions, +) -> Result<(), String> { + for level in 0..u64::from(request.levels) { + let offset = + request.source_offset + layout.planes + level * layout.stride + layout.plane_bytes; check_file_region( source, - source_offset + planes_start + level * stride + plane_bytes, - stride - plane_bytes, + offset, + layout.stride - layout.plane_bytes, RegionRule::ZeroPadding, )?; } - let used_end = planes_start + u64::from(levels) * stride; + let tail = request.entry.section_bytes - layout.used_end; check_file_region( source, - source_offset + used_end, - entry.section_bytes - used_end, + request.source_offset + layout.used_end, + tail, RegionRule::ZeroPadding, - )?; - Ok(()) + ) } fn check_file_region( - source: &mut File, + source: &mut (impl Read + Seek), offset: u64, bytes: u64, rule: RegionRule, @@ -823,40 +2004,45 @@ fn check_file_region( source .read_exact(&mut buffer[..count]) .map_err(|error| error.to_string())?; - match rule { - RegionRule::FiniteScale | RegionRule::FiniteBook => { - if buffer[..count] - .as_chunks::<2>() - .0 - .iter() - .any(|pair| u16::from_le_bytes(*pair) & 0x7c00 == 0x7c00) - { - let name = if matches!(rule, RegionRule::FiniteScale) { - "scale" - } else { - "codebook" - }; - return Err(format!("non-finite f16 {name} in nested file")); - } - } - RegionRule::ZeroPadding => { - if buffer[..count].iter().any(|byte| *byte != 0) { - return Err("nonzero padding in nested file".into()); - } - } - } + validate_region_chunk(&buffer[..count], rule)?; remaining -= count as u64; } Ok(()) } -fn write_bytes( - file: &mut File, +fn validate_region_chunk(bytes: &[u8], rule: RegionRule) -> Result<(), String> { + match rule { + RegionRule::FiniteScale | RegionRule::FiniteBook => { + let non_finite = bytes + .as_chunks::<2>() + .0 + .iter() + .any(|pair| u16::from_le_bytes(*pair) & 0x7c00 == 0x7c00); + if non_finite { + let name = if matches!(rule, RegionRule::FiniteScale) { + "scale" + } else { + "codebook" + }; + return Err(format!("non-finite f16 {name} in nested file")); + } + } + RegionRule::ZeroPadding if bytes.iter().any(|byte| *byte != 0) => { + return Err("nonzero padding in nested file".into()); + } + RegionRule::ZeroPadding => {} + } + Ok(()) +} + +fn write_bytes( + file: &mut W, bytes: &[u8], crc: &mut u32, written: &mut u64, ) -> Result<(), String> { - file.write_all(bytes).map_err(|error| error.to_string())?; + file.write_archive_all(bytes) + .map_err(|error| error.to_string())?; *crc = kar::crc32_step(*crc, bytes); *written = written .checked_add(bytes.len() as u64) @@ -864,7 +2050,12 @@ fn write_bytes( Ok(()) } -fn pad_to(file: &mut File, target: u64, crc: &mut u32, written: &mut u64) -> Result<(), String> { +fn pad_to( + file: &mut W, + target: u64, + crc: &mut u32, + written: &mut u64, +) -> Result<(), String> { if *written > target { return Err("KAR section exceeds planned layout".into()); } @@ -877,6 +2068,22 @@ fn pad_to(file: &mut File, target: u64, crc: &mut u32, written: &mut u64) -> Res } fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> { + let tensor = entry.tensor; + write_record_identity(record, entry)?; + if let Some(metadata) = nested_record_metadata(entry)? { + write_nested_record(record, entry, metadata)?; + } + put_u64(record, 48, entry.n_elements); + put_u64(record, 56, entry.n_padded); + put_u32(record, 108, entry.payload_crc32); + put_u64(record, 112, entry.section_offset); + put_u64(record, 120, entry.section_bytes); + record[128..160].copy_from_slice(&tensor.source_digest); + put_u64(record, 160, tensor.source_offset); + Ok(()) +} + +fn write_record_identity(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> { let tensor = entry.tensor; put_u32(record, 0, entry.name_offset); put_u16( @@ -889,6 +2096,12 @@ fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> { tensor.data, TensorData::Raw(_) | TensorData::RawFile { .. } )); + write_record_dimensions(record, tensor); + record[41] = tensor.source_dtype; + Ok(()) +} + +fn write_record_dimensions(record: &mut [u8], tensor: &Tensor<'_>) { for index in 0..4 { put_u64( record, @@ -896,8 +2109,33 @@ fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> { tensor.dims.get(index).copied().unwrap_or(1), ); } - record[41] = tensor.source_dtype; - let nested = match &tensor.data { +} + +struct NestedRecordMetadata { + group: u16, + nesting: u8, + planes_min: u8, + planes_max: u8, + levels: u8, +} + +fn nested_record_metadata(entry: &Placed<'_>) -> Result, String> { + let Some((group, nesting, planes_min, planes_max, levels)) = + nested_record_fields(&entry.tensor.data) + else { + return Ok(None); + }; + Ok(Some(NestedRecordMetadata { + group, + nesting, + planes_min, + planes_max, + levels, + })) +} + +fn nested_record_fields(data: &TensorData<'_>) -> Option<(u16, u8, u8, u8, u8)> { + match data { TensorData::Nested { group, nesting, @@ -921,33 +2159,31 @@ fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> { .. } => Some((*group, *nesting, *planes_min, *planes_max, *levels)), _ => None, - }; - if let Some((group, nesting, planes_min, planes_max, levels)) = nested { - record[42] = levels; - record[43] = planes_min; - record[44] = planes_max; - record[45] = nesting; - put_u16(record, 46, group); - put_u64(record, 64, entry.scales_offset); - put_u64( - record, - 72, - (entry.n_padded / u64::from(group)) - .checked_mul(2) - .ok_or("KAR scales overflow")?, - ); - put_u64(record, 80, entry.books_offset); - put_u64(record, 88, (1u64 << (u32::from(levels) + 2)) - 4); - put_u64(record, 96, entry.planes_offset); - put_u32(record, 104, entry.plane_stride); } - put_u64(record, 48, entry.n_elements); - put_u64(record, 56, entry.n_padded); - put_u32(record, 108, entry.payload_crc32); - put_u64(record, 112, entry.section_offset); - put_u64(record, 120, entry.section_bytes); - record[128..160].copy_from_slice(&tensor.source_digest); - put_u64(record, 160, tensor.source_offset); +} + +fn write_nested_record( + record: &mut [u8], + entry: &Placed<'_>, + metadata: NestedRecordMetadata, +) -> Result<(), String> { + record[42] = metadata.levels; + record[43] = metadata.planes_min; + record[44] = metadata.planes_max; + record[45] = metadata.nesting; + put_u16(record, 46, metadata.group); + put_u64(record, 64, entry.scales_offset); + put_u64( + record, + 72, + (entry.n_padded / u64::from(metadata.group)) + .checked_mul(2) + .ok_or("KAR scales overflow")?, + ); + put_u64(record, 80, entry.books_offset); + put_u64(record, 88, (1u64 << (u32::from(metadata.levels) + 2)) - 4); + put_u64(record, 96, entry.planes_offset); + put_u32(record, 104, entry.plane_stride); Ok(()) } @@ -964,21 +2200,522 @@ fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { #[cfg(test)] mod tests { use super::*; + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; + + fn test_nested_layout(values: (u64, u64, u16, u8, u8, u8, u8)) -> NestedLayoutRequest { + let (cursor, n_elements, group, nesting, planes_min, planes_max, levels) = values; + NestedLayoutRequest { + cursor, + n_elements, + group, + nesting, + planes_min, + planes_max, + levels, + } + } + + struct FaultReadSeek { + inner: std::io::Cursor>, + fail_seek_at: Option, + seeks: usize, + } + + impl FaultReadSeek { + fn new(bytes: Vec) -> Self { + Self { + inner: std::io::Cursor::new(bytes), + fail_seek_at: None, + seeks: 0, + } + } + } + + impl Read for FaultReadSeek { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.inner.read(buffer) + } + } + + impl Seek for FaultReadSeek { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.seeks += 1; + if self.fail_seek_at == Some(self.seeks) { + return Err(io::ErrorKind::Other.into()); + } + self.inner.seek(position) + } + } + + struct FaultArchiveOutput { + inner: std::io::Cursor>, + fail_seek_at: Option, + fail_write_at: Option, + fail_set_len: bool, + fail_len: bool, + fail_sync: bool, + seeks: usize, + writes: usize, + } + + impl Default for FaultArchiveOutput { + fn default() -> Self { + Self { + inner: std::io::Cursor::new(Vec::new()), + fail_seek_at: None, + fail_write_at: None, + fail_set_len: false, + fail_len: false, + fail_sync: false, + seeks: 0, + writes: 0, + } + } + } + + impl Read for FaultArchiveOutput { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.inner.read(buffer) + } + } + + impl Write for FaultArchiveOutput { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.writes += 1; + if self.fail_write_at == Some(self.writes) { + return Err(io::ErrorKind::Other.into()); + } + self.inner.write(bytes) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } + } + + impl Seek for FaultArchiveOutput { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.seeks += 1; + if self.fail_seek_at == Some(self.seeks) { + return Err(io::ErrorKind::Other.into()); + } + self.inner.seek(position) + } + } + + impl ArchiveOutput for FaultArchiveOutput { + fn set_archive_len(&mut self, len: u64) -> io::Result<()> { + if self.fail_set_len { + return Err(io::ErrorKind::Other.into()); + } + self.inner.get_mut().resize(len as usize, 0); + Ok(()) + } + + fn archive_len(&self) -> io::Result { + if self.fail_len { + return Err(io::ErrorKind::Other.into()); + } + Ok(self.inner.get_ref().len() as u64) + } + + fn sync_archive(&self) -> io::Result<()> { + if self.fail_sync { + Err(io::ErrorKind::Other.into()) + } else { + Ok(()) + } + } + } fn fail_cleanup(_: &Path) -> Result<(), String> { Err("injected temporary cleanup failure".into()) } + #[cfg(unix)] #[test] - fn post_publish_temporary_cleanup_error_keeps_archive_without_overwriting() { - let root = std::env::temp_dir().join(format!("strata-kar-publish-{}", std::process::id())); - let _ = fs::remove_dir_all(&root); - fs::create_dir(&root).unwrap(); - let temporary = root.join("candidate.part"); + fn temporary_slot_creation_retries_lock_and_identity_conflicts() { + let root = test_dir("temp-slot-retry"); let destination = root.join("archive.kar"); - fs::write(&temporary, b"verified archive").unwrap(); - let summary = kar::Summary { - archive_bytes: 16, + assert_lock_conflict_uses_next_temp_slot(&destination); + reap_stale_archive_temps(&destination).unwrap(); + assert_identity_conflict_uses_next_temp_slot(&destination); + reap_stale_archive_temps(&destination).unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn assert_lock_conflict_uses_next_temp_slot(destination: &Path) { + let mut locks = 0; + let (path, file) = create_archive_temp_with( + destination, + |path| archive_temp_options().open(path), + |file| { + locks += 1; + if locks == 1 { + Err(std::fs::TryLockError::WouldBlock) + } else { + file.try_lock() + } + }, + archive_temp_path_matches, + ) + .unwrap(); + assert_eq!(path, archive_temp_path(destination, 1)); + remove_archive_temp_locked(&path, &file).unwrap(); + } + + #[cfg(unix)] + fn assert_identity_conflict_uses_next_temp_slot(destination: &Path) { + let mut checks = 0; + let (path, file) = create_archive_temp_with( + destination, + |path| archive_temp_options().open(path), + |file| file.try_lock(), + |path, file| { + checks += 1; + checks > 1 && archive_temp_path_matches(path, file) + }, + ) + .unwrap(); + assert_eq!(path, archive_temp_path(destination, 1)); + remove_archive_temp_locked(&path, &file).unwrap(); + } + + #[cfg(unix)] + #[test] + fn temporary_slot_creation_fails_closed_on_lock_and_open_errors() { + let root = test_dir("temp-slot-errors"); + let destination = root.join("archive.kar"); + let lock_error = create_archive_temp_with( + &destination, + |path| archive_temp_options().open(path), + |_| Err(std::fs::TryLockError::Error(io::ErrorKind::Other.into())), + archive_temp_path_matches, + ); + assert!(lock_error.is_err()); + reap_stale_archive_temps(&destination).unwrap(); + + let open_error = create_archive_temp_with( + &destination, + |_| Err(io::ErrorKind::PermissionDenied.into()), + |_| unreachable!(), + |_, _| unreachable!(), + ); + assert!(open_error.is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn archive_destination_and_temp_pair_enforce_private_path_contract() { + let root = test_dir("private-pair"); + let other = root.join("other"); + fs::create_dir(&other).unwrap(); + assert!(private_archive_destination(Path::new("")).is_err()); + assert!(private_archive_pair(&root.join("temp.part"), &other.join("archive.kar")).is_err()); + let (temporary, destination) = + private_archive_pair(&root.join("temp.part"), &root.join("archive.kar")).unwrap(); + assert_eq!(temporary.parent(), destination.parent()); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn archive_temp_metadata_matching_fails_closed_on_metadata_errors() { + let root = test_dir("temp-metadata-errors"); + let path = root.join("temp.part"); + fs::write(&path, b"owned").unwrap(); + let metadata = fs::metadata(&path).unwrap(); + assert!(!archive_temp_metadata_matches( + Err(io::ErrorKind::Other.into()), + Ok(metadata) + )); + assert!(!archive_temp_metadata_matches( + Ok(fs::metadata(&path).unwrap()), + Err(io::ErrorKind::NotFound.into()) + )); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn reaper_open_and_lock_errors_preserve_the_temporary_path() { + let root = test_dir("reaper-errors"); + let destination = root.join("archive.kar"); + let path = archive_temp_path(&destination, 0); + write_temp(&path); + assert_reaper_open_error_policy(); + assert_reaper_lock_errors_preserve_temp(&path, &destination); + assert!(path.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn assert_reaper_open_error_policy() { + assert!(handle_reap_archive_temp_open_error(io::ErrorKind::NotFound.into()).is_ok()); + assert!( + handle_reap_archive_temp_open_error(io::ErrorKind::PermissionDenied.into()).is_err() + ); + } + + #[cfg(unix)] + fn assert_reaper_lock_errors_preserve_temp(path: &Path, destination: &Path) { + let fixture = locked_reaper_files(path); + assert_reaper_would_block(path, destination, &fixture); + assert_reaper_lock_io_error(path, destination, &fixture); + } + + #[cfg(unix)] + struct LockedReaperFiles { + before: fs::Metadata, + _owner: File, + blocked: File, + } + + #[cfg(unix)] + fn locked_reaper_files(path: &Path) -> LockedReaperFiles { + let before = fs::symlink_metadata(path).unwrap(); + let owner = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .unwrap(); + owner.try_lock().unwrap(); + let blocked = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .unwrap(); + LockedReaperFiles { + before, + _owner: owner, + blocked, + } + } + + #[cfg(unix)] + fn assert_reaper_would_block(path: &Path, destination: &Path, files: &LockedReaperFiles) { + assert!( + finish_reap_archive_temp_lock( + path, + destination, + &files.before, + &files.blocked, + Err(std::fs::TryLockError::WouldBlock) + ) + .is_ok() + ); + } + + #[cfg(unix)] + fn assert_reaper_lock_io_error(path: &Path, destination: &Path, files: &LockedReaperFiles) { + assert!( + finish_reap_archive_temp_lock( + path, + destination, + &files.before, + &files.blocked, + Err(std::fs::TryLockError::Error(io::ErrorKind::Other.into())) + ) + .is_err() + ); + } + + #[cfg(unix)] + #[test] + fn archive_temp_unlink_handles_missing_replaced_and_unpublished_links() { + let root = test_dir("temp-unlink-boundaries"); + let destination = root.join("archive.kar"); + assert_missing_temp_unlink_is_idempotent(&destination); + assert_unpublished_hard_link_is_preserved(&root, &destination); + assert_replaced_temp_path_is_not_owned(&destination); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn substituted_temp_in_untrusted_parent_is_neither_deleted_nor_published() { + let root = test_dir("untrusted-parent"); + let destination = root.join("archive.kar"); + let temporary = archive_temp_path(&destination, 0); + fs::write(&temporary, b"original inode").unwrap(); + let file = OpenOptions::new() + .read(true) + .write(true) + .open(&temporary) + .unwrap(); + file.try_lock().unwrap(); + let before = file.metadata().unwrap(); + fs::remove_file(&temporary).unwrap(); + fs::write(&temporary, b"substituted inode").unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o777)).unwrap(); + assert_substitution_is_rejected(&temporary, &destination, &before, &file); + drop(file); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn assert_substitution_is_rejected( + temporary: &Path, + destination: &Path, + before: &fs::Metadata, + file: &File, + ) { + assert!(unlink_if_same_archive_temp(temporary, destination, before, file).is_err()); + assert!( + publish_verified_archive( + temporary, + destination, + simple_archive_summary(18), + remove_archive_temp, + ) + .is_err() + ); + assert!(reap_stale_archive_temps(destination).is_err()); + assert_eq!(fs::read(temporary).unwrap(), b"substituted inode"); + assert!(!destination.exists()); + } + + #[cfg(unix)] + fn assert_missing_temp_unlink_is_idempotent(destination: &Path) { + let path = archive_temp_path(destination, 0); + write_temp(&path); + let file = OpenOptions::new() + .read(true) + .write(true) + .open(&path) + .unwrap(); + file.try_lock().unwrap(); + let original = fs::symlink_metadata(&path).unwrap(); + fs::remove_file(&path).unwrap(); + assert!(unlink_if_same_archive_temp(&path, destination, &original, &file).is_ok()); + } + + #[cfg(unix)] + fn assert_unpublished_hard_link_is_preserved(root: &Path, destination: &Path) { + let path = archive_temp_path(destination, 1); + write_temp(&path); + let file = OpenOptions::new() + .read(true) + .write(true) + .open(&path) + .unwrap(); + file.try_lock().unwrap(); + let before = fs::symlink_metadata(&path).unwrap(); + let unrelated_link = root.join("unpublished-link.part"); + fs::hard_link(&path, &unrelated_link).unwrap(); + assert!(unlink_if_same_archive_temp(&path, destination, &before, &file).is_ok()); + assert!(path.exists() && unrelated_link.exists()); + assert!(!is_published_temp(&before, destination)); + drop(file); + } + + #[cfg(unix)] + fn assert_replaced_temp_path_is_not_owned(destination: &Path) { + let path = archive_temp_path(destination, 2); + write_temp(&path); + let file = OpenOptions::new() + .read(true) + .write(true) + .open(&path) + .unwrap(); + file.try_lock().unwrap(); + let before = fs::symlink_metadata(&path).unwrap(); + fs::remove_file(&path).unwrap(); + fs::write(&path, b"replacement").unwrap(); + assert!(unlink_if_same_archive_temp(&path, destination, &before, &file).is_ok()); + assert_eq!(fs::read(&path).unwrap(), b"replacement"); + drop(file); + } + + #[cfg(unix)] + #[test] + fn archive_temp_unlink_returns_metadata_and_remove_failures() { + let root = test_dir("temp-unlink-io-errors"); + let destination = root.join("archive.kar"); + assert_temp_unlink_metadata_error(&destination); + assert_temp_unlink_remove_error(&destination); + assert!(archive_temp_path(&destination, 0).exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn locked_archive_temp(destination: &Path) -> (PathBuf, File, fs::Metadata) { + let path = archive_temp_path(destination, 0); + write_temp(&path); + let file = OpenOptions::new() + .read(true) + .write(true) + .open(&path) + .unwrap(); + file.try_lock().unwrap(); + let before = fs::symlink_metadata(&path).unwrap(); + (path, file, before) + } + + #[cfg(unix)] + fn assert_temp_unlink_metadata_error(destination: &Path) { + let (path, file, before) = locked_archive_temp(destination); + assert!( + unlink_if_same_archive_temp_with( + &path, + destination, + &before, + &file, + ArchiveTempPathOps { + metadata: denied_temp_metadata, + remove: archive_temp_remove_file + }, + ) + .is_err() + ); + drop(file); + } + + #[cfg(unix)] + fn assert_temp_unlink_remove_error(destination: &Path) { + let (path, file, before) = locked_archive_temp(destination); + assert!( + unlink_if_same_archive_temp_with( + &path, + destination, + &before, + &file, + ArchiveTempPathOps { + metadata: archive_temp_symlink_metadata, + remove: denied_temp_remove + }, + ) + .is_err() + ); + drop(file); + } + + #[cfg(unix)] + fn denied_temp_metadata(_: &Path) -> io::Result { + Err(io::ErrorKind::PermissionDenied.into()) + } + + #[cfg(unix)] + fn denied_temp_remove(_: &Path) -> io::Result<()> { + Err(io::ErrorKind::PermissionDenied.into()) + } + + fn test_dir(label: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!( + "strata-kar-{label}-{}-{}", + std::process::id(), + ARCHIVE_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + path + } + + fn simple_archive_summary(archive_bytes: u64) -> kar::Summary { + kar::Summary { + archive_bytes, tensor_count: 1, total_elements: 1, source_total_elements: 1, @@ -986,64 +2723,1320 @@ mod tests { source_digest: [0; 32], source_bytes: 4, max_planes: 0, - }; - assert!(publish_verified_archive(&temporary, &destination, summary, fail_cleanup).is_err()); - assert_eq!(fs::read(&destination).unwrap(), b"verified archive"); - assert!(temporary.exists()); + } + } - let unrelated = root.join("unrelated.kar"); - let competing = root.join("competing.part"); - fs::write(&unrelated, b"do not replace").unwrap(); - fs::write(&competing, b"other archive").unwrap(); - let competing_summary = kar::Summary { - archive_bytes: 13, - tensor_count: 1, - total_elements: 1, - source_total_elements: 1, - accounted_bpw: 104.0, + fn raw_tensor() -> Tensor<'static> { + Tensor { + name: "raw", + dims: &[1], + source_dtype: 0, source_digest: [0; 32], - source_bytes: 4, - max_planes: 0, + source_offset: 0, + data: TensorData::Raw(&[0; 4]), + } + } + + fn placed<'a>(tensor: &'a Tensor<'a>) -> Placed<'a> { + Placed { + tensor, + name_offset: 0, + n_elements: 1, + n_padded: 1, + section_offset: 0, + section_bytes: 0, + scales_offset: 0, + books_offset: 0, + planes_offset: 0, + plane_stride: 0, + payload_crc32: 0, + } + } + + #[test] + fn archive_name_table_rejects_duplicate_empty_and_nul_names() { + let input = reference_input(); + let source = reference_source(&input); + let mut tensors = reference_tensors(&input); + tensors[1].name = tensors[0].name; + assert!(ArchiveNames::build(&source, &tensors).is_err()); + tensors[1].name = "expert"; + tensors[0].name = ""; + assert!(ArchiveNames::build(&source, &tensors).is_err()); + tensors[0].name = "norm"; + let invalid = SourceIdentity { + name: "bad\0name", + ..source + }; + assert!(ArchiveNames::build(&invalid, &tensors).is_err()); + } + + #[test] + fn archive_name_table_enforces_the_inspector_byte_limit() { + let input = reference_input(); + let long_name = "s".repeat(64 * 1024 * 1024 + 1); + let source = SourceIdentity { + name: &long_name, + ..reference_source(&input) }; assert!( - publish_verified_archive( - &competing, - &unrelated, - competing_summary, - remove_archive_temp, - ) - .is_err() + ArchiveNames::build(&source, &[]) + .err() + .unwrap() + .contains("inspector limit") ); - assert_eq!(fs::read(unrelated).unwrap(), b"do not replace"); + } + + #[test] + fn nested_spool_is_written_verified_and_never_overwrites_an_existing_file() { + let root = test_dir("nested-spool"); + let input = reference_input(); + let tensors = reference_tensors(&input); + let path = root.join("nested.section"); + let summary = write_nested_section(&path, &tensors[1]).unwrap(); + assert_eq!(summary.bytes, fs::metadata(&path).unwrap().len()); + assert_eq!( + summary.digest, + hash_reader(&mut File::open(&path).unwrap()).unwrap() + ); + assert!(write_nested_section(&path, &tensors[1]).is_err()); fs::remove_dir_all(root).unwrap(); } #[test] - fn streams_canonical_nested_section_and_rejects_corruption() { + fn nested_spool_size_mismatch_is_removed_for_safe_retry() { + let root = test_dir("nested-spool-size-mismatch"); + let input = reference_input(); + let tensors = reference_tensors(&input); + let mut plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + plan.layout.section_bytes += 1; + let path = root.join("nested.section"); + let error = write_nested_spool(&path, &plan).unwrap_err(); + assert!(error.contains("spool size mismatch")); + assert!(!path.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn archive_request_rejects_empty_identity_and_existing_destination() { + let root = test_dir("request-validation"); + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let destination = root.join("archive.kar"); + assert!(validate_archive_request(&destination, &source, &tensors).is_ok()); + assert!(validate_archive_request(&destination, &source, &[]).is_err()); + let empty = SourceIdentity { + bytes: 0, + ..reference_source(&input) + }; + assert!(validate_archive_request(&destination, &empty, &tensors).is_err()); + let empty = SourceIdentity { + total_elements: 0, + ..reference_source(&input) + }; + assert!(validate_archive_request(&destination, &empty, &tensors).is_err()); + fs::write(&destination, b"occupied").unwrap(); + assert!(validate_archive_request(&destination, &source, &tensors).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn archive_request_rejects_tensor_counts_above_the_inspector_limit() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = std::iter::repeat_with(raw_tensor) + .take(100_001) + .collect::>(); + assert!(validate_archive_request(Path::new("absent.kar"), &source, &tensors).is_err()); + } + + #[test] + fn archive_plan_rejects_tensors_that_exceed_source_elements() { + let input = reference_input(); + let mut source = reference_source(&input); + let tensors = reference_tensors(&input); + source.total_elements = 1; + assert!(ArchivePlan::build(&source, &tensors).is_err()); + } + + #[test] + fn nested_slice_validation_rejects_each_malformed_component() { + let fixture = NestedSliceFixture::new(); + let books = fixture.books(); + let planes = fixture.planes(); + assert!(fixture.validate(&fixture.scales, &books, &planes).is_ok()); + assert!( + fixture + .validate(&fixture.scales, &books[..1], &planes) + .is_err() + ); + assert!(fixture.validate(&[], &books, &planes).is_err()); + assert!( + fixture + .validate(&fixture.bad_scales, &books, &planes) + .is_err() + ); + assert_nested_book_rejections(&fixture); + assert!( + fixture + .validate(&fixture.scales, &books, &fixture.bad_planes()) + .is_err() + ); + } + + struct NestedSliceFixture { + layout: NestedLayout, + scales: [u16; 1], + bad_scales: [u16; 1], + first: [u16; 2], + second: [u16; 4], + bad_first: [u16; 2], + planes_data: [[u32; 1]; 2], + } + + impl NestedSliceFixture { + fn new() -> Self { + let first = [0x3c00; 2]; + let second = [0x3c00; 4]; + let planes_data = [[0u32; 1], [0u32; 1]]; + let layout = nested_layout(test_nested_layout((0, 32, 32, 0, 1, 2, 2))).unwrap(); + Self { + layout, + scales: [0x3c00], + bad_scales: [0x7c00], + first, + second, + bad_first: [0x7c00, 0x3c00], + planes_data, + } + } + + fn books(&self) -> [&[u16]; 2] { + [&self.first, &self.second] + } + + fn planes(&self) -> [&[u32]; 2] { + [&self.planes_data[0], &self.planes_data[1]] + } + + fn bad_planes(&self) -> [&[u32]; 2] { + [&[], &self.planes_data[1]] + } + + fn validate<'a>( + &'a self, + scales: &'a [u16], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], + ) -> Result<(), String> { + validate_nested_slices(NestedSliceValidation { + name: "t", + layout: &self.layout, + group: 32, + scales, + books, + planes, + }) + } + } + + fn assert_nested_book_rejections(fixture: &NestedSliceFixture) { + let planes = fixture.planes(); + let wrong_size = [&fixture.first[..1], &fixture.second[..]]; + let non_finite = [&fixture.bad_first[..], &fixture.second[..]]; + assert!( + fixture + .validate(&fixture.scales, &wrong_size, &planes) + .is_err() + ); + assert!( + fixture + .validate(&fixture.scales, &non_finite, &planes) + .is_err() + ); + } + + #[test] + fn nested_file_layout_rejects_offsets_that_overlap_scales() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let mut entry = placed(&tensors[1]); + entry.n_padded = 32; + let request = NestedValidation { + entry: &entry, + source_offset: 0, + group: 32, + levels: 2, + }; + assert!(NestedFileRegions::new(&request).is_err()); + } + + #[test] + fn nested_layout_rejects_invalid_parameters_and_overflow() { + assert_invalid_nested_layout_parameters(); + assert_nested_layout_overflows(); + assert!(round_up(u64::MAX, 256).is_err()); + } + + fn assert_invalid_nested_layout_parameters() { + for (group, nesting, min, max, levels) in [ + (0, 0, 1, 2, 2), + (1056, 0, 1, 2, 2), + (31, 0, 1, 2, 2), + (32, 2, 1, 2, 2), + (32, 0, 0, 2, 2), + (32, 0, 2, 1, 2), + (32, 0, 1, 3, 2), + (32, 0, 1, 2, 0), + ] { + assert!( + nested_layout(test_nested_layout(( + 0, 32, group, nesting, min, max, levels + ))) + .is_err() + ); + } + } + + fn assert_nested_layout_overflows() { + assert!(nested_layout(test_nested_layout((u64::MAX, 32, 32, 0, 1, 2, 2))).is_err()); + assert!(nested_layout(test_nested_layout((0, u64::MAX, 32, 0, 1, 2, 2))).is_err()); + assert!( + nested_layout(test_nested_layout(( + 0, + (u32::MAX as u64 + 1) * 8, + 32, + 0, + 1, + 2, + 2 + ))) + .is_err() + ); + assert!(nested_layout(test_nested_layout((u64::MAX - 2, 32, 32, 0, 1, 2, 2))).is_err()); + assert!(nested_layout(test_nested_layout((u64::MAX - 17, 32, 32, 0, 1, 2, 2))).is_err()); + } + + #[test] + fn tensor_shape_validation_rejects_rank_dtype_zero_and_overflow() { + let valid = raw_tensor(); + assert_eq!(validate_shape(&valid).unwrap(), 1); + for invalid in [ + Tensor { + dims: &[], + ..raw_tensor() + }, + Tensor { + dims: &[0], + ..raw_tensor() + }, + Tensor { + dims: &[u64::MAX, 2], + ..raw_tensor() + }, + Tensor { + source_dtype: 3, + ..raw_tensor() + }, + ] { + assert!(validate_shape(&invalid).is_err()); + } + } + + #[test] + #[should_panic(expected = "raw tensor data was dispatched separately")] + fn nested_placement_panics_if_raw_dispatch_invariant_is_broken() { + let tensor = raw_tensor(); + let request = PlacementRequest { + tensor: &tensor, + elements: 1, + cursor: 0, + }; + let _ = nested_placement(request, &tensor.data); + } + + #[test] + fn placement_builders_reject_wrong_variants_and_raw_shape_mismatches() { + let tensor = raw_tensor(); + let request = PlacementRequest { + tensor: &tensor, + elements: 1, + cursor: 0, + }; + assert!(memory_placement_request(request, &tensor.data).is_err()); + assert!(file_placement_request(request, &tensor.data).is_err()); + assert!(raw_placement(&request, 4).is_ok()); + let half = Tensor { + source_dtype: 1, + ..tensor + }; + let request = PlacementRequest { + tensor: &half, + elements: 2, + cursor: 0, + }; + assert!(raw_placement(&request, 4).is_ok()); + assert!(raw_placement(&request, 2).is_err()); + assert!(raw_placement(&request, u64::MAX).is_err()); + } + + #[test] + fn nested_file_placement_rejects_a_mismatched_spool_length() { + let tensor = mismatched_nested_file_tensor(); + let request = PlacementRequest { + tensor: &tensor, + elements: 32, + cursor: 0, + }; + assert!( + nested_file_placement(NestedFilePlacement { + request, + group: 32, + nesting: 0, + min: 1, + max: 2, + levels: 2, + bytes: 0, + }) + .is_err() + ); + } + + fn mismatched_nested_file_tensor() -> Tensor<'static> { + Tensor { + name: "nested", + dims: &[32], + source_dtype: 0, + source_digest: [0; 32], + source_offset: 0, + data: TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: Path::new("unused"), + offset: 0, + bytes: 0, + digest: [0; 32], + }, + } + } + + #[test] + #[should_panic] + fn staged_input_removal_panics_for_memory_backed_tensor() { + let tensor = raw_tensor(); + let _ = remove_staged_tensor(&placed(&tensor)); + } + + #[test] + #[should_panic(expected = "raw file data was dispatched by variant")] + #[cfg(unix)] + fn raw_file_payload_panics_if_dispatch_variant_is_wrong() { + let mut output = File::open("/dev/null").unwrap(); + let mut state = SectionWriteState::new(&mut output); + let tensor = raw_tensor(); + let _ = write_raw_file_payload(&mut state, &placed(&tensor)); + } + + #[test] + #[should_panic(expected = "nested file data was dispatched by variant")] + #[cfg(unix)] + fn nested_file_payload_panics_if_dispatch_variant_is_wrong() { + let mut output = File::open("/dev/null").unwrap(); + let mut state = SectionWriteState::new(&mut output); + let tensor = raw_tensor(); + let _ = write_nested_file_payload(&mut state, &placed(&tensor)); + } + + #[test] + #[should_panic(expected = "nested memory data was dispatched by variant")] + #[cfg(unix)] + fn nested_memory_payload_panics_if_dispatch_variant_is_wrong() { + let mut output = File::open("/dev/null").unwrap(); + let mut state = SectionWriteState::new(&mut output); + let tensor = raw_tensor(); + let _ = write_nested_memory_payload(&mut state, &placed(&tensor)); + } + + #[test] + fn missing_parent_fails_stale_temp_scan_before_writing() { + let missing = std::env::temp_dir() + .join(format!("strata-missing-parent-{}", std::process::id())) + .join("archive.kar"); + assert!(reap_stale_archive_temps(&missing).is_err()); + assert!(create_archive_temp(&missing).is_err()); + } + + #[test] + fn source_region_and_hash_reader_fail_on_short_or_unreadable_inputs() { + let root = test_dir("source-region-errors"); + let source_path = root.join("short.bin"); + fs::write(&source_path, b"x").unwrap(); + assert!(open_source_region(&source_path, 0, 2, "test").is_err()); + assert!(open_source_region(&source_path, u64::MAX, 1, "test").is_err()); + assert!(open_source_region(&root.join("missing"), 0, 0, "test").is_err()); + assert!(hash_reader(&mut File::open(&root).unwrap()).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn oversized_section_padding_is_rejected() { + let root = test_dir("padding-overflow"); + let mut file = File::create(root.join("out.bin")).unwrap(); + let mut crc = !0u32; + let mut written = 2; + assert!(pad_to(&mut file, 1, &mut crc, &mut written).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn nested_file_regions_reject_section_shorter_than_used_planes() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + let mut entry = plan.entry; + let used_end = { + let request = NestedValidation { + entry: &entry, + source_offset: 0, + group: 32, + levels: 2, + }; + NestedFileRegions::new(&request).unwrap().used_end + }; + assert!(used_end > 0); + entry.section_bytes = used_end - 1; + let request = NestedValidation { + entry: &entry, + source_offset: 0, + group: 32, + levels: 2, + }; + assert!(matches!( + NestedFileRegions::new(&request), + Err(error) if error == "invalid nested file layout" + )); + } + + fn missing_nested_tensor(path: &Path, bytes: u64) -> Tensor<'_> { + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path, + offset: 0, + bytes, + digest: [0; 32], + }, + } + } + + #[test] + fn nested_file_failure_removes_new_spool_and_region_copy_reports_short_read() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let memory = NestedSectionPlan::new(&tensors[1]).unwrap(); + let missing = PathBuf::from("missing-nested-section"); + let nested = missing_nested_tensor(&missing, memory.layout.section_bytes); + let root = test_dir("nested-spool-errors"); + let spool = root.join("new.section"); + assert!(write_nested_section(&spool, &nested).is_err()); + assert!(!spool.exists()); + let mut output = File::create(root.join("out.bin")).unwrap(); + let mut state = SectionWriteState::new(&mut output); + let path = root.join("short.bin"); + fs::write(&path, b"x").unwrap(); + let mut source = File::open(path).unwrap(); + assert!(copy_region(&mut state, &mut source, 2).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn nested_verifier_rejects_a_missing_spool() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + let root = test_dir("missing-verify-spool"); + assert!(verify_nested_spool(&root.join("missing.section"), &plan).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn staged_file_cleanup_reports_when_owned_input_disappeared() { + let root = test_dir("missing-staged-cleanup"); + let path = root.join("gone.raw"); + let tensor = Tensor { + name: "weight", + dims: &[1], + source_dtype: 0, + source_digest: [0; 32], + source_offset: 0, + data: TensorData::RawFile { + path: &path, + offset: 0, + bytes: 4, + }, + }; + assert!(remove_staged_tensor(&placed(&tensor)).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn nested_region_validator_rejects_short_file_data() { + let root = test_dir("short-region"); + let path = root.join("input.bin"); + fs::write(&path, [0u8]).unwrap(); + let mut file = File::open(path).unwrap(); + assert!(check_file_region(&mut file, 0, 2, RegionRule::ZeroPadding).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn nested_region_validator_propagates_seek_failure() { + let mut source = FaultReadSeek::new(Vec::new()); + source.fail_seek_at = Some(1); + assert!(check_file_region(&mut source, 0, 0, RegionRule::ZeroPadding).is_err()); + } + + #[test] + fn nested_spool_and_copy_propagate_post_validation_seek_failures() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + let root = test_dir("nested-seek-errors"); + let spool = root.join("nested.bin"); + write_nested_section(&spool, &tensors[1]).unwrap(); + let bytes = fs::read(&spool).unwrap(); + let (final_seek, expected) = verify_nested_spool_seek_paths(&bytes, &plan); + assert_nested_copy_seek_paths(&spool, &bytes, &plan, final_seek, &expected); + fs::remove_dir_all(root).unwrap(); + } + + fn verify_nested_spool_seek_paths( + bytes: &[u8], + plan: &NestedSectionPlan<'_>, + ) -> (usize, [u8; 32]) { + let mut counter = FaultReadSeek::new(bytes.to_vec()); + validate_nested_file( + &mut counter, + nested_validation(&plan.entry, plan.group, plan.levels), + ) + .unwrap(); + let final_seek = counter.seeks + 1; + let mut failed = FaultReadSeek::new(bytes.to_vec()); + failed.fail_seek_at = Some(final_seek); + assert!(verify_nested_spool_reader(&mut failed, plan).is_err()); + let mut verified = FaultReadSeek::new(bytes.to_vec()); + let summary = verify_nested_spool_reader(&mut verified, plan).unwrap(); + let expected = Sha256::digest(bytes).into(); + assert_eq!(summary.digest, expected); + (final_seek, expected) + } + + fn nested_validation<'a, 'b>( + entry: &'a Placed<'b>, + group: u16, + levels: u8, + ) -> NestedValidation<'a, 'b> { + NestedValidation { + entry, + source_offset: 0, + group, + levels, + } + } + + fn assert_nested_copy_seek_paths( + spool: &Path, + bytes: &[u8], + plan: &NestedSectionPlan<'_>, + final_seek: usize, + expected: &[u8; 32], + ) { + let mut failed_output = FaultArchiveOutput::default(); + let mut failed_state = SectionWriteState::new(&mut failed_output); + let mut failed_source = FaultReadSeek::new(bytes.to_vec()); + failed_source.fail_seek_at = Some(final_seek); + let failed = nested_file_copy(spool, plan, &[0; 32]); + assert!(copy_nested_file_from(&mut failed_state, failed, &mut failed_source).is_err()); + let mut output = FaultArchiveOutput::default(); + let mut state = SectionWriteState::new(&mut output); + let mut source = FaultReadSeek::new(bytes.to_vec()); + let valid = nested_file_copy(spool, plan, expected); + copy_nested_file_from(&mut state, valid, &mut source).unwrap(); + assert_eq!(output.inner.get_ref(), bytes); + } + + fn nested_file_copy<'a, 'b, 't>( + spool: &'a Path, + plan: &'b NestedSectionPlan<'t>, + digest: &'a [u8; 32], + ) -> NestedFileCopy<'a, 'b, 't> { + NestedFileCopy { + path: spool, + offset: 0, + bytes: plan.layout.section_bytes, + digest, + entry: &plan.entry, + group: plan.group, + levels: plan.levels, + } + } + + #[test] + fn nested_file_layout_rejects_each_invalid_region_ordering() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let entry = placed(&tensors[1]); + for field in 0..3 { + let invalid = corrupt_nested_layout(&entry, field); + let request = NestedValidation { + entry: &invalid, + source_offset: 0, + group: 32, + levels: 2, + }; + assert!(NestedFileRegions::new(&request).is_err()); + } + } + + fn corrupt_nested_layout<'b>(entry: &Placed<'b>, field: usize) -> Placed<'b> { + let mut invalid = Placed { + tensor: entry.tensor, + name_offset: entry.name_offset, + n_elements: entry.n_elements, + n_padded: entry.n_padded, + section_offset: entry.section_offset, + section_bytes: entry.section_bytes, + scales_offset: entry.scales_offset, + books_offset: entry.books_offset, + planes_offset: entry.planes_offset, + plane_stride: entry.plane_stride, + payload_crc32: entry.payload_crc32, + }; + match field { + 0 => invalid.books_offset = invalid.section_offset, + 1 => invalid.planes_offset = invalid.books_offset, + _ => invalid.section_bytes = 0, + } + invalid + } + + #[cfg(unix)] + #[test] + fn section_writer_propagates_full_device_write_errors() { + let Ok(mut full) = OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut crc = !0u32; + let mut written = 0; + assert!(write_bytes(&mut full, &[1], &mut crc, &mut written).is_err()); + } + + fn reject_verified_spool( + path: &Path, + _plan: &NestedSectionPlan<'_>, + ) -> Result { + assert!(fs::metadata(path).unwrap().len() > 0); + Err("injected post-write verification failure".into()) + } + + #[test] + fn post_write_verification_failure_removes_the_unpublished_spool() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let root = test_dir("nested-verify-cleanup"); + let spool = root.join("candidate.section"); + let result = write_nested_section_with_verifier(&spool, &tensors[1], reject_verified_spool); + assert!(matches!( + result, + Err(error) if error.contains("post-write verification") + )); + assert!(!spool.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn archive_io_errors_propagate_for_payload_length_and_full_device() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let mut plan = ArchivePlan::build(&source, &tensors).unwrap(); + let root = test_dir("write-payload-length"); + let mut file = File::create(root.join("archive.part")).unwrap(); + assert!( + write_payloads(&mut file, &mut plan.placed, plan.archive_bytes + 1, false).is_err() + ); + if let Ok(mut full) = OpenOptions::new().write(true).open("/dev/full") { + assert!(plan.write(&mut full, &source, &tensors, false).is_err()); + let directory = archive_directory(&plan.placed, plan.directory_bytes).unwrap(); + assert!( + write_archive_header(&mut full, &source, tensors.len(), &plan, &directory).is_err() + ); + } + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn archive_plan_propagates_position_and_name_write_errors() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let mut plan = ArchivePlan::build(&source, &tensors).unwrap(); + let mut position_error = FaultArchiveOutput { + fail_seek_at: Some(1), + ..FaultArchiveOutput::default() + }; + assert!( + plan.write(&mut position_error, &source, &tensors, false) + .is_err() + ); + let mut name_error = FaultArchiveOutput { + fail_write_at: Some(1), + ..FaultArchiveOutput::default() + }; + assert!( + plan.write(&mut name_error, &source, &tensors, false) + .is_err() + ); + let mut length_error = FaultArchiveOutput { + fail_set_len: true, + ..FaultArchiveOutput::default() + }; + assert!( + plan.write(&mut length_error, &source, &tensors, false) + .is_err() + ); + } + + #[test] + fn archive_plan_writes_complete_archive_through_output_contract() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let mut plan = ArchivePlan::build(&source, &tensors).unwrap(); + let mut output = FaultArchiveOutput::default(); + plan.write(&mut output, &source, &tensors, false).unwrap(); + assert_eq!(output.archive_len().unwrap(), plan.archive_bytes); + } + + #[test] + fn archive_plan_file_adapter_propagates_length_seek_and_write_errors() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let mut plan = ArchivePlan::build(&source, &tensors).unwrap(); + let root = test_dir("archive-plan-file-errors"); + for operation in [ + ArchiveOutputOperation::SetLength, + ArchiveOutputOperation::Length, + ArchiveOutputOperation::Seek, + ArchiveOutputOperation::Write, + ] { + let mut output = File::create(root.join("archive.part")).unwrap(); + fail_archive_output_at(operation, 1); + assert!(plan.write(&mut output, &source, &tensors, false).is_err()); + } + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn archive_header_propagates_each_position_error() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let plan = ArchivePlan::build(&source, &tensors).unwrap(); + let directory = archive_directory(&plan.placed, plan.directory_bytes).unwrap(); + assert_header_seek_failures(&source, &tensors, &plan, &directory); + assert_header_write_and_sync_failures(&source, &tensors, &plan, &directory); + } + + fn assert_header_seek_failures( + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], + plan: &ArchivePlan<'_>, + directory: &[u8], + ) { + for fail_seek_at in [1, 2] { + let mut output = FaultArchiveOutput { + fail_seek_at: Some(fail_seek_at), + ..FaultArchiveOutput::default() + }; + assert!( + write_archive_header(&mut output, source, tensors.len(), plan, directory).is_err() + ); + } + } + + fn assert_header_write_and_sync_failures( + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], + plan: &ArchivePlan<'_>, + directory: &[u8], + ) { + for output in [ + FaultArchiveOutput { + fail_write_at: Some(1), + ..FaultArchiveOutput::default() + }, + FaultArchiveOutput { + fail_write_at: Some(2), + ..FaultArchiveOutput::default() + }, + FaultArchiveOutput { + fail_sync: true, + ..FaultArchiveOutput::default() + }, + ] { + let mut output = output; + assert!( + write_archive_header(&mut output, source, tensors.len(), plan, directory).is_err() + ); + } + } + + #[test] + fn archive_header_file_adapter_propagates_each_io_error() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let plan = ArchivePlan::build(&source, &tensors).unwrap(); + let directory = archive_directory(&plan.placed, plan.directory_bytes).unwrap(); + let root = test_dir("archive-header-file-errors"); + for (operation, call) in [ + (ArchiveOutputOperation::Seek, 1), + (ArchiveOutputOperation::Seek, 2), + (ArchiveOutputOperation::Write, 1), + (ArchiveOutputOperation::Write, 2), + (ArchiveOutputOperation::Sync, 1), + ] { + let mut output = File::create(root.join("archive.part")).unwrap(); + fail_archive_output_at(operation, call); + assert!( + write_archive_header(&mut output, &source, tensors.len(), &plan, &directory) + .is_err() + ); + } + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn nested_spool_output_propagates_length_and_sync_errors() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + for output in [ + FaultArchiveOutput { + fail_len: true, + ..FaultArchiveOutput::default() + }, + FaultArchiveOutput { + fail_sync: true, + ..FaultArchiveOutput::default() + }, + ] { + let mut output = output; + assert!(write_nested_spool_output(&mut output, &plan).is_err()); + } + let mut output = FaultArchiveOutput::default(); + write_nested_spool_output(&mut output, &plan).unwrap(); + assert_eq!(output.archive_len().unwrap(), plan.layout.section_bytes); + } + + #[test] + fn payload_writer_propagates_archive_length_metadata_error() { + let input = reference_input(); + let source = reference_source(&input); + let tensors = reference_tensors(&input); + let mut plan = ArchivePlan::build(&source, &tensors).unwrap(); + let mut output = FaultArchiveOutput { + fail_len: true, + ..FaultArchiveOutput::default() + }; + assert!(write_payloads(&mut output, &mut plan.placed, plan.archive_bytes, false).is_err()); + } + + #[test] + fn section_writer_propagates_position_error() { + let input = reference_input(); + let tensors = reference_tensors(&input); + let mut output = FaultArchiveOutput { + fail_seek_at: Some(1), + ..FaultArchiveOutput::default() + }; + assert!(write_section(&mut output, &placed(&tensors[0])).is_err()); + } + + fn write_orphan_retry_fixture(root: &Path) -> (PathBuf, PathBuf, Vec, kar::Summary) { + let destination = root.join("archive.kar"); + let orphan = root.join("archive.kar.part"); + let partial = b"partial archive from interrupted attempt".to_vec(); + fs::write(&orphan, &partial).unwrap(); + let raw = [0.0f32; 4].map(f32::to_le_bytes).concat(); + let digest = Sha256::digest(&raw).into(); let source = SourceIdentity { + name: "orphan-retry", + architecture: "fixture", + builder: "test", + digest, + total_elements: 4, + bytes: raw.len() as u64, + }; + let tensors = [Tensor { + name: "weight", + dims: &[4], + source_dtype: 0, + source_digest: digest, + source_offset: 0, + data: TensorData::Raw(&raw), + }]; + let summary = write_archive(&destination, &source, &tensors).unwrap(); + (destination, orphan, partial, summary) + } + + #[cfg(unix)] + struct ReapFixture { + root: PathBuf, + destination: PathBuf, + orphan: PathBuf, + unrelated: PathBuf, + recent: PathBuf, + published: PathBuf, + published_temp: PathBuf, + active: PathBuf, + active_file: File, + } + + #[cfg(unix)] + fn make_reap_fixture() -> ReapFixture { + let root = test_dir("reap"); + let destination = root.join("archive.kar"); + let orphan = archive_temp_path(&destination, 1); + write_temp(&orphan); + let unrelated = archive_temp_path(&root.join("other.kar"), 1); + write_temp(&unrelated); + let recent = archive_temp_path(&destination, 3); + fs::write(&recent, b"recent partial").unwrap(); + let published = root.join("published.kar"); + let published_temp = archive_temp_path(&published, 1); + fs::write(&published_temp, b"linked archive").unwrap(); + fs::hard_link(&published_temp, &published).unwrap(); + let active = archive_temp_path(&destination, 2); + let active_file = archive_temp_options().open(&active).unwrap(); + active_file.try_lock().unwrap(); + ReapFixture { + root, + destination, + orphan, + unrelated, + recent, + published, + published_temp, + active, + active_file, + } + } + + #[cfg(unix)] + fn verify_reap_fixture(fixture: ReapFixture) { + reap_stale_archive_temps(&fixture.destination).unwrap(); + reap_stale_archive_temps(&fixture.published).unwrap(); + assert!(!fixture.orphan.exists() && !fixture.recent.exists()); + assert!(fixture.unrelated.exists() && fixture.active.exists()); + assert!(!fixture.published_temp.exists()); + assert_eq!(fs::read(&fixture.published).unwrap(), b"linked archive"); + drop(fixture.active_file); + fs::remove_dir_all(fixture.root).unwrap(); + } + + #[test] + fn post_publish_temporary_cleanup_error_is_retried_without_losing_archive() { + let root = test_dir("publish"); + let temporary = root.join("candidate.part"); + let destination = root.join("archive.kar"); + fs::write(&temporary, b"verified archive").unwrap(); + assert!( + publish_verified_archive( + &temporary, + &destination, + simple_archive_summary(16), + fail_cleanup + ) + .is_ok() + ); + assert_eq!(fs::read(&destination).unwrap(), b"verified archive"); + assert!(temporary.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn invalid_archive_temp_is_removed_before_publication() { + let root = test_dir("invalid-temp"); + let temporary = root.join("candidate.part"); + let destination = root.join("archive.kar"); + fs::write(&temporary, b"not a KAR archive").unwrap(); + assert!(verify_and_publish(&temporary, &destination, remove_archive_temp,).is_err()); + assert!(!temporary.exists()); + assert!(!destination.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn verified_archive_publication_never_replaces_existing_destination() { + let root = test_dir("no-replace"); + let destination = root.join("archive.kar"); + let temporary = root.join("candidate.part"); + fs::write(&destination, b"existing archive").unwrap(); + fs::write(&temporary, b"new archive").unwrap(); + assert!( + publish_verified_archive( + &temporary, + &destination, + simple_archive_summary(11), + remove_archive_temp + ) + .is_err() + ); + assert_eq!(fs::read(destination).unwrap(), b"existing archive"); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn reaps_only_unlocked_owned_temps_for_the_same_archive() { + verify_reap_fixture(make_reap_fixture()); + } + + #[cfg(unix)] + #[test] + fn reaper_preserves_replaced_paths_and_unpublished_hard_links() { + let root = test_dir("reaper-replacement"); + let destination = root.join("archive.kar"); + let (temporary, mut active) = create_archive_temp(&destination).unwrap(); + active.write_all(b"owned partial").unwrap(); + let before = active.metadata().unwrap(); + let replacement = root.join("replacement.part"); + fs::write(&replacement, b"new inode").unwrap(); + fs::remove_file(&temporary).unwrap(); + fs::rename(&replacement, &temporary).unwrap(); + unlink_if_same_archive_temp(&temporary, &destination, &before, &active).unwrap(); + assert_eq!(fs::read(&temporary).unwrap(), b"new inode"); + + let linked = archive_temp_path(&destination, 1); + fs::write(&linked, b"shared inode").unwrap(); + let unrelated = root.join("unrelated.link"); + fs::hard_link(&linked, &unrelated).unwrap(); + reap_archive_temp(&linked, &destination).unwrap(); + assert!(linked.exists() && unrelated.exists()); + drop(active); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn reaper_ignores_symlinks_and_tolerates_paths_removed_after_scan() { + let root = test_dir("reaper-disappeared"); + let destination = root.join("archive.kar"); + let target = root.join("target"); + let symlink = archive_temp_path(&destination, 0); + fs::write(&target, b"keep target").unwrap(); + std::os::unix::fs::symlink(&target, &symlink).unwrap(); + reap_archive_temp(&symlink, &destination).unwrap(); + assert!( + fs::symlink_metadata(&symlink) + .unwrap() + .file_type() + .is_symlink() + ); + + let path = archive_temp_path(&destination, 1); + let file = archive_temp_options().open(&path).unwrap(); + let before = file.metadata().unwrap(); + fs::remove_file(&path).unwrap(); + assert!( + reap_locked_archive_temp(&path, &destination, &before, archive_temp_options()).is_ok() + ); + assert!(unlink_if_same_archive_temp(&path, &destination, &before, &file).is_ok()); + drop(file); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn reaper_preserves_a_temp_owned_by_another_uid() { + use std::os::unix::ffi::OsStrExt; + + if unsafe { libc::geteuid() } != 0 { + return; + } + let root = test_dir("foreign-temp-owner"); + let destination = root.join("archive.kar"); + let temporary = archive_temp_path(&destination, 1); + fs::write(&temporary, b"foreign owner data").unwrap(); + let path = std::ffi::CString::new(temporary.as_os_str().as_bytes()).unwrap(); + assert_eq!(unsafe { libc::chown(path.as_ptr(), 65534, 65534) }, 0); + reap_archive_temp(&temporary, &destination).unwrap(); + assert_eq!(fs::read(&temporary).unwrap(), b"foreign owner data"); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn reaper_fails_closed_when_a_scanned_temp_becomes_a_symlink() { + let root = test_dir("temp-symlink-race"); + let destination = root.join("archive.kar"); + let path = archive_temp_path(&destination, 0); + let target = root.join("target.part"); + fs::write(&target, b"keep target").unwrap(); + let before = fs::metadata(&target).unwrap(); + std::os::unix::fs::symlink(&target, &path).unwrap(); + let mut options = OpenOptions::new(); + options + .read(true) + .write(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + assert!(reap_locked_archive_temp(&path, &destination, &before, options).is_err()); + assert!( + fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink() + ); + assert_eq!(fs::read(target).unwrap(), b"keep target"); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn archive_temp_matching_requires_the_expected_private_slot_name() { + let root = test_dir("temp-name"); + let destination = root.join("archive.kar"); + let expected = archive_temp_path(&destination, 2); + assert!(is_archive_temp_name( + &destination, + expected.file_name().unwrap() + )); + for name in [ + ".strata-kar-invalid-2.part", + ".strata-kar-x-255.part", + "other.part", + ] { + assert!(!is_archive_temp_name( + &destination, + std::ffi::OsStr::new(name) + )); + } + let missing_suffix = expected.file_name().unwrap().to_string_lossy(); + assert!(!is_archive_temp_name( + &destination, + std::ffi::OsStr::new(missing_suffix.trim_end_matches(".part")) + )); + let (path, file) = create_archive_temp(&destination).unwrap(); + assert!(archive_temp_path_matches(&path, &file)); + fs::remove_file(&path).unwrap(); + assert!(!archive_temp_path_matches(&path, &file)); + drop(file); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn failed_writer_cleanup_holds_lock_across_reaper_and_slot_reuse() { + let root = std::env::temp_dir().join(format!( + "strata-kar-cleanup-race-{}-{}", + std::process::id(), + ARCHIVE_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&root).unwrap(); + let destination = root.join("archive.kar"); + let (temporary, mut writer) = create_archive_temp(&destination).unwrap(); + assert_eq!(temporary, archive_temp_path(&destination, 0)); + writer.write_all(b"failed writer partial").unwrap(); + + let reaper_destination = destination.clone(); + std::thread::spawn(move || reap_stale_archive_temps(&reaper_destination)) + .join() + .unwrap() + .unwrap(); + assert!(temporary.exists()); + + remove_archive_temp_locked(&temporary, &writer).unwrap(); + assert!(!temporary.exists()); + let (replacement, mut next_writer) = create_archive_temp(&destination).unwrap(); + assert_eq!(replacement, temporary); + next_writer.write_all(b"replacement writer").unwrap(); + + remove_archive_temp_locked(&replacement, &writer).unwrap(); + assert_eq!(fs::read(&replacement).unwrap(), b"replacement writer"); + + drop(next_writer); + drop(writer); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn archive_temp_slots_bound_crash_left_file_count() { + let root = std::env::temp_dir().join(format!( + "strata-kar-slots-{}-{}", + std::process::id(), + ARCHIVE_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&root).unwrap(); + let destination = root.join("archive.kar"); + let mut active = Vec::new(); + for _ in 0..ARCHIVE_TEMP_SLOTS { + active.push(create_archive_temp(&destination).unwrap()); + } + assert!(create_archive_temp(&destination).is_err()); + drop(active); + fs::remove_dir_all(root).unwrap(); + } + + fn write_temp(path: &Path) { + fs::write(path, b"crash-left temporary").unwrap(); + } + + struct CanonicalNestedFixture { + root: PathBuf, + streamed: PathBuf, + spool: PathBuf, + native_spool: PathBuf, + source: SourceIdentity<'static>, + source_digest: [u8; 32], + reference: Vec, + section: Vec, + } + + fn canonical_nested_source() -> SourceIdentity<'static> { + SourceIdentity { name: "nested-fixture", architecture: "qwen35", builder: "strata-next-test", digest: Sha256::digest(b"source").into(), total_elements: 32, bytes: 6, - }; - let book1 = [0xbc00, 0x3c00]; - let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; - let books: [&[u16]; 2] = [&book1, &book2]; - let plane1 = [0xaaaa_aaaa]; - let plane2 = [0x5555_5555]; - let planes: [&[u32]; 2] = [&plane1, &plane2]; - let source_digest: [u8; 32] = Sha256::digest(b"weights").into(); - let original = - std::env::temp_dir().join(format!("strata-nested-{}.kar", std::process::id())); - let streamed = - std::env::temp_dir().join(format!("strata-nested-stream-{}.kar", std::process::id())); - let spool = - std::env::temp_dir().join(format!("strata-nested-spool-{}.bin", std::process::id())); - let _ = fs::remove_file(&original); - let _ = fs::remove_file(&streamed); - let nested = [Tensor { + } + } + + fn canonical_nested_tensor<'a>( + source_digest: [u8; 32], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], + ) -> Tensor<'a> { + Tensor { name: "expert", dims: &[32], source_dtype: 1, @@ -1055,84 +4048,154 @@ mod tests { planes_min: 1, planes_max: 2, scales: &[0x3c00], - books: &books, - planes: &planes, + books, + planes, }, - }]; - write_archive(&original, &source, &nested).unwrap(); - let reference = fs::read(&original).unwrap(); - let section_offset = - u64::from_le_bytes(reference[256 + 112..256 + 120].try_into().unwrap()) as usize; - let section_bytes = - u64::from_le_bytes(reference[256 + 120..256 + 128].try_into().unwrap()) as usize; - let section = &reference[section_offset..section_offset + section_bytes]; - let native_spool = std::env::temp_dir().join(format!( - "strata-nested-native-spool-{}.bin", - std::process::id() - )); - let _ = fs::remove_file(&native_spool); - let native_section = write_nested_section(&native_spool, &nested[0]).unwrap(); - assert_eq!(native_section.bytes, section_bytes as u64); - assert_eq!(fs::read(&native_spool).unwrap(), section); - let expected_digest: [u8; 32] = Sha256::digest(section).into(); - assert_eq!(native_section.digest, expected_digest); - let mut spool_bytes = vec![0xabu8; 11]; - spool_bytes.extend_from_slice(section); - fs::write(&spool, &spool_bytes).unwrap(); - let digest: [u8; 32] = Sha256::digest(section).into(); - let file_tensor = |digest| { - [Tensor { - name: "expert", - dims: &[32], - source_dtype: 1, - source_digest, - source_offset: 0, - data: TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - levels: 2, - path: &spool, - offset: 11, - bytes: section_bytes as u64, - digest, - }, - }] - }; - write_archive(&streamed, &source, &file_tensor(digest)).unwrap(); - assert_eq!(fs::read(&streamed).unwrap(), reference); - fs::remove_file(&streamed).unwrap(); + } + } - spool_bytes[11] = 0; - spool_bytes[12] = 0x7c; - fs::write(&spool, &spool_bytes).unwrap(); + fn create_canonical_nested_fixture() -> CanonicalNestedFixture { + let root = test_dir("canonical-nested"); + let original = root.join("reference.kar"); + let streamed = root.join("streamed.kar"); + let spool = root.join("section.bin"); + let native_spool = root.join("native.bin"); + let source = canonical_nested_source(); + let source_digest = Sha256::digest(b"weights").into(); + let books = [&[0xbc00, 0x3c00][..], &[0xbe00, 0xb800, 0x3800, 0x3e00][..]]; + let planes = [&[0xaaaa_aaaa][..], &[0x5555_5555][..]]; + let tensor = canonical_nested_tensor(source_digest, &books, &planes); + write_archive(&original, &source, std::slice::from_ref(&tensor)).unwrap(); + let reference = fs::read(&original).unwrap(); + let section = nested_reference_section(&reference); + let native = write_nested_section(&native_spool, &tensor).unwrap(); + assert_eq!(native.bytes, section.len() as u64); + assert_eq!(fs::read(&native_spool).unwrap(), section); + assert_eq!(native.digest, Sha256::digest(§ion).as_slice()); + write_section_spool(&spool, §ion); + CanonicalNestedFixture { + root, + streamed, + spool, + native_spool, + source, + source_digest, + reference, + section, + } + } + + fn nested_reference_section(reference: &[u8]) -> Vec { + let offset = u64::from_le_bytes(reference[368..376].try_into().unwrap()) as usize; + let bytes = u64::from_le_bytes(reference[376..384].try_into().unwrap()) as usize; + reference[offset..offset + bytes].to_vec() + } + + fn write_section_spool(path: &Path, section: &[u8]) { + let mut bytes = vec![0xabu8; 11]; + bytes.extend_from_slice(section); + fs::write(path, bytes).unwrap(); + } + + fn canonical_nested_file_tensor<'a>( + fixture: &'a CanonicalNestedFixture, + digest: [u8; 32], + ) -> Tensor<'a> { + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: fixture.source_digest, + source_offset: 0, + data: TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: &fixture.spool, + offset: 11, + bytes: fixture.section.len() as u64, + digest, + }, + } + } + + fn assert_nested_file_rejected(fixture: &CanonicalNestedFixture, message: &str) { + let digest = Sha256::digest(&fixture.section).into(); + let tensor = canonical_nested_file_tensor(fixture, digest); assert!( - write_archive(&streamed, &source, &file_tensor(digest)) + write_archive(&fixture.streamed, &fixture.source, &[tensor]) .unwrap_err() - .contains("non-finite f16 scale") + .contains(message) ); - assert!(!streamed.exists()); - spool_bytes[11..11 + section_bytes].copy_from_slice(section); - spool_bytes[13] = 1; - fs::write(&spool, &spool_bytes).unwrap(); + assert!(!fixture.streamed.exists()); + } + + fn corrupt_nested_spool(fixture: &CanonicalNestedFixture, offset: usize, byte: u8) { + let mut bytes = vec![0xabu8; 11]; + bytes.extend_from_slice(&fixture.section); + bytes[offset] = byte; + fs::write(&fixture.spool, bytes).unwrap(); + } + + fn cleanup_canonical_nested_fixture(fixture: CanonicalNestedFixture) { + fs::remove_dir_all(fixture.root).unwrap(); + } + + #[test] + fn streams_canonical_nested_section_and_rejects_corruption() { + let fixture = create_canonical_nested_fixture(); + assert_streamed_nested_matches_reference(&fixture); + cleanup_canonical_nested_fixture(fixture); + } + + fn assert_streamed_nested_matches_reference(fixture: &CanonicalNestedFixture) { + let digest = Sha256::digest(&fixture.section).into(); + let tensor = canonical_nested_file_tensor(fixture, digest); + write_archive(&fixture.streamed, &fixture.source, &[tensor]).unwrap(); + assert_eq!(fs::read(&fixture.streamed).unwrap(), fixture.reference); + fs::remove_file(&fixture.streamed).unwrap(); + } + + #[test] + fn nested_file_archive_rejects_invalid_scale_and_codebook() { + let fixture = create_canonical_nested_fixture(); + corrupt_nested_spool(&fixture, 11, 0); + corrupt_nested_spool(&fixture, 12, 0x7c); + assert_nested_file_rejected(&fixture, "non-finite f16 scale"); + corrupt_nested_spool(&fixture, 27, 0); + corrupt_nested_spool(&fixture, 28, 0x7c); + assert_nested_file_rejected(&fixture, "non-finite f16 codebook"); + cleanup_canonical_nested_fixture(fixture); + } + + #[test] + fn nested_file_archive_rejects_padding_and_digest_corruption() { + let fixture = create_canonical_nested_fixture(); + corrupt_nested_spool(&fixture, 13, 1); + assert_nested_file_rejected(&fixture, "nonzero padding"); + write_section_spool(&fixture.spool, &fixture.section); + let tensor = canonical_nested_file_tensor(&fixture, [0; 32]); assert!( - write_archive(&streamed, &source, &file_tensor(digest)) - .unwrap_err() - .contains("nonzero padding") - ); - assert!(!streamed.exists()); - spool_bytes[11..11 + section_bytes].copy_from_slice(section); - fs::write(&spool, &spool_bytes).unwrap(); - assert!( - write_archive(&streamed, &source, &file_tensor([0; 32])) + write_archive(&fixture.streamed, &fixture.source, &[tensor]) .unwrap_err() .contains("nested section digest mismatch") ); - assert!(!streamed.exists()); - fs::remove_file(original).unwrap(); - fs::remove_file(spool).unwrap(); - fs::remove_file(native_spool).unwrap(); + assert!(!fixture.streamed.exists()); + cleanup_canonical_nested_fixture(fixture); + } + + #[test] + fn nested_file_archive_preserves_canonical_section_bytes_and_digest() { + let fixture = create_canonical_nested_fixture(); + let section = nested_reference_section(&fixture.reference); + assert_eq!(section, fixture.section); + let expected: [u8; 32] = Sha256::digest(§ion).into(); + assert_eq!(fs::read(&fixture.native_spool).unwrap(), section); + let streamed_digest: [u8; 32] = Sha256::digest(&fixture.section).into(); + assert_eq!(expected, streamed_digest); + cleanup_canonical_nested_fixture(fixture); } #[test] @@ -1210,36 +4273,52 @@ mod tests { fs::remove_dir_all(root).unwrap(); } - #[test] - fn archive_bytes_match_pinned_koference_reference_writer() { - // Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture. + const REFERENCE_BOOK1: [u16; 2] = [0xbc00, 0x3c00]; + const REFERENCE_BOOK2: [u16; 4] = [0xbe00, 0xb800, 0x3800, 0x3e00]; + const REFERENCE_PLANE1: [u32; 1] = [0xaaaa_aaaa]; + const REFERENCE_PLANE2: [u32; 1] = [0x5555_5555]; + + struct ReferenceInput { + raw: Vec, + source_bytes: Vec, + books: [&'static [u16]; 2], + planes: [&'static [u32]; 2], + } + + fn reference_input() -> ReferenceInput { let raw = (0..32) .flat_map(|value| (value as f32).to_le_bytes()) .collect::>(); let mut source_bytes = raw.clone(); source_bytes.extend_from_slice(b"weights"); - let source = SourceIdentity { + ReferenceInput { + raw, + source_bytes, + books: [&REFERENCE_BOOK1, &REFERENCE_BOOK2], + planes: [&REFERENCE_PLANE1, &REFERENCE_PLANE2], + } + } + + fn reference_source(input: &ReferenceInput) -> SourceIdentity<'_> { + SourceIdentity { name: "synthetic", architecture: "qwen35", builder: "kar_container.py/2", - digest: Sha256::digest(&source_bytes).into(), + digest: Sha256::digest(&input.source_bytes).into(), total_elements: 64, - bytes: source_bytes.len() as u64, - }; - let book1 = [0xbc00, 0x3c00]; - let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; - let books: [&[u16]; 2] = [&book1, &book2]; - let plane1 = [0xaaaa_aaaa]; - let plane2 = [0x5555_5555]; - let planes: [&[u32]; 2] = [&plane1, &plane2]; - let tensors = [ + bytes: input.source_bytes.len() as u64, + } + } + + fn reference_tensors(input: &ReferenceInput) -> [Tensor<'_>; 2] { + [ Tensor { name: "norm", dims: &[32], source_dtype: 0, - source_digest: Sha256::digest(&raw).into(), + source_digest: Sha256::digest(&input.raw).into(), source_offset: 0, - data: TensorData::Raw(&raw), + data: TensorData::Raw(&input.raw), }, Tensor { name: "expert", @@ -1253,33 +4332,101 @@ mod tests { planes_min: 1, planes_max: 2, scales: &[0x3c00], - books: &books, - planes: &planes, + books: &input.books, + planes: &input.planes, }, }, - ]; - let path = - std::env::temp_dir().join(format!("strata-kar-writer-{}.kar", std::process::id())); - let _ = fs::remove_file(&path); - let summary = write_archive(&path, &source, &tensors).unwrap(); + ] + } + + fn reference_raw_file_tensors<'a>( + input: &'a ReferenceInput, + path: &'a Path, + ) -> [Tensor<'a>; 2] { + [ + reference_raw_file_tensor(input, path), + reference_nested_memory_tensor(input), + ] + } + + fn reference_raw_file_tensor<'a>(input: &'a ReferenceInput, path: &'a Path) -> Tensor<'a> { + Tensor { + name: "norm", + dims: &[32], + source_dtype: 0, + source_digest: Sha256::digest(&input.raw).into(), + source_offset: 0, + data: TensorData::RawFile { + path, + offset: 17, + bytes: input.raw.len() as u64, + }, + } + } + + fn reference_nested_memory_tensor(input: &ReferenceInput) -> Tensor<'_> { + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &input.books, + planes: &input.planes, + }, + } + } + + fn write_reference_archive(path: &Path, input: &ReferenceInput) -> (Vec, kar::Summary) { + let summary = + write_archive(path, &reference_source(input), &reference_tensors(input)).unwrap(); assert_eq!(summary.archive_bytes, 1280); assert_eq!(summary.tensor_count, 2); assert_eq!(summary.accounted_bpw, 160.0); - let archive = fs::read(&path).unwrap(); + (fs::read(path).unwrap(), summary) + } + + #[test] + fn archive_bytes_match_pinned_koference_reference_writer() { + let root = test_dir("reference"); + let path = root.join("archive.kar"); + let input = reference_input(); + let (archive, _) = write_reference_archive(&path, &input); assert_eq!( hex::encode(Sha256::digest(&archive)), "013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2" ); - assert!(write_archive(&path, &source, &tensors).is_err()); - let other = path.with_file_name(format!("strata-kar-stale-{}.kar", std::process::id())); - let stale = other.with_file_name(format!( - "{}.part", - other.file_name().unwrap().to_string_lossy() - )); - fs::write(&stale, b"previous work").unwrap(); - assert!(write_archive(&other, &source, &tensors).is_err()); - assert_eq!(fs::read(&stale).unwrap(), b"previous work"); - fs::remove_file(stale).unwrap(); + assert!( + write_archive(&path, &reference_source(&input), &reference_tensors(&input)).is_err() + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn pre_publish_orphan_does_not_change_reference_archive_bytes() { + let root = test_dir("stale-part"); + let input = reference_input(); + let (expected, _) = write_reference_archive(&root.join("expected.kar"), &input); + let other = root.join("retry.kar"); + let stale = root.join("retry.kar.part"); + fs::write(&stale, b"partial archive left by a crashed attempt").unwrap(); + assert_eq!(write_reference_archive(&other, &input).0, expected); + assert_eq!( + fs::read(stale).unwrap(), + b"partial archive left by a crashed attempt" + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn rejects_non_finite_nested_reference_scale() { + let input = reference_input(); let invalid = [Tensor { name: "bad-scale", dims: &[32], @@ -1292,68 +4439,68 @@ mod tests { planes_min: 1, planes_max: 2, scales: &[0x7c00], - books: &books, - planes: &planes, + books: &input.books, + planes: &input.planes, }, }]; + let path = test_dir("bad-scale").join("invalid.kar"); assert!( - write_archive(&other, &source, &invalid) + write_archive(&path, &reference_source(&input), &invalid) .unwrap_err() .contains("non-finite f16 scale") ); - assert!(!other.exists()); - let raw_file = - path.with_file_name(format!("strata-kar-raw-input-{}.bin", std::process::id())); - let mut padded_raw = vec![0u8; 17]; - padded_raw.extend_from_slice(&raw); - fs::write(&raw_file, &padded_raw).unwrap(); - let streamed_tensors = [ - Tensor { - name: "norm", - dims: &[32], - source_dtype: 0, - source_digest: Sha256::digest(&raw).into(), - source_offset: 0, - data: TensorData::RawFile { - path: &raw_file, - offset: 17, - bytes: raw.len() as u64, - }, - }, - Tensor { - name: "expert", - dims: &[32], - source_dtype: 1, - source_digest: Sha256::digest(b"weights").into(), - source_offset: 0, - data: TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &[0x3c00], - books: &books, - planes: &planes, - }, - }, - ]; - let streamed = - path.with_file_name(format!("strata-kar-streamed-{}.kar", std::process::id())); - let _ = fs::remove_file(&streamed); - write_archive(&streamed, &source, &streamed_tensors).unwrap(); - assert_eq!(fs::read(&streamed).unwrap(), archive); - padded_raw[17] ^= 1; - fs::write(&raw_file, padded_raw).unwrap(); - let corrupt = path.with_file_name(format!("strata-kar-corrupt-{}.kar", std::process::id())); - let _ = fs::remove_file(&corrupt); + assert!(!path.exists()); + fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn raw_file_payload_matches_reference_and_rejects_digest_mismatch() { + let root = test_dir("raw-file"); + let input = reference_input(); + let (expected, _) = write_reference_archive(&root.join("expected.kar"), &input); + let raw_path = root.join("source.bin"); + write_padded_raw(&raw_path, &input.raw); + let tensors = reference_raw_file_tensors(&input, &raw_path); + let streamed = root.join("streamed.kar"); + write_archive(&streamed, &reference_source(&input), &tensors).unwrap(); + assert_eq!(fs::read(&streamed).unwrap(), expected); + assert_corrupted_raw_file_is_rejected(&root, &input, &raw_path, &tensors); + fs::remove_dir_all(root).unwrap(); + } + + fn write_padded_raw(path: &Path, raw: &[u8]) { + let mut bytes = vec![0u8; 17]; + bytes.extend_from_slice(raw); + fs::write(path, bytes).unwrap(); + } + + fn assert_corrupted_raw_file_is_rejected( + root: &Path, + input: &ReferenceInput, + path: &Path, + tensors: &[Tensor<'_>; 2], + ) { + let mut bytes = fs::read(path).unwrap(); + bytes[17] ^= 1; + fs::write(path, bytes).unwrap(); + let corrupt = root.join("corrupt.kar"); assert!( - write_archive(&corrupt, &source, &streamed_tensors) + write_archive(&corrupt, &reference_source(input), tensors) .unwrap_err() .contains("RAW source digest mismatch") ); assert!(!corrupt.exists()); - fs::remove_file(streamed).unwrap(); - fs::remove_file(raw_file).unwrap(); - fs::remove_file(path).unwrap(); + } + + #[test] + fn retry_after_pre_publish_orphan_preserves_stale_partial_file() { + let root = test_dir("orphan-retry"); + let (destination, orphan, partial, summary) = write_orphan_retry_fixture(&root); + assert_eq!( + kar::verify(&destination).unwrap().archive_bytes, + summary.archive_bytes + ); + assert_eq!(fs::read(&orphan).unwrap(), partial); + fs::remove_dir_all(root).unwrap(); } } diff --git a/control-plane/src/model_pipeline.rs b/control-plane/src/model_pipeline.rs index b15c5d7e..6a7f14f6 100644 --- a/control-plane/src/model_pipeline.rs +++ b/control-plane/src/model_pipeline.rs @@ -139,7 +139,7 @@ impl StreamedEnsureRequest<'_> { } fn reuse_existing(&self, metadata: fs::Metadata) -> Result> { - if !metadata.is_file() || metadata.file_type().is_symlink() { + if metadata.file_type().is_symlink() || !metadata.is_file() { return Err("existing KAR path must be a regular file".into()); } let summary = if prepare_preview::has_pending_streamed_publication(self.archive)? { @@ -266,8 +266,93 @@ fn preflight_existing_shards( #[cfg(test)] mod tests { use super::*; + use sha2::{Digest, Sha256}; use std::time::{SystemTime, UNIX_EPOCH}; + fn gguf_string(bytes: &mut Vec, value: &str) { + bytes.extend_from_slice(&(value.len() as u64).to_le_bytes()); + bytes.extend_from_slice(value.as_bytes()); + } + + fn f32_shard(name: &str, values: &[f32]) -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + gguf_string(&mut bytes, "general.architecture"); + bytes.extend_from_slice(&8u32.to_le_bytes()); + gguf_string(&mut bytes, "qwen35"); + gguf_string(&mut bytes, name); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&(values.len() as u64).to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(values.iter().flat_map(|value| value.to_le_bytes())); + bytes + } + + fn iq3_shard() -> Vec { + let mut payload = vec![0u8; crate::iq3_s::BLOCK_BYTES]; + payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + gguf_string(&mut bytes, "expert"); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&256u64.to_le_bytes()); + bytes.extend_from_slice(&21u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(payload); + bytes + } + + fn temporary_directory(label: &str) -> std::path::PathBuf { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!("strata-{label}-{}-{stamp}", std::process::id())) + } + + fn local_manifest(directory: &Path) -> model::Manifest { + let payload = (0..64) + .map(|number| [-1.0, -0.25, 0.25, 1.0][number % 4]) + .collect::>(); + let shard = f32_shard("dense", &payload); + fs::write(directory.join("tiny.gguf"), &shard).unwrap(); + let iq3 = iq3_shard(); + fs::write(directory.join("expert.gguf"), &iq3).unwrap(); + model::Manifest { + schema_version: 1, + files: [("tiny.gguf", shard), ("expert.gguf", iq3)] + .into_iter() + .map(|(name, bytes)| model::ModelFile { + name: name.into(), + url: format!("https://example.invalid/{name}"), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(bytes)), + }) + .collect(), + } + } + + fn ple_manifest(directory: &Path) -> model::Manifest { + let mut manifest = local_manifest(directory); + let values = (0..512).map(|value| value as f32).collect::>(); + let bytes = f32_shard(stream_parts::PLE_TENSOR_NAME, &values); + fs::write(directory.join("ple.gguf"), &bytes).unwrap(); + manifest.files.push(model::ModelFile { + name: "ple.gguf".into(), + url: "https://example.invalid/ple.gguf".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(bytes)), + }); + manifest + } + #[tokio::test] async fn full_model_is_rejected_before_creating_a_download_directory() { let manifest = model::Manifest::from_spec("qwen-iq3-s").await.unwrap(); @@ -289,4 +374,193 @@ mod tests { assert!(error.contains("at most 64 MiB")); assert!(!source_dir.exists()); } + + #[test] + fn streamed_create_and_reuse_verify_local_archive() { + let directory = temporary_directory("pipeline"); + fs::create_dir(&directory).unwrap(); + let manifest = local_manifest(&directory); + let archive = directory.join("tiny.kar"); + let request = StreamedEnsureRequest { + manifest: &manifest, + source_dir: &directory, + archive: &archive, + levels: 2, + ple_part_elements: None, + }; + let created = request.create_archive().unwrap(); + assert!(matches!(created, PreviewOutcome::Created(_))); + let metadata = fs::metadata(&archive).unwrap(); + let reused = request.reuse_existing(metadata).unwrap(); + assert!(matches!(reused, PreviewOutcome::Reused(_))); + verify_streamed_archive(&manifest, &directory, &archive, 2, None).unwrap(); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn streamed_ple_create_verify_and_reuse_keep_the_partition_policy() { + let directory = temporary_directory("pipeline-ple"); + fs::create_dir(&directory).unwrap(); + let manifest = ple_manifest(&directory); + let archive = directory.join("ple.kar"); + let request = StreamedEnsureRequest { + manifest: &manifest, + source_dir: &directory, + archive: &archive, + levels: 2, + ple_part_elements: Some(128), + }; + let created = request.create_archive().unwrap(); + assert!(matches!(created, PreviewOutcome::Created(_))); + assert!(verify_streamed_archive(&manifest, &directory, &archive, 2, Some(128)).is_ok()); + assert!(matches!( + request.reuse_existing(fs::metadata(&archive).unwrap()), + Ok(PreviewOutcome::Reused(_)) + )); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn preflight_defers_existing_missing_and_resumable_shards() { + let directory = temporary_directory("preflight-incomplete"); + fs::create_dir(&directory).unwrap(); + let manifest = local_manifest(&directory); + let archive = directory.join("model.kar"); + assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok()); + fs::write(&archive, b"existing").unwrap(); + assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok()); + fs::remove_file(&archive).unwrap(); + fs::remove_file(directory.join("tiny.gguf")).unwrap(); + assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok()); + fs::write(directory.join("tiny.gguf"), b"short").unwrap(); + assert!(preflight_existing_shards(&manifest, &directory, &archive, 2).is_ok()); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn preflight_rejects_unsafe_names_and_non_regular_shards() { + let directory = temporary_directory("preflight-invalid"); + fs::create_dir(&directory).unwrap(); + let mut manifest = local_manifest(&directory); + manifest.files.truncate(1); + manifest.files[0].name = "../escape.gguf".into(); + assert!(preflight_existing_shards(&manifest, &directory, Path::new("out"), 2).is_err()); + manifest.files[0].name = "directory.gguf".into(); + fs::create_dir(directory.join("directory.gguf")).unwrap(); + assert!(preflight_existing_shards(&manifest, &directory, Path::new("out"), 2).is_err()); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn streamed_request_validation_and_archive_path_fail_closed() { + let manifest = model::Manifest { + schema_version: 1, + files: Vec::new(), + }; + let source_dir = Path::new("."); + let archive = Path::new("bad\0archive.kar"); + let invalid = StreamedEnsureRequest { + manifest: &manifest, + source_dir, + archive, + levels: 0, + ple_part_elements: None, + }; + assert!(invalid.validate().is_err()); + let invalid_limit = StreamedEnsureRequest { + levels: 2, + ple_part_elements: Some(31), + ..invalid + }; + assert!(invalid_limit.validate().is_err()); + assert!(invalid_limit.resolve_archive().is_err()); + } + + #[test] + fn existing_non_regular_archive_is_rejected() { + let dir = temporary_directory("non-regular"); + fs::create_dir(&dir).unwrap(); + let manifest = model::Manifest { + schema_version: 1, + files: Vec::new(), + }; + let request = StreamedEnsureRequest { + manifest: &manifest, + source_dir: &dir, + archive: &dir, + levels: 2, + ple_part_elements: None, + }; + assert!(request.reuse_existing(fs::metadata(&dir).unwrap()).is_err()); + assert!( + StreamedEnsureRequest { + manifest: &manifest, + source_dir: &dir, + archive: &dir, + levels: 2, + ple_part_elements: None, + } + .resolve_archive() + .is_err() + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn streamed_archive_resolution_handles_missing_and_symlink_paths() { + let dir = temporary_directory("archive-resolution"); + fs::create_dir(&dir).unwrap(); + let manifest = model::Manifest { + schema_version: 1, + files: Vec::new(), + }; + let archive = dir.join("missing.kar"); + assert_missing_archive_rejected(&manifest, &dir, &archive); + let target = dir.join("target"); + fs::write(&target, b"regular target").unwrap(); + let link = dir.join("link.kar"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert_symlink_archive_rejected(&manifest, &dir, &link); + fs::remove_dir_all(dir).unwrap(); + } + + #[cfg(unix)] + fn assert_missing_archive_rejected( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + ) { + let request = ensure_request(manifest, source_dir, archive); + assert!(request.resolve_archive().is_err()); + } + + #[cfg(unix)] + fn assert_symlink_archive_rejected( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + ) { + let request = ensure_request(manifest, source_dir, archive); + assert!( + request + .reuse_existing(fs::symlink_metadata(archive).unwrap()) + .is_err() + ); + } + + #[cfg(unix)] + fn ensure_request<'a>( + manifest: &'a model::Manifest, + source_dir: &'a Path, + archive: &'a Path, + ) -> StreamedEnsureRequest<'a> { + StreamedEnsureRequest { + manifest, + source_dir, + archive, + levels: 2, + ple_part_elements: None, + } + } } diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index bef0960d..4ca106d8 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -9,6 +9,9 @@ use std::{ sync::atomic::{AtomicU64, Ordering}, }; +#[cfg(test)] +use std::cell::RefCell; + use sha2::{Digest, Sha256}; use crate::{ @@ -23,6 +26,26 @@ const MAX_TENSORS: usize = 1000; const MAX_TENSOR_ELEMENTS: u64 = 1_000_000; static PROVENANCE_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); +#[cfg(test)] +thread_local! { + static PREVIEW_DESTINATION_RETARGET: RefCell> = const { RefCell::new(None) }; +} + +#[cfg(test)] +fn retarget_preview_parent_after_staging(link: PathBuf, target: PathBuf) { + PREVIEW_DESTINATION_RETARGET.with(|retarget| *retarget.borrow_mut() = Some((link, target))); +} + +#[cfg(test)] +fn apply_preview_destination_retarget() -> Result<(), String> { + let retarget = PREVIEW_DESTINATION_RETARGET.with(|value| value.borrow_mut().take()); + let Some((link, target)) = retarget else { + return Ok(()); + }; + fs::remove_file(&link).map_err(|error| error.to_string())?; + std::os::unix::fs::symlink(target, link).map_err(|error| error.to_string()) +} + pub(crate) fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result { if !derived_bytes.is_multiple_of(4) || !(1..=8).contains(&levels) { return Err("invalid KAR part F32 byte count or level".into()); @@ -184,6 +207,89 @@ struct PreparedTensor { section_digest: [u8; 32], } +struct PreviewTensorRequest<'a> { + name: &'a str, + dimensions: &'a [u64], + weights: &'a [f32], + source_digest: [u8; 32], + source_offset: u64, + section_path: &'a Path, + levels: u8, +} + +struct ShardedPrepareState { + architecture: Option, + maximum_relative_l2: f64, + prepared: Vec, + next_tensor: usize, +} + +impl ShardedPrepareState { + fn new(tensors: usize) -> Self { + Self { + architecture: None, + maximum_relative_l2: 0.0, + prepared: Vec::with_capacity(tensors), + next_tensor: 0, + } + } +} + +struct ShardedArchiveRequest<'a> { + identity: &'a derived_mixed::ShardedIdentity, + prepared: &'a [PreparedTensor], + architecture: &'a str, + destination: &'a Path, + levels: u8, + maximum_relative_l2: f64, +} + +struct ShardedShardRequest<'a> { + identity: &'a derived_mixed::ShardedIdentity, + shard: &'a derived_mixed::ShardIdentity, + source_dir: &'a Path, + staging: &'a StagingDir, + levels: u8, +} + +struct SingleSourcePrepare<'a> { + source_path: &'a Path, + destination: &'a Path, + levels: u8, + kind: PreviewKind, +} + +struct SingleSourceIdentity { + architecture: String, + source_name: String, + original_digest: [u8; 32], + source_bytes: u64, + derived: Option, +} + +struct SingleTensorProgress { + total_elements: u64, + maximum_relative_l2: f64, + prepared: Vec, +} + +struct SingleTensorRequest<'a> { + source: &'a SingleSourcePrepare<'a>, + index: &'a gguf::TensorIndex, + identity: &'a SingleSourceIdentity, + staging: &'a StagingDir, + tensor: &'a gguf::TensorInfo, + number: usize, +} + +struct SingleArchiveRequest<'a> { + source: &'a SingleSourcePrepare<'a>, + identity: &'a SingleSourceIdentity, + prepared: &'a [PreparedTensor], + total_elements: u64, + maximum_relative_l2: f64, +} + struct StreamedTensor { prepared: PreparedTensor, nested: bool, @@ -248,125 +354,280 @@ pub fn prepare_sharded( destination: &Path, levels: u8, ) -> Result { + let destination = kar_writer::canonical_archive_destination(destination)?; + validate_sharded_request(manifest, levels)?; + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + validate_sharded_identity(&identity)?; + let staging = create_preview_staging(&destination)?; + let mut state = ShardedPrepareState::new(identity.tensors.len()); + prepare_shard_tensors(&identity, source_dir, &staging, levels, &mut state)?; + let architecture = state + .architecture + .as_deref() + .ok_or("GGUF shards have no architecture")?; + write_sharded_preview(ShardedArchiveRequest { + identity: &identity, + prepared: &state.prepared, + architecture, + destination: &destination, + levels, + maximum_relative_l2: state.maximum_relative_l2, + }) +} + +fn validate_sharded_request(manifest: &Manifest, levels: u8) -> Result<(), String> { if !(1..=8).contains(&levels) { return Err("sharded preview requires 1..=8 KAR levels".into()); } - let total_source_bytes = manifest + let bytes = manifest .files .iter() .try_fold(0u64, |sum, file| sum.checked_add(file.size)) .ok_or("sharded GGUF source byte count overflow")?; - if total_source_bytes > MAX_SOURCE_BYTES { + if bytes > MAX_SOURCE_BYTES { return Err("sharded preview exceeds its 64 MiB source limit".into()); } - let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + Ok(()) +} + +fn validate_sharded_identity(identity: &derived_mixed::ShardedIdentity) -> Result<(), String> { if identity.tensors.is_empty() || identity.tensors.len() > MAX_TENSORS { return Err("sharded preview exceeds its tensor-count limit".into()); } - let staging_path = destination.with_file_name(format!( + Ok(()) +} + +fn create_preview_staging(destination: &Path) -> Result { + let name = destination + .file_name() + .ok_or("KAR destination has no file name")?; + let path = destination.with_file_name(format!( "{}.parts-{}", - destination - .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy(), + name.to_string_lossy(), std::process::id() )); - fs::create_dir(&staging_path).map_err(|error| error.to_string())?; - let staging = StagingDir(staging_path); - let mut architecture = None::; - let mut maximum_relative_l2 = 0.0f64; - let mut prepared = Vec::with_capacity(identity.tensors.len()); - let mut number = 0usize; + fs::create_dir(&path).map_err(|error| error.to_string())?; + #[cfg(test)] + apply_preview_destination_retarget()?; + Ok(StagingDir(path)) +} + +fn prepare_shard_tensors( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + staging: &StagingDir, + levels: u8, + state: &mut ShardedPrepareState, +) -> Result<(), String> { for shard in &identity.shards { - let path = source_dir.join(&shard.name); - let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - if let Some(shard_architecture) = index.summary.architecture.as_deref() { - if architecture - .as_deref() - .is_some_and(|expected| expected != shard_architecture) - { - return Err("GGUF shard architectures differ".into()); - } - architecture.get_or_insert_with(|| shard_architecture.to_owned()); - } - if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes - { - return Err("GGUF shard changed after identity derivation".into()); - } - let mut source = File::open(&path).map_err(|error| error.to_string())?; - for tensor in &index.tensors { - if tensor.dimensions.len() > 4 { - return Err(format!( - "{}: KAR preview supports up to four dimensions", - tensor.name - )); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |count, dim| count.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - if elements > MAX_TENSOR_ELEMENTS { - return Err("sharded preview exceeds its per-tensor element limit".into()); - } - let derived = &identity.tensors[number]; - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - source - .seek(SeekFrom::Start(absolute)) - .map_err(|error| error.to_string())?; - let mut raw = vec![0u8; tensor.bytes as usize]; - source - .read_exact(&mut raw) - .map_err(|error| error.to_string())?; - if derived.name != tensor.name - || derived.source_kind != tensor.kind - || Sha256::digest(&raw).as_slice() != derived.source_sha256 - || derived.derived_bytes != elements * 4 - { - return Err(format!( - "{}: sharded source tensor identity mismatch", - tensor.name - )); - } - let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; - let mut f32_digest = Sha256::new(); - for value in &weights { - f32_digest.update(value.to_le_bytes()); - } - if f32_digest.finalize().as_slice() != derived.f32_sha256 { - return Err(format!( - "{}: sharded derived F32 tensor mismatch", - tensor.name - )); - } - let section_path = staging.0.join(format!("{number:06}.section")); - let (coded, relative_l2) = encode_preview_tensor( - &tensor.name, - &tensor.dimensions, - &weights, - derived.f32_sha256, - derived.derived_offset, - §ion_path, + prepare_one_shard( + ShardedShardRequest { + identity, + shard, + source_dir, + staging, levels, - )?; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - prepared.push(coded); - number += 1; - } - if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes - || hash_file(&path)? != shard.gguf_sha256 - { - return Err(format!( - "{}: GGUF shard changed during preparation", - shard.name - )); - } + }, + state, + )?; } - let tensors = prepared + Ok(()) +} + +fn prepare_one_shard( + request: ShardedShardRequest<'_>, + state: &mut ShardedPrepareState, +) -> Result<(), String> { + let path = request.source_dir.join(&request.shard.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + check_shard_index(&index, request.shard, &mut state.architecture)?; + let mut source = File::open(&path).map_err(|error| error.to_string())?; + prepare_shard_records(&request, &index, &mut source, state)?; + verify_prepared_shard(&path, request.shard, &source) +} + +fn check_shard_index( + index: &gguf::TensorIndex, + shard: &derived_mixed::ShardIdentity, + architecture: &mut Option, +) -> Result<(), String> { + if let Some(actual) = index.summary.architecture.as_deref() { + if architecture + .as_deref() + .is_some_and(|expected| expected != actual) + { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert_with(|| actual.to_owned()); + } + if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes { + return Err("GGUF shard changed after identity derivation".into()); + } + Ok(()) +} + +fn prepare_shard_records( + request: &ShardedShardRequest<'_>, + index: &gguf::TensorIndex, + source: &mut File, + state: &mut ShardedPrepareState, +) -> Result<(), String> { + for tensor in &index.tensors { + prepare_sharded_record(request, index, tensor, source, state)?; + } + Ok(()) +} + +fn prepare_sharded_record( + request: &ShardedShardRequest<'_>, + index: &gguf::TensorIndex, + tensor: &gguf::TensorInfo, + source: &mut File, + state: &mut ShardedPrepareState, +) -> Result<(), String> { + let (weights, derived) = + read_sharded_weights(request.identity, index, tensor, source, state.next_tensor)?; + let section_path = request + .staging + .0 + .join(format!("{:06}.section", state.next_tensor)); + let (prepared, error) = encode_preview_tensor(PreviewTensorRequest { + name: &tensor.name, + dimensions: &tensor.dimensions, + weights: &weights, + source_digest: derived.f32_sha256, + source_offset: derived.derived_offset, + section_path: §ion_path, + levels: request.levels, + })?; + state.maximum_relative_l2 = state.maximum_relative_l2.max(error); + state.prepared.push(prepared); + state.next_tensor += 1; + Ok(()) +} + +fn read_sharded_weights<'a>( + identity: &'a derived_mixed::ShardedIdentity, + index: &gguf::TensorIndex, + tensor: &gguf::TensorInfo, + source: &mut File, + number: usize, +) -> Result<(Vec, &'a derived_mixed::TensorIdentity), String> { + let elements = sharded_tensor_elements(tensor)?; + let derived = identity + .tensors + .get(number) + .ok_or("sharded tensor identity is incomplete")?; + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + source + .seek(SeekFrom::Start(absolute)) + .map_err(|error| error.to_string())?; + let mut raw = vec![0u8; tensor.bytes as usize]; + source + .read_exact(&mut raw) + .map_err(|error| error.to_string())?; + verify_sharded_source(tensor, &raw, elements, derived)?; + let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; + verify_sharded_f32(tensor, &weights, derived)?; + Ok((weights, derived)) +} + +fn sharded_tensor_elements(tensor: &gguf::TensorInfo) -> Result { + if tensor.dimensions.len() > 4 { + return Err(format!( + "{}: KAR preview supports up to four dimensions", + tensor.name + )); + } + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |count, dim| count.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + if elements > MAX_TENSOR_ELEMENTS { + return Err("sharded preview exceeds its per-tensor element limit".into()); + } + Ok(elements) +} + +fn verify_sharded_source( + tensor: &gguf::TensorInfo, + raw: &[u8], + elements: u64, + derived: &derived_mixed::TensorIdentity, +) -> Result<(), String> { + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || Sha256::digest(raw).as_slice() != derived.source_sha256 + || derived.derived_bytes != elements * 4 + { + return Err(format!( + "{}: sharded source tensor identity mismatch", + tensor.name + )); + } + Ok(()) +} + +fn verify_sharded_f32( + tensor: &gguf::TensorInfo, + weights: &[f32], + derived: &derived_mixed::TensorIdentity, +) -> Result<(), String> { + let mut digest = Sha256::new(); + for value in weights { + digest.update(value.to_le_bytes()); + } + if digest.finalize().as_slice() != derived.f32_sha256 { + return Err(format!( + "{}: sharded derived F32 tensor mismatch", + tensor.name + )); + } + Ok(()) +} + +fn verify_prepared_shard( + path: &Path, + shard: &derived_mixed::ShardIdentity, + source: &File, +) -> Result<(), String> { + if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes + || hash_file(path)? != shard.gguf_sha256 + { + return Err(format!( + "{}: GGUF shard changed during preparation", + shard.name + )); + } + Ok(()) +} + +fn write_sharded_preview(request: ShardedArchiveRequest<'_>) -> Result { + let tensors = nested_file_tensors(request.prepared, request.levels); + let builder = format!( + "strata-next/experimental-sharded-derived-f32-topdown-v1:g32:l{}:sample-all", + request.levels + ); + let source = kar_writer::SourceIdentity { + name: "gguf-shards#derived-f32-le-v1", + architecture: request.architecture, + builder: &builder, + digest: request.identity.derived_sha256, + total_elements: request.identity.derived_bytes / 4, + bytes: request.identity.derived_bytes, + }; + let archive = kar_writer::write_archive(request.destination, &source, &tensors)?; + let archive_digest = hash_file(request.destination)?; + publish_sharded_provenance(&request, archive, archive_digest) +} + +fn nested_file_tensors(prepared: &[PreparedTensor], levels: u8) -> Vec> { + prepared .iter() .map(|tensor| kar_writer::Tensor { name: &tensor.name, @@ -386,35 +647,26 @@ pub fn prepare_sharded( digest: tensor.section_digest, }, }) - .collect::>(); - let builder = - format!("strata-next/experimental-sharded-derived-f32-topdown-v1:g32:l{levels}:sample-all"); - let source = kar_writer::SourceIdentity { - name: "gguf-shards#derived-f32-le-v1", - architecture: architecture - .as_deref() - .ok_or("GGUF shards have no architecture")?, - builder: &builder, - digest: identity.derived_sha256, - total_elements: identity.derived_bytes / 4, - bytes: identity.derived_bytes, - }; - let archive = kar_writer::write_archive(destination, &source, &tensors)?; - let archive_digest = hash_file(destination)?; - let provenance_path = provenance_path(destination)?; - if let Err(error) = write_provenance( - &provenance_path, - &sharded_provenance_value(&identity, archive_digest), - ) { - let _ = fs::remove_file(destination); + .collect() +} + +fn publish_sharded_provenance( + request: &ShardedArchiveRequest<'_>, + archive: kar::Summary, + archive_digest: [u8; 32], +) -> Result { + let path = provenance_path(request.destination)?; + let value = sharded_provenance_value(request.identity, archive_digest); + if let Err(error) = write_provenance(&path, &value) { + let _ = fs::remove_file(request.destination); return Err(error); } Ok(PreviewSummary { archive, archive_digest, - maximum_relative_l2, + maximum_relative_l2: request.maximum_relative_l2, tensor_distortions: Vec::new(), - provenance_path: Some(provenance_path), + provenance_path: Some(path), }) } @@ -474,6 +726,15 @@ fn prepare_sharded_streamed_with_limit( fn prepare_sharded_streamed_with_policy( request: StreamPrepareRequest<'_>, ) -> Result { + let destination = kar_writer::canonical_archive_destination(request.destination)?; + let request = StreamPrepareRequest { + manifest: request.manifest, + source_dir: request.source_dir, + destination: &destination, + levels: request.levels, + max_part_elements: request.max_part_elements, + ple_part_elements: request.ple_part_elements, + }; if !(1..=8).contains(&request.levels) { return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); } @@ -513,9 +774,20 @@ fn ensure_pending_intent(path: &Path, expected: &serde_json::Value) -> Result<() } fn read_json_if_regular(path: &Path) -> Result, String> { + read_json_if_regular_with_open(path, open_json_file) +} + +fn open_json_file(path: &Path) -> std::io::Result { + File::open(path) +} + +fn read_json_if_regular_with_open( + path: &Path, + open: fn(&Path) -> std::io::Result, +) -> Result, String> { match fs::symlink_metadata(path) { - Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => { - let file = File::open(path).map_err(|error| error.to_string())?; + Ok(metadata) if !metadata.file_type().is_symlink() && metadata.is_file() => { + let file = open(path).map_err(|error| error.to_string())?; serde_json::from_reader(file) .map(Some) .map_err(|error| error.to_string()) @@ -535,14 +807,25 @@ fn remove_pending_intent(path: &Path) -> Result<(), String> { } pub(crate) fn has_pending_streamed_publication(destination: &Path) -> Result { - match fs::symlink_metadata(provenance_path(destination)?) { + let destination = kar_writer::canonical_archive_destination(destination)?; + has_pending_streamed_publication_with_lookup(&destination, |path| fs::symlink_metadata(path)) +} + +fn has_pending_streamed_publication_with_lookup( + destination: &Path, + mut lookup: F, +) -> Result +where + F: FnMut(&Path) -> std::io::Result, +{ + match lookup(&provenance_path(destination)?) { Ok(_) => return Ok(false), Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error.to_string()), } let pending = streamed_publish_intent_path(destination)?; - match fs::symlink_metadata(&pending) { - Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => Ok(true), + match lookup(&pending) { + Ok(metadata) if !metadata.file_type().is_symlink() && metadata.is_file() => Ok(true), Ok(_) => Err("KAR publish intent must be a regular file".into()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), Err(error) => Err(error.to_string()), @@ -571,11 +854,20 @@ fn recover_streamed_publication( request: &StreamVerifyRequest<'_>, ops: &StreamPublicationOps, ) -> Result, String> { + let archive_path = kar_writer::canonical_archive_destination(request.archive_path)?; + let request = StreamVerifyRequest { + manifest: request.manifest, + source_dir: request.source_dir, + archive_path: &archive_path, + streamed_levels: request.streamed_levels, + max_part_elements: request.max_part_elements, + ple_part_elements: request.ple_part_elements, + }; let intent_path = streamed_publish_intent_path(request.archive_path)?; - let Some(verified) = verify_if_intended(request, &intent_path)? else { + let Some(verified) = verify_if_intended(&request, &intent_path)? else { return Ok(None); }; - validate_streamed_levels(request, &verified.summary)?; + validate_streamed_levels(&request, &verified.summary)?; let provenance_request = StreamProvenanceRequest { identity: &verified.identity, parts: verified @@ -683,6 +975,8 @@ impl StagingDir { std::process::id() )); fs::create_dir(&path).map_err(|error| error.to_string())?; + #[cfg(test)] + apply_preview_destination_retarget()?; Ok(Self(path)) } } @@ -726,10 +1020,18 @@ impl<'a> StreamPreparation<'a> { } fn prepare_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> { + self.prepare_shard_with_open(shard, |path| File::open(path)) + } + + fn prepare_shard_with_open( + &mut self, + shard: &derived_mixed::ShardIdentity, + open: fn(&Path) -> std::io::Result, + ) -> Result<(), String> { let path = self.request.source_dir.join(&shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; self.check_shard_index(shard, &index)?; - let mut source = File::open(&path).map_err(|error| error.to_string())?; + let mut source = open(&path).map_err(|error| error.to_string())?; for tensor in &index.tensors { self.prepare_tensor(&index, &mut source, tensor)?; } @@ -1038,12 +1340,7 @@ fn encode_nested_part( destination: section_path, }, )?; - if result.source_digest != part.source_sha256 || result.derived_digest != part.f32_sha256 { - return Err(format!( - "{}: streamed source or F32 digest mismatch", - part.name - )); - } + verify_nested_part(part, &result)?; Ok(EncodedPart { bytes: result.bytes, digest: result.digest, @@ -1052,6 +1349,19 @@ fn encode_nested_part( }) } +fn verify_nested_part( + part: &stream_parts::PartIdentity, + result: &kar_stream_encode::SectionResult, +) -> Result<(), String> { + if result.source_digest == part.source_sha256 && result.derived_digest == part.f32_sha256 { + return Ok(()); + } + Err(format!( + "{}: streamed source or F32 digest mismatch", + part.name + )) +} + fn encode_raw_part( source: &mut File, absolute: u64, @@ -1060,10 +1370,12 @@ fn encode_raw_part( ) -> Result { let (source_digest, derived_digest, bytes) = spool_raw_f32( source, - absolute, - part.source_kind, - part.source_bytes, - section_path, + RawF32Spool { + absolute, + source_kind: part.source_kind, + source_bytes: part.source_bytes, + path: section_path, + }, )?; if source_digest != part.source_sha256 || derived_digest != part.f32_sha256 @@ -1096,246 +1408,409 @@ fn streamed_builder(request: &StreamPrepareRequest<'_>) -> String { } } -fn spool_raw_f32( - reader: &mut R, +struct RawF32Spool<'a> { absolute: u64, source_kind: u32, source_bytes: u64, - path: &Path, + path: &'a Path, +} + +fn spool_raw_f32( + reader: &mut R, + request: RawF32Spool<'_>, +) -> Result<([u8; 32], [u8; 32], u64), String> { + spool_raw_f32_with_sync(reader, request, File::sync_all) +} + +fn spool_raw_f32_with_sync( + reader: &mut R, + request: RawF32Spool<'_>, + sync: fn(&File) -> std::io::Result<()>, ) -> Result<([u8; 32], [u8; 32], u64), String> { let file = fs::OpenOptions::new() .write(true) .create_new(true) - .open(path) + .open(request.path) .map_err(|error| error.to_string())?; let result = (|| { let mut writer = BufWriter::new(file); - let mut source_hash = Sha256::new(); - let mut derived_hash = Sha256::new(); - let bytes = gguf_f32_stream::visit( + let digests = write_raw_f32_chunks( reader, - absolute, - source_kind, - source_bytes, - |raw, f32_bytes| { - source_hash.update(raw); - derived_hash.update(f32_bytes); - writer - .write_all(f32_bytes) - .map_err(|error| error.to_string()) - }, + request.absolute, + request.source_kind, + request.source_bytes, + &mut writer, )?; writer.flush().map_err(|error| error.to_string())?; - writer - .get_ref() - .sync_all() - .map_err(|error| error.to_string())?; - Ok(( - source_hash.finalize().into(), - derived_hash.finalize().into(), - bytes, - )) + sync(writer.get_ref()).map_err(|error| error.to_string())?; + Ok(digests) })(); if result.is_err() { - let _ = fs::remove_file(path); + let _ = fs::remove_file(request.path); } result } +fn write_raw_f32_chunks( + reader: &mut R, + absolute: u64, + source_kind: u32, + source_bytes: u64, + writer: &mut W, +) -> Result<([u8; 32], [u8; 32], u64), String> { + let mut source_hash = Sha256::new(); + let mut derived_hash = Sha256::new(); + let bytes = gguf_f32_stream::visit( + reader, + absolute, + source_kind, + source_bytes, + |raw, f32_bytes| { + source_hash.update(raw); + derived_hash.update(f32_bytes); + writer + .write_all(f32_bytes) + .map_err(|error| error.to_string()) + }, + )?; + Ok(( + source_hash.finalize().into(), + derived_hash.finalize().into(), + bytes, + )) +} + fn prepare( source_path: &Path, destination: &Path, levels: u8, kind: PreviewKind, ) -> Result { + let destination = kar_writer::canonical_archive_destination(destination)?; + let request = SingleSourcePrepare { + source_path, + destination: &destination, + levels, + kind, + }; + validate_single_source_levels(levels)?; + let index = load_single_source_index(source_path)?; + let identity = identify_single_source(&request, &index)?; + let staging = create_preview_staging(&destination)?; + let progress = prepare_single_source_tensors(&request, &index, &identity, &staging)?; + verify_single_source_unchanged(&request, &index, &identity)?; + publish_single_source_archive(SingleArchiveRequest { + source: &request, + identity: &identity, + prepared: &progress.prepared, + total_elements: progress.total_elements, + maximum_relative_l2: progress.maximum_relative_l2, + }) +} + +fn validate_single_source_levels(levels: u8) -> Result<(), String> { if !(1..=8).contains(&levels) { return Err("F32 preview requires 1..=8 KAR levels".into()); } - let index = gguf::tensor_index(source_path).map_err(|error| error.to_string())?; - if index.summary.file_size > MAX_SOURCE_BYTES - || index.tensors.is_empty() - || index.tensors.len() > MAX_TENSORS - { + Ok(()) +} + +fn load_single_source_index(path: &Path) -> Result { + let index = gguf::tensor_index(path).map_err(|error| error.to_string())?; + // `tensor_index` rejects zero-tensor GGUFs before returning an index. + if index.summary.file_size > MAX_SOURCE_BYTES || index.tensors.len() > MAX_TENSORS { return Err("F32 preview exceeds its source or tensor-count limit".into()); } + Ok(index) +} + +fn identify_single_source( + request: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, +) -> Result { let architecture = index .summary .architecture - .as_deref() + .clone() .ok_or("GGUF source has no architecture")?; - let filename = source_path + let filename = request + .source_path .file_name() .ok_or("GGUF source has no file name")? .to_string_lossy(); - let derived_identity = match kind { - PreviewKind::F32 => None, - PreviewKind::Iq3 => Some(DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?)), - PreviewKind::Mixed => Some(DerivedIdentity::Mixed(derived_mixed::fingerprint( - source_path, - )?)), + let derived = derive_single_source_identity(request.source_path, request.kind)?; + let source_name = single_source_name(&filename, request.kind); + let original_digest = match &derived { + Some(identity) => identity.gguf_digest(), + None => hash_file(request.source_path)?, }; - let source_name = match kind { - PreviewKind::F32 => filename.to_string(), + Ok(SingleSourceIdentity { + architecture, + source_name, + original_digest, + source_bytes: index.summary.file_size, + derived, + }) +} + +fn derive_single_source_identity( + path: &Path, + kind: PreviewKind, +) -> Result, String> { + match kind { + PreviewKind::F32 => Ok(None), + PreviewKind::Iq3 => Ok(Some(DerivedIdentity::Iq3(derived_iq3::fingerprint(path)?))), + PreviewKind::Mixed => Ok(Some(DerivedIdentity::Mixed(derived_mixed::fingerprint( + path, + )?))), + } +} + +fn single_source_name(filename: &str, kind: PreviewKind) -> String { + match kind { + PreviewKind::F32 => filename.to_owned(), PreviewKind::Iq3 => format!("{filename}#derived-f32-le-v1"), PreviewKind::Mixed => format!("{filename}#mixed-derived-f32-le-v1"), - }; - let original_digest = match &derived_identity { - Some(identity) => identity.gguf_digest(), - None => hash_file(source_path)?, - }; - let staging_name = format!( - "{}.parts-{}", - destination - .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy(), - std::process::id() - ); - let staging_path = destination.with_file_name(staging_name); - fs::create_dir(&staging_path).map_err(|error| error.to_string())?; - let staging = StagingDir(staging_path); - let mut source_file = File::open(source_path).map_err(|error| error.to_string())?; - let mut total_elements = 0u64; - let mut maximum_relative_l2 = 0.0f64; - let mut prepared = Vec::with_capacity(index.tensors.len()); - for (number, tensor) in index.tensors.iter().enumerate() { - let supported = match kind { - PreviewKind::F32 => tensor.kind == 0, - PreviewKind::Iq3 => tensor.kind == 21, - PreviewKind::Mixed => matches!(tensor.kind, 0 | 1 | 21 | 30), - }; - if !supported || tensor.dimensions.len() > 4 { - return Err(format!( - "{}: preview supports only {} tensors with up to four dimensions", - tensor.name, - match kind { - PreviewKind::F32 => "F32", - PreviewKind::Iq3 => "IQ3_S", - PreviewKind::Mixed => "F32/F16/BF16/IQ3_S", - } - )); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |product, dim| product.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - total_elements = total_elements - .checked_add(elements) - .ok_or("GGUF model element count overflow")?; - if elements > MAX_TENSOR_ELEMENTS { - return Err("F32 preview exceeds its per-tensor element limit".into()); - } - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - source_file - .seek(SeekFrom::Start(absolute)) - .map_err(|error| error.to_string())?; - let mut raw = vec![0u8; tensor.bytes as usize]; - source_file - .read_exact(&mut raw) - .map_err(|error| error.to_string())?; - let (weights, tensor_digest, source_offset) = if let Some(identity) = &derived_identity { - let derived = identity.tensor(number); - if derived.name != tensor.name - || derived.source_kind != tensor.kind - || Sha256::digest(&raw).as_slice() != derived.source_digest - { - return Err("GGUF tensor differs from derived source identity".into()); - } - let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; - let mut digest = Sha256::new(); - for value in &weights { - digest.update(value.to_le_bytes()); - } - if digest.finalize().as_slice() != derived.f32_digest || derived.bytes != elements * 4 { - return Err("decoded F32 tensor differs from derived source identity".into()); - } - (weights, *derived.f32_digest, derived.offset) - } else { - let digest = Sha256::digest(&raw).into(); - let weights = raw - .as_chunks::<4>() - .0 - .iter() - .map(|chunk| f32::from_le_bytes(*chunk)) - .collect::>(); - (weights, digest, absolute) - }; - drop(raw); - let section_path = staging.0.join(format!("{number:06}.section")); - let (coded, relative_l2) = encode_preview_tensor( - &tensor.name, - &tensor.dimensions, - &weights, - tensor_digest, - source_offset, - §ion_path, - levels, - )?; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - prepared.push(coded); } - if source_file - .metadata() - .map_err(|error| error.to_string())? - .len() - != index.summary.file_size - || hash_file(source_path)? != original_digest +} + +fn prepare_single_source_tensors( + request: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, + identity: &SingleSourceIdentity, + staging: &StagingDir, +) -> Result { + let mut source = File::open(request.source_path).map_err(|error| error.to_string())?; + let mut progress = SingleTensorProgress { + total_elements: 0, + maximum_relative_l2: 0.0, + prepared: Vec::with_capacity(index.tensors.len()), + }; + for (number, tensor) in index.tensors.iter().enumerate() { + prepare_single_tensor( + SingleTensorRequest { + source: request, + index, + identity, + staging, + tensor, + number, + }, + &mut source, + &mut progress, + )?; + } + Ok(progress) +} + +fn prepare_single_tensor( + request: SingleTensorRequest<'_>, + source: &mut File, + progress: &mut SingleTensorProgress, +) -> Result<(), String> { + validate_single_tensor(&request)?; + let elements = tensor_elements(request.tensor)?; + progress.total_elements = progress + .total_elements + .checked_add(elements) + .ok_or("GGUF model element count overflow")?; + let absolute = request + .index + .summary + .data_start + .checked_add(request.tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + source + .seek(SeekFrom::Start(absolute)) + .map_err(|error| error.to_string())?; + let mut raw = vec![0u8; request.tensor.bytes as usize]; + source + .read_exact(&mut raw) + .map_err(|error| error.to_string())?; + let (weights, digest, offset) = single_tensor_weights(&request, &raw, elements, absolute)?; + drop(raw); + append_encoded_single_tensor(&request, &weights, digest, offset, progress) +} + +fn validate_single_tensor(request: &SingleTensorRequest<'_>) -> Result<(), String> { + let tensor = request.tensor; + let supported = match request.source.kind { + PreviewKind::F32 => tensor.kind == 0, + PreviewKind::Iq3 => tensor.kind == 21, + PreviewKind::Mixed => matches!(tensor.kind, 0 | 1 | 21 | 30), + }; + if !supported || tensor.dimensions.len() > 4 { + return Err(format!( + "{}: preview supports only {} tensors with up to four dimensions", + tensor.name, + preview_kind_name(request.source.kind) + )); + } + if tensor_elements(tensor)? > MAX_TENSOR_ELEMENTS { + return Err("F32 preview exceeds its per-tensor element limit".into()); + } + Ok(()) +} + +fn preview_kind_name(kind: PreviewKind) -> &'static str { + match kind { + PreviewKind::F32 => "F32", + PreviewKind::Iq3 => "IQ3_S", + PreviewKind::Mixed => "F32/F16/BF16/IQ3_S", + } +} + +fn tensor_elements(tensor: &gguf::TensorInfo) -> Result { + tensor + .dimensions + .iter() + .try_fold(1u64, |count, dim| count.checked_mul(*dim)) + .ok_or_else(|| "GGUF tensor element count overflow".into()) +} + +fn single_tensor_weights( + request: &SingleTensorRequest<'_>, + raw: &[u8], + elements: u64, + absolute: u64, +) -> Result<(Vec, [u8; 32], u64), String> { + if let Some(identity) = &request.identity.derived { + return derived_tensor_weights(identity, request.number, request.tensor, raw, elements); + } + let digest = Sha256::digest(raw).into(); + let weights = raw + .as_chunks::<4>() + .0 + .iter() + .map(|chunk| f32::from_le_bytes(*chunk)) + .collect(); + Ok((weights, digest, absolute)) +} + +fn derived_tensor_weights( + identity: &DerivedIdentity, + number: usize, + tensor: &gguf::TensorInfo, + raw: &[u8], + elements: u64, +) -> Result<(Vec, [u8; 32], u64), String> { + let derived = identity.tensor(number); + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || Sha256::digest(raw).as_slice() != derived.source_digest + { + return Err("GGUF tensor differs from derived source identity".into()); + } + let weights = decode_source_tensor(tensor.kind, raw, elements as usize)?; + verify_derived_tensor(identity, number, &weights, elements)?; + let tensor = identity.tensor(number); + Ok((weights, *tensor.f32_digest, tensor.offset)) +} + +fn verify_derived_tensor( + identity: &DerivedIdentity, + number: usize, + weights: &[f32], + elements: u64, +) -> Result<(), String> { + let derived = identity.tensor(number); + let mut digest = Sha256::new(); + for value in weights { + digest.update(value.to_le_bytes()); + } + if digest.finalize().as_slice() != derived.f32_digest || derived.bytes != elements * 4 { + return Err("decoded F32 tensor differs from derived source identity".into()); + } + Ok(()) +} + +fn append_encoded_single_tensor( + request: &SingleTensorRequest<'_>, + weights: &[f32], + digest: [u8; 32], + offset: u64, + progress: &mut SingleTensorProgress, +) -> Result<(), String> { + let path = request + .staging + .0 + .join(format!("{:06}.section", request.number)); + let (prepared, error) = encode_preview_tensor(PreviewTensorRequest { + name: &request.tensor.name, + dimensions: &request.tensor.dimensions, + weights, + source_digest: digest, + source_offset: offset, + section_path: &path, + levels: request.source.levels, + })?; + progress.maximum_relative_l2 = progress.maximum_relative_l2.max(error); + progress.prepared.push(prepared); + Ok(()) +} + +fn verify_single_source_unchanged( + request: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, + identity: &SingleSourceIdentity, +) -> Result<(), String> { + let source = File::open(request.source_path).map_err(|error| error.to_string())?; + if source.metadata().map_err(|error| error.to_string())?.len() != index.summary.file_size + || hash_file(request.source_path)? != identity.original_digest { return Err("GGUF source changed during F32 preparation".into()); } - let tensors = prepared - .iter() - .map(|tensor| kar_writer::Tensor { - name: &tensor.name, - dims: &tensor.dims, - source_dtype: 0, - source_digest: tensor.source_digest, - source_offset: tensor.source_offset, - data: kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - levels, - path: &tensor.section_path, - offset: 0, - bytes: tensor.section_bytes, - digest: tensor.section_digest, - }, - }) - .collect::>(); + Ok(()) +} + +fn publish_single_source_archive( + request: SingleArchiveRequest<'_>, +) -> Result { + let tensors = nested_file_tensors(request.prepared, request.source.levels); let builder = format!( - "strata-next/experimental-{}-topdown-v1:g32:l{levels}:sample-all", - match kind { - PreviewKind::F32 => "f32", - PreviewKind::Iq3 => "iq3-derived-f32", - PreviewKind::Mixed => "mixed-derived-f32", - } + "strata-next/experimental-{}-topdown-v1:g32:l{}:sample-all", + preview_builder_name(request.source.kind), + request.source.levels ); - let (source_digest, source_bytes) = derived_identity - .as_ref() - .map(|identity| (identity.derived_digest(), identity.derived_bytes())) - .unwrap_or((original_digest, index.summary.file_size)); + let (digest, bytes) = virtual_source_identity(request.identity); let source = kar_writer::SourceIdentity { - name: &source_name, - architecture, + name: &request.identity.source_name, + architecture: &request.identity.architecture, builder: &builder, - digest: source_digest, - total_elements, - bytes: source_bytes, + digest, + total_elements: request.total_elements, + bytes, }; - let archive = kar_writer::write_archive(destination, &source, &tensors)?; - let archive_digest = hash_file(destination)?; - let provenance_path = if let Some(identity) = derived_identity { - let path = provenance_path(destination)?; - let manifest = provenance_value(&identity, archive_digest); + let archive = kar_writer::write_archive(request.source.destination, &source, &tensors)?; + publish_single_source_summary(&request, archive) +} + +fn preview_builder_name(kind: PreviewKind) -> &'static str { + match kind { + PreviewKind::F32 => "f32", + PreviewKind::Iq3 => "iq3-derived-f32", + PreviewKind::Mixed => "mixed-derived-f32", + } +} + +fn virtual_source_identity(identity: &SingleSourceIdentity) -> ([u8; 32], u64) { + identity + .derived + .as_ref() + .map(|value| (value.derived_digest(), value.derived_bytes())) + .unwrap_or((identity.original_digest, identity.source_bytes)) +} + +fn publish_single_source_summary( + request: &SingleArchiveRequest<'_>, + archive: kar::Summary, +) -> Result { + let archive_digest = hash_file(request.source.destination)?; + let provenance_path = if let Some(identity) = &request.identity.derived { + let path = provenance_path(request.source.destination)?; + let manifest = provenance_value(identity, archive_digest); if let Err(error) = write_provenance(&path, &manifest) { - let _ = fs::remove_file(destination); + let _ = fs::remove_file(request.source.destination); return Err(error); } Some(path) @@ -1345,83 +1820,111 @@ fn prepare( Ok(PreviewSummary { archive, archive_digest, - maximum_relative_l2, + maximum_relative_l2: request.maximum_relative_l2, tensor_distortions: Vec::new(), provenance_path, }) } fn encode_preview_tensor( - name: &str, - dimensions: &[u64], - weights: &[f32], - source_digest: [u8; 32], - source_offset: u64, - section_path: &Path, - levels: u8, + request: PreviewTensorRequest<'_>, ) -> Result<(PreparedTensor, f64), String> { + let encoded = calibrate_preview_weights(request.weights, request.levels)?; + let relative_l2 = preview_relative_l2(request.weights, &encoded, request.levels)?; + let section = write_preview_section(&request, &encoded)?; + Ok((prepared_tensor(&request, section), relative_l2)) +} + +fn calibrate_preview_weights( + weights: &[f32], + levels: u8, +) -> Result<(kar_codec::Calibration, kar_codec::EncodedPlanes), String> { let normalized = kar_codec::normalize_for_calibration(weights, 32)?; let calibration = kar_codec::fit_topdown(&normalized.values, levels)?; let encoded = kar_codec::encode_with_boundaries(weights, 32, &calibration.boundaries, levels)?; - let plane_refs = encoded.planes.iter().map(Vec::as_slice).collect::>(); - let mut decoded = vec![0.0f32; weights.len()]; + Ok((calibration, encoded)) +} + +fn preview_relative_l2( + weights: &[f32], + codec: &(kar_codec::Calibration, kar_codec::EncodedPlanes), + levels: u8, +) -> Result { + let decoded = decode_preview_weights(weights.len(), codec, levels)?; + let (error_sum, reference_sum) = preview_error_sums(weights, &decoded); + Ok(if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + }) +} + +fn decode_preview_weights( + length: usize, + codec: &(kar_codec::Calibration, kar_codec::EncodedPlanes), + levels: u8, +) -> Result, String> { + let plane_refs = codec.1.planes.iter().map(Vec::as_slice).collect::>(); + let mut decoded = vec![0.0f32; length]; kar_codec::decode_range( - &encoded.scales, - &calibration.books[usize::from(levels) - 1], + &codec.1.scales, + &codec.0.books[usize::from(levels) - 1], &plane_refs, 32, 0, &mut decoded, )?; - let (error_sum, reference_sum) = weights.iter().zip(&decoded).fold( - (0.0f64, 0.0f64), - |(error_sum, reference_sum), (original, rebuilt)| { - let delta = f64::from(*original) - f64::from(*rebuilt); - ( - error_sum + delta * delta, - reference_sum + f64::from(*original).powi(2), - ) - }, - ); - let relative_l2 = if reference_sum == 0.0 { - error_sum.sqrt() - } else { - (error_sum / reference_sum).sqrt() - }; - let books = calibration - .books + Ok(decoded) +} + +fn preview_error_sums(weights: &[f32], decoded: &[f32]) -> (f64, f64) { + weights .iter() - .map(Vec::as_slice) - .collect::>(); - let coded_tensor = kar_writer::Tensor { - name, - dims: dimensions, + .zip(decoded) + .fold((0.0, 0.0), |(error, reference), (a, b)| { + let delta = f64::from(*a) - f64::from(*b); + (error + delta * delta, reference + f64::from(*a).powi(2)) + }) +} + +fn write_preview_section( + request: &PreviewTensorRequest<'_>, + codec: &(kar_codec::Calibration, kar_codec::EncodedPlanes), +) -> Result { + let plane_refs = codec.1.planes.iter().map(Vec::as_slice).collect::>(); + let books = codec.0.books.iter().map(Vec::as_slice).collect::>(); + let tensor = kar_writer::Tensor { + name: request.name, + dims: request.dimensions, source_dtype: 0, - source_digest, - source_offset, + source_digest: request.source_digest, + source_offset: request.source_offset, data: kar_writer::TensorData::Nested { group: 32, nesting: 0, planes_min: 1, - planes_max: levels, - scales: &encoded.scales, + planes_max: request.levels, + scales: &codec.1.scales, books: &books, planes: &plane_refs, }, }; - let section = kar_writer::write_nested_section(section_path, &coded_tensor)?; - Ok(( - PreparedTensor { - name: name.to_owned(), - dims: dimensions.to_vec(), - source_digest, - source_offset, - section_path: section_path.to_path_buf(), - section_bytes: section.bytes, - section_digest: section.digest, - }, - relative_l2, - )) + kar_writer::write_nested_section(request.section_path, &tensor) +} + +fn prepared_tensor( + request: &PreviewTensorRequest<'_>, + section: kar_writer::SectionSummary, +) -> PreparedTensor { + PreparedTensor { + name: request.name.to_owned(), + dims: request.dimensions.to_vec(), + source_digest: request.source_digest, + source_offset: request.source_offset, + section_path: request.section_path.to_path_buf(), + section_bytes: section.bytes, + section_digest: section.digest, + } } pub fn verify_iq3(source_path: &Path, archive_path: &Path) -> Result { @@ -1488,6 +1991,15 @@ pub fn verify_sharded_streamed_ple( } fn verify_sharded_inner(request: StreamVerifyRequest<'_>) -> Result { + let archive_path = kar_writer::canonical_archive_destination(request.archive_path)?; + let request = StreamVerifyRequest { + manifest: request.manifest, + source_dir: request.source_dir, + archive_path: &archive_path, + streamed_levels: request.streamed_levels, + max_part_elements: request.max_part_elements, + ple_part_elements: request.ple_part_elements, + }; let verified = verify_sharded_archive(&request)?; verify_sharded_provenance(&request, &verified)?; Ok(verified.summary) @@ -1587,21 +2099,17 @@ fn verify_tensor_records( bytes: tensor.derived_bytes, }, )?; - if record - .dimensions - .iter() - .try_fold(1u64, |size, dim| size.checked_mul(*dim)) - != Some(tensor.derived_bytes / 4) - { - return Err(format!( - "{}: sharded KAR tensor shape mismatch", - tensor.name - )); - } } Ok(()) } +fn tensor_shape_matches_derived_bytes(dimensions: &[u64], derived_bytes: u64) -> bool { + dimensions + .iter() + .try_fold(1u64, |size, dim| size.checked_mul(*dim)) + == Some(derived_bytes / 4) +} + fn verify_source_record( record: &kar::TensorSource, expected: ExpectedSourceRecord<'_>, @@ -1613,11 +2121,14 @@ fn verify_source_record( .ok_or("KAR tensor source byte count overflow")?; let dimensions_match = expected.dimensions.is_empty() || record.dimensions == expected.dimensions; + let derived_shape_matches = + tensor_shape_matches_derived_bytes(&record.dimensions, expected.bytes); if record.name != expected.name || !dimensions_match || record.dtype != 0 || record.digest != expected.digest || record.offset != expected.offset + || !derived_shape_matches || bytes != expected.bytes { return Err(format!( @@ -1883,7 +2394,7 @@ fn partitioned_provenance(parts: &[Vec]) -> serde_js ) } -fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> { +pub(crate) fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> { write_provenance_with_ops(path, value, hard_link_path, remove_file_path) } @@ -1916,12 +2427,21 @@ fn write_provenance_with_ops( } fn create_provenance_temp(path: &Path) -> Result<(PathBuf, File), String> { + create_provenance_temp_with_sequence(path, || { + PROVENANCE_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) + }) +} + +fn create_provenance_temp_with_sequence( + path: &Path, + mut next_sequence: impl FnMut() -> u64, +) -> Result<(PathBuf, File), String> { let name = path .file_name() .ok_or("provenance path has no file name")? .to_string_lossy(); for _ in 0..64 { - let sequence = PROVENANCE_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let sequence = next_sequence(); let temporary = path.with_file_name(format!("{name}.part-{}-{sequence}", std::process::id())); match fs::OpenOptions::new() @@ -1938,9 +2458,24 @@ fn create_provenance_temp(path: &Path) -> Result<(PathBuf, File), String> { } fn write_provenance_contents(file: &mut File, value: &serde_json::Value) -> Result<(), String> { - serde_json::to_writer_pretty(&mut *file, value).map_err(|error| error.to_string())?; - file.write_all(b"\n").map_err(|error| error.to_string())?; - file.sync_all().map_err(|error| error.to_string()) + write_provenance_contents_with_sync(file, value, File::sync_all) +} + +fn write_provenance_contents_with_sync( + file: &mut File, + value: &serde_json::Value, + sync: fn(&File) -> std::io::Result<()>, +) -> Result<(), String> { + write_provenance_json(file, value)?; + sync(file).map_err(|error| error.to_string()) +} + +fn write_provenance_json( + writer: &mut W, + value: &serde_json::Value, +) -> Result<(), String> { + serde_json::to_writer_pretty(&mut *writer, value).map_err(|error| error.to_string())?; + writer.write_all(b"\n").map_err(|error| error.to_string()) } fn hash_file(path: &Path) -> Result<[u8; 32], String> { @@ -1963,6 +2498,762 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> { mod tests { use super::*; + fn source_record() -> kar::TensorSource { + kar::TensorSource { + name: "weight".into(), + dimensions: vec![2], + dtype: 0, + digest: [7; 32], + offset: 16, + section_bytes: 8, + storage_class: 0, + n_elements: 2, + planes_min: 0, + planes_max: 0, + section_offset: 0, + planes_offset: 0, + plane_stride_bytes: 0, + } + } + + fn expected_record() -> ExpectedSourceRecord<'static> { + ExpectedSourceRecord { + name: "weight", + dimensions: &[2], + digest: [7; 32], + offset: 16, + bytes: 8, + } + } + + #[test] + fn source_record_verification_rejects_each_identity_field_mismatch() { + assert!(verify_source_record(&source_record(), expected_record()).is_ok()); + for field in 0..5 { + let mut record = source_record(); + match field { + 0 => record.name = "other".into(), + 1 => record.dimensions = vec![1, 2], + 2 => record.dtype = 1, + 3 => record.digest = [8; 32], + _ => record.offset = 8, + } + assert!(verify_source_record(&record, expected_record()).is_err()); + } + assert!( + verify_source_record( + &source_record(), + ExpectedSourceRecord { + bytes: 4, + ..expected_record() + } + ) + .is_err() + ); + } + + #[test] + fn source_record_verification_rejects_dimension_product_overflow() { + let mut record = source_record(); + record.dimensions = vec![u64::MAX, 2]; + assert!( + verify_source_record( + &record, + ExpectedSourceRecord { + dimensions: &[], + ..expected_record() + } + ) + .is_err() + ); + } + + #[test] + fn source_record_verification_checks_shape_before_accepting_any_dimensions() { + let record = source_record(); + let expected = ExpectedSourceRecord { + dimensions: &[], + ..expected_record() + }; + assert!(verify_source_record(&record, expected).is_ok()); + let mut mismatched = record; + mismatched.dimensions = vec![3]; + assert_eq!( + verify_source_record( + &mismatched, + ExpectedSourceRecord { + dimensions: &[], + ..expected_record() + }, + ) + .unwrap_err(), + "weight: sharded KAR source record mismatch" + ); + } + + #[test] + fn source_record_verification_rejects_nonmultiple_expected_bytes() { + assert_eq!( + verify_source_record( + &source_record(), + ExpectedSourceRecord { + dimensions: &[], + bytes: 9, + ..expected_record() + }, + ) + .unwrap_err(), + "weight: sharded KAR source record mismatch" + ); + } + + #[test] + fn streamed_preparation_rejects_invalid_levels_before_reading_sources() { + let manifest = invalid_manifest(); + assert_prepare_rejects_invalid_levels(&manifest); + assert_verify_rejects_invalid_levels(&manifest); + } + + fn invalid_manifest() -> Manifest { + Manifest { + schema_version: 0, + files: Vec::new(), + } + } + + fn assert_prepare_rejects_invalid_levels(manifest: &Manifest) { + for levels in [0, 9] { + assert!( + prepare_sharded_streamed( + manifest, + Path::new("missing-source"), + Path::new("unused-archive.kar"), + levels + ) + .is_err() + ); + } + } + + fn assert_verify_rejects_invalid_levels(manifest: &Manifest) { + assert!( + verify_sharded_streamed( + manifest, + Path::new("missing-source"), + Path::new("unused-archive.kar"), + 0 + ) + .is_err() + ); + assert!( + verify_sharded_streamed_ple( + manifest, + Path::new("missing-source"), + Path::new("unused-archive.kar"), + 2, + 1 + ) + .is_err() + ); + } + + #[test] + fn sharded_request_enforces_manifest_byte_budget() { + assert_eq!( + validate_sharded_request(&manifest_with_sizes(&[MAX_SOURCE_BYTES]), 1), + Ok(()) + ); + assert!( + validate_sharded_request(&manifest_with_sizes(&[MAX_SOURCE_BYTES + 1]), 1) + .unwrap_err() + .contains("64 MiB") + ); + assert!( + validate_sharded_request(&manifest_with_sizes(&[u64::MAX, 1]), 1) + .unwrap_err() + .contains("overflow") + ); + } + + fn manifest_with_sizes(sizes: &[u64]) -> Manifest { + Manifest { + schema_version: 1, + files: sizes + .iter() + .enumerate() + .map(|(number, size)| crate::model::ModelFile { + name: format!("shard-{number}.gguf"), + url: format!("https://example.invalid/shard-{number}.gguf"), + size: *size, + sha256: "0".repeat(64), + }) + .collect(), + } + } + + #[test] + fn sharded_identity_requires_a_bounded_nonempty_tensor_set() { + assert!(validate_sharded_identity(&sharded_identity(0)).is_err()); + assert!(validate_sharded_identity(&sharded_identity(MAX_TENSORS)).is_ok()); + assert!(validate_sharded_identity(&sharded_identity(MAX_TENSORS + 1)).is_err()); + } + + fn sharded_identity(tensor_count: usize) -> derived_mixed::ShardedIdentity { + derived_mixed::ShardedIdentity { + derived_sha256: [0; 32], + derived_bytes: 0, + shards: Vec::new(), + tensors: (0..tensor_count).map(sharded_tensor_identity).collect(), + } + } + + fn sharded_tensor_identity(number: usize) -> derived_mixed::TensorIdentity { + derived_mixed::TensorIdentity { + name: format!("tensor-{number}"), + source_kind: 0, + source_sha256: [0; 32], + derived_offset: 0, + derived_bytes: 0, + f32_sha256: [0; 32], + } + } + + #[test] + fn sharded_tensor_dimensions_reject_unsupported_overflow_and_oversize_shapes() { + assert_eq!( + sharded_tensor_elements(&preview_tensor(vec![2, 3])).unwrap(), + 6 + ); + assert!(sharded_tensor_elements(&preview_tensor(vec![1, 1, 1, 1, 1])).is_err()); + assert!(sharded_tensor_elements(&preview_tensor(vec![u64::MAX, 2])).is_err()); + assert!(sharded_tensor_elements(&preview_tensor(vec![MAX_TENSOR_ELEMENTS + 1])).is_err()); + } + + fn preview_tensor(dimensions: Vec) -> gguf::TensorInfo { + gguf::TensorInfo { + name: "weight".into(), + dimensions, + kind: 0, + offset: 0, + bytes: 4, + } + } + + #[test] + fn sharded_source_and_decoded_values_must_match_derived_identity() { + let tensor = preview_tensor(vec![1]); + let raw = 1.25f32.to_le_bytes(); + let derived = sharded_identity_for(&tensor, &raw, &[1.25]); + assert!(verify_sharded_source(&tensor, &raw, 1, &derived).is_ok()); + assert!(verify_sharded_f32(&tensor, &[1.25], &derived).is_ok()); + assert_sharded_identity_mismatches(&tensor, &raw, &derived); + } + + fn sharded_identity_for( + tensor: &gguf::TensorInfo, + raw: &[u8], + weights: &[f32], + ) -> derived_mixed::TensorIdentity { + let mut digest = Sha256::new(); + for value in weights { + digest.update(value.to_le_bytes()); + } + derived_mixed::TensorIdentity { + name: tensor.name.clone(), + source_kind: tensor.kind, + source_sha256: Sha256::digest(raw).into(), + derived_offset: 0, + derived_bytes: (weights.len() * 4) as u64, + f32_sha256: digest.finalize().into(), + } + } + + fn assert_sharded_identity_mismatches( + tensor: &gguf::TensorInfo, + raw: &[u8], + derived: &derived_mixed::TensorIdentity, + ) { + assert!(verify_sharded_source(tensor, raw, 2, derived).is_err()); + assert!(verify_sharded_source(tensor, &[0; 4], 1, derived).is_err()); + assert!(verify_sharded_f32(tensor, &[2.5], derived).is_err()); + let wrong_name = gguf::TensorInfo { + name: "other".into(), + ..preview_tensor(vec![1]) + }; + assert!(verify_sharded_source(&wrong_name, raw, 1, derived).is_err()); + let wrong_kind = gguf::TensorInfo { + kind: 1, + ..preview_tensor(vec![1]) + }; + assert!(verify_sharded_source(&wrong_kind, raw, 1, derived).is_err()); + } + + #[test] + fn single_source_levels_admit_format_bounds_only() { + for level in [1, 8] { + assert!(validate_single_source_levels(level).is_ok()); + } + for level in [0, 9] { + assert!(validate_single_source_levels(level).is_err()); + } + } + + #[test] + fn derived_single_tensor_checks_source_and_decoded_identity() { + let raw = 1.25f32.to_le_bytes(); + let tensor = preview_tensor(vec![1]); + let identity = mixed_identity_for(&tensor, &raw, &[1.25]); + assert!(derived_tensor_weights(&identity, 0, &tensor, &raw, 1).is_ok()); + assert_derived_tensor_rejects_mismatches(&identity, &tensor, &raw); + } + + fn mixed_identity_for( + tensor: &gguf::TensorInfo, + raw: &[u8], + weights: &[f32], + ) -> DerivedIdentity { + let mut digest = Sha256::new(); + for value in weights { + digest.update(value.to_le_bytes()); + } + DerivedIdentity::Mixed(derived_mixed::Identity { + gguf_sha256: [0; 32], + derived_sha256: [0; 32], + derived_bytes: 4, + tensors: vec![derived_mixed::TensorIdentity { + name: tensor.name.clone(), + source_kind: tensor.kind, + source_sha256: Sha256::digest(raw).into(), + derived_offset: 0, + derived_bytes: 4, + f32_sha256: digest.finalize().into(), + }], + }) + } + + fn assert_derived_tensor_rejects_mismatches( + identity: &DerivedIdentity, + tensor: &gguf::TensorInfo, + raw: &[u8], + ) { + assert!(derived_tensor_weights(identity, 0, tensor, &[0; 4], 1).is_err()); + assert!(verify_derived_tensor(identity, 0, &[2.5], 1).is_err()); + let mut wrong_name = preview_tensor(vec![1]); + wrong_name.name = "other".into(); + assert!(derived_tensor_weights(identity, 0, &wrong_name, raw, 1).is_err()); + let mut wrong_kind = preview_tensor(vec![1]); + wrong_kind.kind = 1; + assert!(derived_tensor_weights(identity, 0, &wrong_kind, raw, 1).is_err()); + assert!(verify_derived_tensor(identity, 0, &[1.25], 2).is_err()); + } + + #[test] + fn single_tensor_validation_preserves_kind_and_shape_policy() { + assert!(validate_single_tensor_for(PreviewKind::F32, preview_tensor(vec![2, 3])).is_ok()); + assert!(validate_single_tensor_for(PreviewKind::Iq3, tensor_kind(21)).is_ok()); + assert!(validate_single_tensor_for(PreviewKind::Mixed, tensor_kind(1)).is_ok()); + assert!(validate_single_tensor_for(PreviewKind::F32, tensor_kind(21)).is_err()); + assert!(validate_single_tensor_for(PreviewKind::F32, preview_tensor(vec![1; 5])).is_err()); + assert!( + validate_single_tensor_for( + PreviewKind::F32, + preview_tensor(vec![MAX_TENSOR_ELEMENTS + 1]) + ) + .is_err() + ); + assert!(tensor_elements(&preview_tensor(vec![u64::MAX, 2])).is_err()); + } + + fn validate_single_tensor_for( + kind: PreviewKind, + tensor: gguf::TensorInfo, + ) -> Result<(), String> { + let source = SingleSourcePrepare { + source_path: Path::new("unused.gguf"), + destination: Path::new("unused.kar"), + levels: 2, + kind, + }; + let identity = SingleSourceIdentity { + architecture: "fixture".into(), + source_name: "fixture.gguf".into(), + original_digest: [0; 32], + source_bytes: 0, + derived: None, + }; + let index = empty_tensor_index(); + let staging = StagingDir(PathBuf::new()); + validate_single_tensor(&SingleTensorRequest { + source: &source, + index: &index, + identity: &identity, + staging: &staging, + tensor: &tensor, + number: 0, + }) + } + + fn tensor_kind(kind: u32) -> gguf::TensorInfo { + gguf::TensorInfo { + kind, + ..preview_tensor(vec![1]) + } + } + + fn empty_tensor_index() -> gguf::TensorIndex { + gguf::TensorIndex { + summary: gguf::Summary { + tensors: 0, + metadata: 0, + architecture: None, + split_no: None, + split_count: None, + split_tensors_count: None, + data_start: 32, + file_size: 32, + types: Default::default(), + }, + tensors: Vec::new(), + } + } + + #[test] + fn relative_l2_defines_zero_reference_and_normalized_error() { + let codec = zero_decoder_codec(); + assert_eq!(preview_relative_l2(&[0.0; 32], &codec, 2).unwrap(), 0.0); + assert_eq!(preview_relative_l2(&[1.0; 32], &codec, 2).unwrap(), 1.0); + } + + fn zero_decoder_codec() -> (kar_codec::Calibration, kar_codec::EncodedPlanes) { + ( + kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0; 2], vec![0; 4]], + }, + kar_codec::EncodedPlanes { + scales: vec![0x3c00], + planes: vec![vec![0], vec![0]], + padded_elements: 32, + }, + ) + } + + #[test] + fn single_source_change_after_index_is_detected_by_size_and_digest() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("source-changed.gguf"); + let original = two_tensor_f32_gguf(); + fs::write(&path, &original).unwrap(); + let index = gguf::tensor_index(&path).unwrap(); + let identity = single_source_identity_for(&path, &index, &original); + let request = SingleSourcePrepare { + source_path: &path, + destination: Path::new("unused.kar"), + levels: 2, + kind: PreviewKind::F32, + }; + assert_same_size_source_change_rejected(&request, &index, &identity, &original); + assert_changed_size_source_rejected(&request, &index, &identity); + } + + fn single_source_identity_for( + path: &Path, + index: &gguf::TensorIndex, + original: &[u8], + ) -> SingleSourceIdentity { + SingleSourceIdentity { + architecture: index.summary.architecture.clone().unwrap(), + source_name: path.file_name().unwrap().to_string_lossy().into_owned(), + original_digest: Sha256::digest(original).into(), + source_bytes: index.summary.file_size, + derived: None, + } + } + + fn assert_same_size_source_change_rejected( + request: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, + identity: &SingleSourceIdentity, + original: &[u8], + ) { + let mut changed = original.to_vec(); + let last = changed.len() - 1; + changed[last] ^= 1; + fs::write(request.source_path, changed).unwrap(); + assert!(verify_single_source_unchanged(request, index, identity).is_err()); + } + + fn assert_changed_size_source_rejected( + request: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, + identity: &SingleSourceIdentity, + ) { + fs::write(request.source_path, b"changed-size").unwrap(); + assert!(verify_single_source_unchanged(request, index, identity).is_err()); + } + + #[test] + fn single_source_index_rejects_oversized_inputs() { + let fixture = overlay_fixture(); + assert_oversized_single_source_rejected(&fixture.directory); + } + + #[test] + fn zero_tensor_gguf_is_rejected_by_indexer_before_preview_validation() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("empty-source.gguf"); + fs::write(&path, empty_gguf()).unwrap(); + assert!( + gguf::tensor_index(&path) + .unwrap_err() + .to_string() + .contains("no tensors") + ); + } + + fn empty_gguf() -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(32, 0); + bytes + } + + fn assert_oversized_single_source_rejected(directory: &Path) { + let path = directory.join("oversized-source.gguf"); + let bytes = oversized_tensor_gguf(); + let file_size = bytes.len() as u64 + (MAX_SOURCE_BYTES / 4 + 1) * 4; + fs::write(&path, bytes).unwrap(); + File::options() + .write(true) + .open(&path) + .unwrap() + .set_len(file_size) + .unwrap(); + let error = load_single_source_index(&path).unwrap_err(); + assert!(error.contains("source or tensor-count limit"), "{error}"); + } + + fn oversized_tensor_gguf() -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + string(&mut bytes, "large"); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&(MAX_SOURCE_BYTES / 4 + 1).to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes + } + + #[test] + fn recovery_ignores_absent_intent_without_inspecting_archive() { + let manifest = Manifest { + schema_version: 0, + files: Vec::new(), + }; + let request = StreamVerifyRequest { + manifest: &manifest, + source_dir: Path::new("missing-source"), + archive_path: Path::new("unused-archive.kar"), + streamed_levels: Some(2), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + }; + assert!( + recover_streamed_publication(&request, &FILE_PUBLICATION_OPS) + .unwrap() + .is_none() + ); + } + + #[test] + fn nested_part_digest_verification_accepts_exact_and_rejects_each_mismatch() { + let part = stream_parts::PartIdentity { + name: "tensor".into(), + parent_name: "parent".into(), + parent_dimensions: vec![1], + dimensions: vec![1], + source_kind: 0, + source_byte_offset: 0, + source_bytes: 4, + source_sha256: [1; 32], + derived_offset: 0, + derived_bytes: 4, + f32_sha256: [2; 32], + }; + let result = || kar_stream_encode::SectionResult { + bytes: 256, + digest: [3; 32], + source_digest: [1; 32], + derived_digest: [2; 32], + relative_l2: 0.0, + }; + assert!(verify_nested_part(&part, &result()).is_ok()); + + let mut bad_source = result(); + bad_source.source_digest = [4; 32]; + assert!(verify_nested_part(&part, &bad_source).is_err()); + + let mut bad_derived = result(); + bad_derived.derived_digest = [5; 32]; + assert!(verify_nested_part(&part, &bad_derived).is_err()); + } + + #[test] + fn raw_part_encoder_rejects_a_source_digest_mismatch() { + let fixture = overlay_fixture(); + let source_path = fixture.directory.join("raw-f32.bin"); + let section_path = fixture.directory.join("raw-part.section"); + let bytes = 1.25f32.to_le_bytes(); + fs::write(&source_path, bytes).unwrap(); + let mut source = File::open(source_path).unwrap(); + let mut part = raw_part_identity(); + assert_raw_part_mismatch(&mut source, &part, §ion_path); + assert_eq!(fs::read(§ion_path).unwrap(), bytes); + part.source_sha256 = Sha256::digest(bytes).into(); + fs::remove_file(§ion_path).unwrap(); + assert_raw_part_mismatch(&mut source, &part, §ion_path); + part.f32_sha256 = Sha256::digest(bytes).into(); + part.derived_bytes += 4; + fs::remove_file(§ion_path).unwrap(); + assert_raw_part_mismatch(&mut source, &part, §ion_path); + } + + fn raw_part_identity() -> stream_parts::PartIdentity { + stream_parts::PartIdentity { + name: "weight".into(), + parent_name: "weight".into(), + parent_dimensions: vec![1], + dimensions: vec![1], + source_kind: 0, + source_byte_offset: 0, + source_bytes: 4, + source_sha256: [0; 32], + derived_offset: 0, + derived_bytes: 4, + f32_sha256: [0; 32], + } + } + + fn assert_raw_part_mismatch(source: &mut File, part: &stream_parts::PartIdentity, path: &Path) { + let error = encode_raw_part(source, 0, part, path).err().unwrap(); + assert!(error.contains("RAW source or F32 digest mismatch")); + } + + #[test] + fn raw_spool_failure_removes_owned_partial_and_preserves_existing_output() { + let fixture = overlay_fixture(); + let source_path = fixture.directory.join("raw-source.bin"); + fs::write(&source_path, 2.5f32.to_le_bytes()).unwrap(); + let mut source = File::open(source_path).unwrap(); + assert_unsupported_raw_spool_removes_partial( + &mut source, + &fixture.directory.join("partial.raw"), + ); + assert_raw_spool_preserves_existing(&mut source, &fixture.directory.join("owned.raw")); + } + + fn assert_unsupported_raw_spool_removes_partial(source: &mut File, path: &Path) { + let request = RawF32Spool { + absolute: 0, + source_kind: u32::MAX, + source_bytes: 4, + path, + }; + let error = spool_raw_f32(source, request).unwrap_err(); + assert!(error.contains("unsupported GGUF source kind")); + assert!(!path.exists()); + } + + fn assert_raw_spool_preserves_existing(source: &mut File, path: &Path) { + fs::write(path, b"pre-existing").unwrap(); + let request = RawF32Spool { + absolute: 0, + source_kind: 0, + source_bytes: 4, + path, + }; + assert!(spool_raw_f32(source, request).is_err()); + assert_eq!(fs::read(path).unwrap(), b"pre-existing"); + } + + struct RejectRawWrite; + + impl std::io::Write for RejectRawWrite { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn raw_spool_writer_propagates_sink_errors() { + let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes()); + let result = write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut RejectRawWrite); + assert!(result.is_err()); + } + + fn reject_spool_sync(_: &File) -> std::io::Result<()> { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + + #[test] + fn raw_spool_sync_failure_removes_the_owned_file() { + let fixture = overlay_fixture(); + let source_path = fixture.directory.join("sync-source.bin"); + fs::write(&source_path, 2.5f32.to_le_bytes()).unwrap(); + let mut source = File::open(source_path).unwrap(); + let path = fixture.directory.join("sync-failure.raw"); + let result = spool_raw_f32_with_sync( + &mut source, + RawF32Spool { + absolute: 0, + source_kind: 0, + source_bytes: 4, + path: &path, + }, + reject_spool_sync, + ); + assert!(result.is_err()); + assert!(!path.exists()); + } + + #[test] + fn streamed_preparation_detects_identity_tensor_count_changed_before_run() { + let fixture = overlay_fixture(); + let mut identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + identity.shards.clear(); + let archive = fixture.directory.join("tensor-count-changed.kar"); + let preparation = StreamPreparation::new( + StreamPrepareRequest { + manifest: &fixture.manifest, + source_dir: &fixture.directory, + destination: &archive, + levels: 2, + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + }, + identity, + Vec::new(), + StagingDir::create(&archive).unwrap(), + ); + assert!( + preparation + .run() + .unwrap_err() + .contains("GGUF tensor count changed during preparation") + ); + assert!(!archive.exists()); + } + #[test] fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { assert_eq!( @@ -1973,6 +3264,614 @@ mod tests { assert_eq!(minimum_part_payload_bytes(4, 8).unwrap(), 4); assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err()); } + + #[test] + fn streamed_space_gate_rejects_empty_plan_and_unavailable_parent() { + assert!(require_streamed_space(Path::new("empty.kar"), &[], 2).is_err()); + let part = stream_parts::PartIdentity { + name: "weight".into(), + parent_name: "weight".into(), + parent_dimensions: vec![1], + dimensions: vec![1], + source_kind: 0, + source_byte_offset: 0, + source_bytes: 4, + source_sha256: [0; 32], + derived_offset: 0, + derived_bytes: 4, + f32_sha256: [0; 32], + }; + let absent = std::env::temp_dir().join(format!( + "strata-no-parent-{}-{}", + std::process::id(), + OVERLAY_FIXTURE_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let error = + require_streamed_space(&absent.join("archive.kar"), &[vec![part]], 2).unwrap_err(); + assert!(error.contains("KAR minimum payload does not fit")); + } + + #[test] + fn streamed_space_gate_rejects_count_limit_and_payload_sum_overflow() { + let part = stream_parts::PartIdentity { + name: "weight".into(), + parent_name: "weight".into(), + parent_dimensions: vec![1], + dimensions: vec![1], + source_kind: 0, + source_byte_offset: 0, + source_bytes: 4, + source_sha256: [0; 32], + derived_offset: 0, + derived_bytes: 4, + f32_sha256: [0; 32], + }; + let many = vec![part.clone(); 100_001]; + assert!(require_streamed_space(Path::new("unused.kar"), &[many], 1).is_err()); + + let huge = stream_parts::PartIdentity { + derived_bytes: u64::MAX - 3, + ..part + }; + assert!( + require_streamed_space(Path::new("unused.kar"), &[vec![huge.clone(); 5]], 8,) + .unwrap_err() + .contains("size overflow") + ); + } + + #[test] + fn sharded_archive_header_rejects_source_digest_size_and_record_count_mismatch() { + let identity = derived_mixed::ShardedIdentity { + derived_sha256: [1; 32], + derived_bytes: 8, + shards: Vec::new(), + tensors: Vec::new(), + }; + let mut summary = kar::Summary { + archive_bytes: 0, + tensor_count: 0, + total_elements: 2, + source_total_elements: 2, + accounted_bpw: 0.0, + source_digest: [1; 32], + source_bytes: 8, + max_planes: 0, + }; + assert!(verify_sharded_header(&identity, None, &summary, 0).is_ok()); + summary.source_digest = [2; 32]; + assert!(verify_sharded_header(&identity, None, &summary, 0).is_err()); + summary.source_digest = [1; 32]; + summary.source_bytes = 4; + assert!(verify_sharded_header(&identity, None, &summary, 0).is_err()); + summary.source_bytes = 8; + summary.source_total_elements = 1; + assert!(verify_sharded_header(&identity, None, &summary, 0).is_err()); + summary.source_total_elements = 2; + assert!(verify_sharded_header(&identity, None, &summary, 1).is_err()); + } + + #[test] + fn preparation_rejects_shard_modified_after_identity_derivation() { + let fixture = overlay_fixture(); + let identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + let parts = stream_parts::plan_shards(&identity, &fixture.directory).unwrap(); + let shard = shard_identity(&identity.shards[0]); + let destination = fixture.directory.join("changed-source.kar"); + let request = shard_prepare_request(&fixture.manifest, &fixture.directory, &destination); + let preparation = StreamPreparation::new( + request, + identity, + parts, + StagingDir::create(&fixture.directory.join("changed-source.kar")).unwrap(), + ); + let source_path = fixture.directory.join(&shard.name); + let source_file = File::open(&source_path).unwrap(); + assert_wrong_shard_size_rejected(&preparation, &shard, &source_path, &source_file); + assert_changed_shard_bytes_rejected(&preparation, &shard, &source_path, &source_file); + } + + fn shard_identity(source: &derived_mixed::ShardIdentity) -> derived_mixed::ShardIdentity { + derived_mixed::ShardIdentity { + name: source.name.clone(), + gguf_sha256: source.gguf_sha256, + gguf_bytes: source.gguf_bytes, + tensor_count: source.tensor_count, + } + } + + fn shard_prepare_request<'a>( + manifest: &'a Manifest, + source_dir: &'a Path, + destination: &'a Path, + ) -> StreamPrepareRequest<'a> { + StreamPrepareRequest { + manifest, + source_dir, + destination, + levels: 2, + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + } + } + + fn assert_wrong_shard_size_rejected( + preparation: &StreamPreparation<'_>, + shard: &derived_mixed::ShardIdentity, + path: &Path, + file: &File, + ) { + let wrong = derived_mixed::ShardIdentity { + name: shard.name.clone(), + gguf_sha256: shard.gguf_sha256, + gguf_bytes: shard.gguf_bytes + 1, + tensor_count: shard.tensor_count, + }; + assert!( + preparation + .verify_shard_file(&wrong, path, file) + .unwrap_err() + .contains("changed during preparation") + ); + } + + fn assert_changed_shard_bytes_rejected( + preparation: &StreamPreparation<'_>, + shard: &derived_mixed::ShardIdentity, + path: &Path, + file: &File, + ) { + let original = fs::read(path).unwrap(); + let mut changed = original.clone(); + *changed.last_mut().unwrap() ^= 1; + fs::write(path, changed).unwrap(); + assert!( + preparation + .verify_shard_file(shard, path, file) + .unwrap_err() + .contains("changed during preparation") + ); + fs::write(path, original).unwrap(); + } + + #[test] + fn pending_intent_requires_matching_regular_json_and_removes_idempotently() { + let fixture = overlay_fixture(); + let intent = fixture.directory.join("publish.pending.json"); + let expected = serde_json::json!({"schema":"test/pending-v1"}); + assert_matching_pending_intent(&intent, &expected); + assert_malformed_pending_intent_is_rejected(&fixture.directory); + assert_non_file_pending_intent_is_rejected(&fixture.directory); + assert!(has_pending_streamed_publication(Path::new("bad\0archive.kar")).is_err()); + } + + fn assert_matching_pending_intent(intent: &Path, expected: &serde_json::Value) { + assert_eq!(read_json_if_regular(intent).unwrap(), None); + ensure_pending_intent(intent, expected).unwrap(); + assert_eq!( + read_json_if_regular(intent).unwrap(), + Some(expected.clone()) + ); + assert!(read_json_if_regular_with_open(intent, fail_json_open).is_err()); + ensure_pending_intent(intent, expected).unwrap(); + assert!(ensure_pending_intent(intent, &serde_json::json!({})).is_err()); + remove_pending_intent(intent).unwrap(); + remove_pending_intent(intent).unwrap(); + } + + fn assert_malformed_pending_intent_is_rejected(directory: &Path) { + let malformed = directory.join("malformed.pending.json"); + fs::write(&malformed, b"not-json").unwrap(); + assert!(read_json_if_regular(&malformed).is_err()); + assert!(read_json_if_regular(Path::new("bad\0intent.json")).is_err()); + } + + fn assert_non_file_pending_intent_is_rejected(directory: &Path) { + let path = directory.join("not-file"); + fs::create_dir(&path).unwrap(); + assert!(read_json_if_regular(&path).is_err()); + assert!(remove_pending_intent(&path).is_err()); + } + + #[cfg(unix)] + #[test] + fn streamed_pending_intent_symlink_fails_closed() { + let fixture = overlay_fixture(); + let archive = fixture.directory.join("symlink.kar"); + let pending = streamed_publish_intent_path(&archive).unwrap(); + let target = fixture.directory.join("target.json"); + fs::write(&target, b"{}").unwrap(); + std::os::unix::fs::symlink(&target, &pending).unwrap(); + assert!(has_pending_streamed_publication(&archive).is_err()); + assert!(read_json_if_regular(&pending).is_err()); + } + + #[test] + fn publication_preflight_checks_archive_provenance_and_intent_states() { + let fixture = overlay_fixture(); + assert!(ensure_output_is_free(&fixture.base).is_err()); + + let destination = fixture.directory.join("free.kar"); + assert!(!has_pending_streamed_publication(&destination).unwrap()); + let intent = streamed_publish_intent_path(&destination).unwrap(); + fs::write(&intent, b"{}").unwrap(); + assert!(has_pending_streamed_publication(&destination).unwrap()); + + fs::remove_file(&intent).unwrap(); + fs::write(provenance_path(&destination).unwrap(), b"{}").unwrap(); + assert!(ensure_output_is_free(&destination).is_err()); + } + + #[test] + fn pending_probe_rejects_a_directory_instead_of_a_regular_intent() { + let fixture = overlay_fixture(); + let destination = fixture.directory.join("directory-intent.kar"); + fs::create_dir(streamed_publish_intent_path(&destination).unwrap()).unwrap(); + assert!(has_pending_streamed_publication(&destination).is_err()); + } + + #[test] + fn pending_publication_probe_surfaces_non_directory_parent_errors() { + let fixture = overlay_fixture(); + let file = fixture.directory.join("parent-file"); + fs::write(&file, b"not a directory").unwrap(); + assert!(has_pending_streamed_publication(&file.join("archive.kar")).is_err()); + } + + #[test] + fn pending_probe_surfaces_errors_that_arrive_between_sidecar_and_intent_checks() { + let fixture = overlay_fixture(); + let destination = fixture.directory.join("racing-probe.kar"); + let lookups = std::cell::Cell::new(0); + let result = has_pending_streamed_publication_with_lookup(&destination, |_: &Path| { + let call = lookups.get(); + lookups.set(call + 1); + let kind = if call == 0 { + std::io::ErrorKind::NotFound + } else { + std::io::ErrorKind::PermissionDenied + }; + Err(std::io::Error::from(kind)) + }); + assert!(result.is_err()); + assert_eq!(lookups.get(), 2); + } + + #[test] + fn streamed_recovery_rejects_intent_bound_to_different_source_policy() { + let fixture = overlay_fixture(); + let archive = fixture.directory.join("recover-intent.kar"); + prepare_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).unwrap(); + fs::remove_file(provenance_path(&archive).unwrap()).unwrap(); + let intent = streamed_publish_intent_path(&archive).unwrap(); + fs::write(&intent, br#"{"schema":"wrong-policy"}"#).unwrap(); + assert!( + recover_sharded_streamed_provenance( + &fixture.manifest, + &fixture.directory, + &archive, + 2, + None, + ) + .is_err() + ); + assert!(intent.exists()); + assert!(!provenance_path(&archive).unwrap().exists()); + } + + #[test] + fn streamed_level_validation_rejects_archive_with_excess_planes() { + let manifest = Manifest { + schema_version: 0, + files: Vec::new(), + }; + let request = StreamVerifyRequest { + manifest: &manifest, + source_dir: Path::new("unused"), + archive_path: Path::new("unused.kar"), + streamed_levels: Some(1), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, + }; + let summary = kar::Summary { + archive_bytes: 0, + tensor_count: 0, + total_elements: 0, + source_total_elements: 0, + accounted_bpw: 0.0, + source_digest: [0; 32], + source_bytes: 0, + max_planes: 2, + }; + assert!(validate_streamed_levels(&request, &summary).is_err()); + } + + #[test] + fn streamed_ple_verifier_rejects_invalid_levels_before_archive_access() { + let fixture = overlay_fixture(); + let error = verify_sharded_streamed_ple( + &fixture.manifest, + &fixture.directory, + &fixture.directory.join("unused.kar"), + 0, + 128, + ) + .unwrap_err(); + assert!(error.contains("1..=8 KAR levels")); + } + + #[test] + fn sharded_tensor_identity_rejects_rank_and_metadata_mismatch() { + let tensor = gguf::TensorInfo { + name: "weight".into(), + dimensions: vec![1, 1, 1, 1, 1], + kind: 0, + offset: 0, + bytes: 4, + }; + let mut derived = derived_mixed::TensorIdentity { + name: "weight".into(), + source_kind: 0, + source_sha256: [0; 32], + derived_offset: 0, + derived_bytes: 4, + f32_sha256: [0; 32], + }; + assert!(validate_tensor_identity(&tensor, &derived).is_err()); + + let rank_one = gguf::TensorInfo { + dimensions: vec![1], + ..tensor + }; + derived.source_kind = 1; + assert!(validate_tensor_identity(&rank_one, &derived).is_err()); + derived.source_kind = 0; + derived.derived_bytes = 8; + assert!(validate_tensor_identity(&rank_one, &derived).is_err()); + derived.derived_bytes = 4; + derived.name = "other-weight".into(); + assert!(validate_tensor_identity(&rank_one, &derived).is_err()); + } + + #[test] + fn shard_architecture_mismatch_is_rejected_before_preparation() { + let fixture = overlay_fixture(); + let identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + let parts = stream_parts::plan_shards(&identity, &fixture.directory).unwrap(); + let mut shard = shard_identity(&identity.shards[0]); + let destination = fixture.directory.join("architecture-mismatch.kar"); + let request = shard_prepare_request(&fixture.manifest, &fixture.directory, &destination); + let mut preparation = StreamPreparation::new( + request, + identity, + parts, + StagingDir::create(&destination).unwrap(), + ); + let index = gguf::tensor_index(&fixture.directory.join(&shard.name)).unwrap(); + assert_shard_index_mismatches(&mut preparation, &mut shard, &index); + } + + fn assert_shard_index_mismatches( + preparation: &mut StreamPreparation<'_>, + shard: &mut derived_mixed::ShardIdentity, + index: &gguf::TensorIndex, + ) { + preparation.architecture = Some("different-architecture".into()); + assert!(preparation.check_shard_index(shard, index).is_err()); + preparation.architecture = None; + shard.tensor_count += 1; + assert!(preparation.check_shard_index(shard, index).is_err()); + shard.tensor_count -= 1; + shard.gguf_bytes += 1; + assert!(preparation.check_shard_index(shard, index).is_err()); + } + + #[test] + fn sharded_tensor_record_accepts_matching_identity_and_shape() { + let identity = derived_mixed::TensorIdentity { + name: "weight".into(), + source_kind: 0, + source_sha256: [0; 32], + derived_offset: 16, + derived_bytes: 8, + f32_sha256: [7; 32], + }; + assert!(verify_tensor_records(&[source_record()], &[identity]).is_ok()); + } + + #[test] + fn tensor_shape_predicate_rejects_mismatch_and_overflow() { + assert!(tensor_shape_matches_derived_bytes(&[2, 4], 32)); + assert!(!tensor_shape_matches_derived_bytes(&[2, 3], 32)); + assert!(!tensor_shape_matches_derived_bytes( + &[u64::MAX, 2], + u64::MAX + )); + } + + #[test] + fn preparation_returns_post_index_source_open_errors() { + let fixture = overlay_fixture(); + let identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + let parts = stream_parts::plan_shards(&identity, &fixture.directory).unwrap(); + let shard = shard_identity(&identity.shards[0]); + let archive = fixture.directory.join("open-failure.kar"); + let request = shard_prepare_request(&fixture.manifest, &fixture.directory, &archive); + let staging = StagingDir::create(&archive).unwrap(); + let mut preparation = StreamPreparation::new(request, identity, parts, staging); + assert_post_index_open_error(&mut preparation, &shard); + } + + fn assert_post_index_open_error( + preparation: &mut StreamPreparation<'_>, + shard: &derived_mixed::ShardIdentity, + ) { + let error = preparation.prepare_shard_with_open(shard, |_| { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + }); + assert_eq!( + error.unwrap_err(), + std::io::Error::from(std::io::ErrorKind::PermissionDenied).to_string() + ); + } + + #[test] + fn streamed_staging_refuses_existing_directory_and_root_destination() { + let fixture = overlay_fixture(); + let archive = fixture.directory.join("staging.kar"); + let staging = StagingDir::create(&archive).unwrap(); + assert!(StagingDir::create(&archive).is_err()); + assert!(StagingDir::create(Path::new("/")).is_err()); + drop(staging); + } + + #[test] + fn streamed_verification_rejects_tampered_provenance_fields() { + let fixture = overlay_fixture(); + let archive = fixture.directory.join("verified.kar"); + prepare_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).unwrap(); + verify_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).unwrap(); + let sidecar = provenance_path(&archive).unwrap(); + let mut recorded: serde_json::Value = + serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); + recorded["archive_sha256"] = serde_json::json!("wrong-digest"); + fs::write(&sidecar, serde_json::to_vec(&recorded).unwrap()).unwrap(); + assert!( + verify_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).is_err() + ); + } + + #[test] + fn streamed_verification_rejects_missing_and_malformed_provenance() { + let fixture = overlay_fixture(); + let archive = fixture.directory.join("missing-provenance.kar"); + prepare_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).unwrap(); + let sidecar = provenance_path(&archive).unwrap(); + fs::remove_file(&sidecar).unwrap(); + assert!( + verify_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).is_err() + ); + fs::write(&sidecar, b"not JSON").unwrap(); + assert!( + verify_sharded_streamed(&fixture.manifest, &fixture.directory, &archive, 2).is_err() + ); + } + + struct LimitedProvenanceWriter(usize); + + impl std::io::Write for LimitedProvenanceWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.0 == 0 { + return Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)); + } + let accepted = self.0.min(bytes.len()); + self.0 -= accepted; + Ok(accepted) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn provenance_serialization_propagates_json_and_newline_write_errors() { + let value = serde_json::json!({"source":"fixture"}); + assert!(write_provenance_json(&mut LimitedProvenanceWriter(0), &value).is_err()); + let size = serde_json::to_vec_pretty(&value).unwrap().len(); + assert!(write_provenance_json(&mut LimitedProvenanceWriter(size), &value).is_err()); + } + + fn reject_provenance_sync(_: &File) -> std::io::Result<()> { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + + #[test] + fn provenance_sync_failure_is_reported_after_writing_complete_json() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("unsynced.json"); + let mut file = File::create(&path).unwrap(); + assert!( + write_provenance_contents_with_sync( + &mut file, + &serde_json::json!({"source":"fixture"}), + reject_provenance_sync, + ) + .is_err() + ); + assert!(serde_json::from_slice::(&fs::read(path).unwrap()).is_ok()); + } + + #[test] + fn archive_hash_reports_missing_source_file() { + let fixture = overlay_fixture(); + assert!(hash_file(&fixture.directory.join("missing.bin")).is_err()); + } + + fn fail_provenance_publish(_: &Path, _: &Path) -> std::io::Result<()> { + Err(std::io::Error::other( + "injected provenance hard-link failure", + )) + } + + #[test] + fn provenance_publish_failure_cleans_its_temporary_file() { + let fixture = overlay_fixture(); + let destination = fixture.directory.join("publish-failure.json"); + let expected = serde_json::json!({"schema":"test/v1"}); + assert!( + write_provenance_with_ops( + &destination, + &expected, + fail_provenance_publish, + remove_file_path, + ) + .is_err() + ); + assert!(!destination.exists()); + assert_eq!(fs::read_dir(&fixture.directory).unwrap().count(), 5); + } + + #[test] + fn provenance_temp_collision_retries_without_replacing_existing_file() { + let fixture = overlay_fixture(); + let destination = fixture.directory.join("collision.json"); + let collision = fixture + .directory + .join(format!("collision.json.part-{}-7", std::process::id())); + fs::write(&collision, b"unrelated reservation").unwrap(); + let mut sequence = 7; + let (temporary, file) = create_provenance_temp_with_sequence(&destination, || { + let current = sequence; + sequence += 1; + current + }) + .unwrap(); + drop(file); + assert!(temporary.exists() && temporary != collision); + assert_eq!(fs::read(&collision).unwrap(), b"unrelated reservation"); + assert!(create_provenance_temp_with_sequence(&destination, || 7).is_err()); + fs::remove_file(temporary).unwrap(); + } + + #[test] + fn provenance_temp_creation_surfaces_parent_path_errors_without_mutation() { + let fixture = overlay_fixture(); + let parent = fixture.directory.join("not-a-directory"); + fs::write(&parent, b"keep this file").unwrap(); + let destination = parent.join("sidecar.json"); + assert!(create_provenance_temp_with_sequence(&destination, || 1).is_err()); + assert_eq!(fs::read(parent).unwrap(), b"keep this file"); + } + + #[test] + fn archive_hash_surfaces_directory_read_errors() { + let fixture = overlay_fixture(); + assert!(hash_file(&fixture.directory).is_err()); + } use crate::model::ModelFile; fn string(out: &mut Vec, value: &str) { @@ -2010,6 +3909,219 @@ mod tests { gguf } + struct OverlayFixture { + directory: PathBuf, + values: Vec, + manifest: Manifest, + base: PathBuf, + policy: PathBuf, + overlay: PathBuf, + } + + impl Drop for OverlayFixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.directory); + } + } + + fn overlay_fixture() -> OverlayFixture { + let directory = std::env::temp_dir().join(format!( + "strata-overlay-{}-{}", + std::process::id(), + OVERLAY_FIXTURE_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&directory).unwrap(); + build_overlay_shards(&directory) + } + + fn build_overlay_shards(directory: &Path) -> OverlayFixture { + let values = (0..256) + .map(|index| (index as f32 - 127.5) / 128.0) + .collect::>(); + let files = overlay_model_files(directory, &values); + let manifest = Manifest { + schema_version: 1, + files, + }; + let base = directory.join("base.kar"); + prepare_sharded_streamed(&manifest, directory, &base, 2).unwrap(); + let policy = overlay_candidate_policy(directory, &base); + OverlayFixture { + directory: directory.to_path_buf(), + values, + manifest, + base, + policy, + overlay: directory.join("overlay.kar"), + } + } + + fn overlay_model_files(directory: &Path, values: &[f32]) -> Vec { + let dense = values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + [ + ("a.gguf", one_shard("dense", 0, 256, &dense)), + ( + "b.gguf", + one_shard_with_arch("extra", 21, 256, &[0; iq3_s::BLOCK_BYTES], false), + ), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect() + } + + fn overlay_candidate_policy(directory: &Path, base: &Path) -> PathBuf { + let prepared = serde_json::from_slice::( + &fs::read(provenance_path(base).unwrap()).unwrap(), + ) + .unwrap(); + let path = directory.join("candidates.json"); + let policy = serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": prepared["archive_sha256"], + "proposed_levels": 3, "records": [{"name": "dense", "elements": 256}], + }); + fs::write(&path, serde_json::to_vec(&policy).unwrap()).unwrap(); + path + } + + impl OverlayFixture { + fn prepare(&self) -> Result { + self.prepare_to(&self.overlay) + } + + fn prepare_to(&self, destination: &Path) -> Result { + crate::kar_overlay::prepare( + &self.manifest, + &self.directory, + &self.base, + &self.policy, + destination, + ) + } + + fn pending(&self) -> PathBuf { + self.overlay.with_file_name("overlay.kar.pending.json") + } + } + + fn check_overlay_reconstruction( + fixture: &OverlayFixture, + result: &crate::kar_overlay::Summary, + ) { + let decoded = kar::decode_preview_tensor(&fixture.overlay, "dense", 3).unwrap(); + let error = decoded + .iter() + .zip(&fixture.values) + .map(|(actual, expected)| f64::from(actual - expected).powi(2)) + .sum::(); + let reference = fixture + .values + .iter() + .map(|value| f64::from(*value).powi(2)) + .sum::(); + assert!(((error / reference).sqrt() - result.maximum_relative_l2).abs() < 1e-7); + } + + fn check_overlay_selection(fixture: &OverlayFixture, result: &crate::kar_overlay::Summary) { + let comparison = crate::kar_overlay::compare( + &fixture.manifest, + &fixture.directory, + &fixture.base, + &fixture.overlay, + ) + .unwrap(); + assert_eq!(comparison.records[0].name, "dense"); + assert_eq!( + comparison.records[0].overlay_relative_l2, + result.maximum_relative_l2 + ); + let selection = + crate::kar_overlay::resolve_verified(&fixture.base, &fixture.overlay).unwrap(); + assert_eq!(selection.replacement_count, 1); + assert_eq!(selection.records[0].archive, "overlay"); + assert_eq!(selection.records[1].archive, "base"); + } + + fn assert_overlay_interrupted(fixture: &OverlayFixture, stage: u8) { + assert_eq!(fixture.pending().exists(), stage < 4); + assert_eq!(fixture.overlay.exists(), stage >= 2); + assert_eq!(fixture.overlay_sidecar().exists(), stage >= 3); + } + + fn assert_overlay_recovered(fixture: &OverlayFixture) { + let (summary, records) = kar::verify_with_sources(&fixture.overlay).unwrap(); + assert_eq!(summary.max_planes, 3); + assert_eq!(records.len(), 1); + assert!(fixture.overlay_sidecar().exists()); + assert!(!fixture.pending().exists()); + assert_eq!( + crate::kar_overlay::resolve_verified(&fixture.base, &fixture.overlay) + .unwrap() + .replacement_count, + 1 + ); + } + + fn preserve_unrelated_overlay_outputs() { + for (name, bytes) in [ + ("overlay.kar", b"unrelated archive".as_slice()), + ( + "overlay.kar.provenance.json", + b"unrelated sidecar".as_slice(), + ), + ] { + let fixture = overlay_fixture(); + let destination = fixture.directory.join(name); + fs::write(&destination, bytes).unwrap(); + assert!(fixture.prepare().is_err()); + assert_eq!(fs::read(destination).unwrap(), bytes); + } + } + + fn assert_overlay_staging_removed(fixture: &OverlayFixture) { + let staging = format!("overlay.kar.overlay-sections-{}", std::process::id()); + assert!(!fixture.directory.join(staging).exists()); + assert_eq!( + fs::read_dir(&fixture.directory) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "part")) + .count(), + 0, + ); + } + + fn reject_corrupt_overlay_provenance( + fixture: &OverlayFixture, + result: &crate::kar_overlay::Summary, + ) { + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap(); + value["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); + fs::write(&result.provenance_path, serde_json::to_vec(&value).unwrap()).unwrap(); + assert!(crate::kar_overlay::resolve_verified(&fixture.base, &fixture.overlay).is_err()); + } + + impl OverlayFixture { + fn overlay_sidecar(&self) -> PathBuf { + self.overlay.with_file_name("overlay.kar.provenance.json") + } + } + + static OVERLAY_FIXTURE_SEQUENCE: AtomicU64 = AtomicU64::new(0); + fn two_f32_shard_manifest(directory: &Path) -> Manifest { let f32_payload = (0..64) .flat_map(|index| (index as f32).to_le_bytes()) @@ -2055,6 +4167,10 @@ mod tests { )) } + fn fail_json_open(_: &Path) -> std::io::Result { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + fn ple_shard(payload: &[u8]) -> Vec { let mut gguf = b"GGUF".to_vec(); gguf.extend_from_slice(&3u32.to_le_bytes()); @@ -2076,73 +4192,87 @@ mod tests { #[test] fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&2u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - for (name, offset) in [("first", 0u64), ("second", 128)] { - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&32u64.to_le_bytes()); - gguf.extend_from_slice(&0u32.to_le_bytes()); - gguf.extend_from_slice(&offset.to_le_bytes()); - } - let data_start = gguf.len().div_ceil(32) * 32; - gguf.resize(data_start, 0); - for index in 0..64 { - let value = [-1.0f32, -0.25, 0.25, 1.0][index % 4]; - gguf.extend_from_slice(&value.to_le_bytes()); - } - let source_path = - std::env::temp_dir().join(format!("strata-preview-{}.gguf", std::process::id())); - let output = - std::env::temp_dir().join(format!("strata-preview-{}.kar", std::process::id())); + let gguf = two_tensor_f32_gguf(); + let source = preview_test_path("two-tensor", "gguf"); + let output = preview_test_path("two-tensor", "kar"); let _ = fs::remove_file(&output); - fs::write(&source_path, &gguf).unwrap(); - let summary = prepare_f32(&source_path, &output, 2).unwrap(); + fs::write(&source, &gguf).unwrap(); + let summary = prepare_f32(&source, &output, 2).unwrap(); + assert_two_tensor_archive(&summary, &source, &output); + assert_duplicate_archive_rejected(&source, &output); + assert_invalid_normalization_rejected(&gguf); + fs::remove_file(output).unwrap(); + fs::remove_file(source).unwrap(); + } + + fn preview_test_path(label: &str, extension: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "strata-{label}-{}.{}", + std::process::id(), + extension + )) + } + + fn two_tensor_f32_gguf() -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&2u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + string(&mut bytes, "general.architecture"); + bytes.extend_from_slice(&8u32.to_le_bytes()); + string(&mut bytes, "qwen35"); + for (name, offset) in [("first", 0u64), ("second", 128)] { + append_f32_tensor_record(&mut bytes, name, offset); + } + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + for index in 0..64 { + bytes.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()); + } + bytes + } + + fn append_f32_tensor_record(bytes: &mut Vec, name: &str, offset: u64) { + string(bytes, name); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&32u64.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&offset.to_le_bytes()); + } + + fn assert_two_tensor_archive(summary: &PreviewSummary, source: &Path, output: &Path) { assert_eq!(summary.archive.tensor_count, 2); assert_eq!(summary.archive.total_elements, 64); assert!(summary.maximum_relative_l2.is_finite()); - assert_eq!( - summary.archive.source_digest, - hash_file(&source_path).unwrap() - ); - assert_eq!(summary.archive_digest, hash_file(&output).unwrap()); - let staging = output.with_file_name(format!( + assert_eq!(summary.archive.source_digest, hash_file(source).unwrap()); + assert_eq!(summary.archive_digest, hash_file(output).unwrap()); + assert!(!preview_staging_path(output).exists()); + } + + fn assert_duplicate_archive_rejected(source: &Path, output: &Path) { + assert!(prepare_f32(source, output, 2).is_err()); + assert!(!preview_staging_path(output).exists()); + } + + fn assert_invalid_normalization_rejected(gguf: &[u8]) { + let source = preview_test_path("two-tensor-bad", "gguf"); + let output = preview_test_path("two-tensor-bad", "kar"); + let mut broken = gguf.to_vec(); + let last = broken.len() - 4; + broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); + fs::write(&source, broken).unwrap(); + let error = prepare_f32(&source, &output, 2).unwrap_err(); + assert!(error.contains("invalid KAR normalization input")); + assert!(!output.exists()); + assert!(!preview_staging_path(&output).exists()); + fs::remove_file(source).unwrap(); + } + + fn preview_staging_path(output: &Path) -> PathBuf { + output.with_file_name(format!( "{}.parts-{}", output.file_name().unwrap().to_string_lossy(), std::process::id() - )); - assert!(!staging.exists()); - assert!(prepare_f32(&source_path, &output, 2).is_err()); - assert!(!staging.exists()); - let failed_source = - std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id())); - let failed_output = - std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id())); - let _ = fs::remove_file(&failed_output); - let mut broken = gguf.clone(); - let last = broken.len() - 4; - broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); - fs::write(&failed_source, broken).unwrap(); - assert!( - prepare_f32(&failed_source, &failed_output, 2) - .unwrap_err() - .contains("invalid KAR normalization input") - ); - assert!(!failed_output.exists()); - let failed_staging = failed_output.with_file_name(format!( - "{}.parts-{}", - failed_output.file_name().unwrap().to_string_lossy(), - std::process::id() - )); - assert!(!failed_staging.exists()); - fs::remove_file(failed_source).unwrap(); - fs::remove_file(&output).unwrap(); - fs::remove_file(&source_path).unwrap(); + )) } #[test] @@ -2178,48 +4308,66 @@ mod tests { #[test] fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - string(&mut gguf, "expert"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&256u64.to_le_bytes()); - gguf.extend_from_slice(&21u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let source_path = preview_test_path("iq3-good", "gguf"); + let output = preview_test_path("iq3-good", "kar"); + let provenance = provenance_path(&output).unwrap(); + let _ = fs::remove_file(&output); + let _ = fs::remove_file(&provenance); + fs::write(&source_path, iq3_preview_gguf()).unwrap(); + let identity = derived_iq3::fingerprint(&source_path).unwrap(); + let result = prepare_iq3(&source_path, &output, 2).unwrap(); + assert_iq3_preview_identity(&result, &identity, &source_path, &output, &provenance); + assert_iq3_provenance_reuse(&source_path, &output, &provenance); + assert_iq3_preflight_rejects_reserved_provenance(&source_path); + fs::remove_file(provenance).unwrap(); + fs::remove_file(output).unwrap(); + fs::remove_file(source_path).unwrap(); + } + + fn iq3_preview_gguf() -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + string(&mut bytes, "general.architecture"); + bytes.extend_from_slice(&8u32.to_le_bytes()); + string(&mut bytes, "qwen35"); + string(&mut bytes, "expert"); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&256u64.to_le_bytes()); + bytes.extend_from_slice(&21u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend_from_slice(&iq3_preview_block()); + bytes + } + + fn iq3_preview_block() -> [u8; iq3_s::BLOCK_BYTES] { let mut block = [0u8; iq3_s::BLOCK_BYTES]; block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); for (index, byte) in block[2..66].iter_mut().enumerate() { *byte = (index as u8).wrapping_mul(3); } block[74] = 0x55; - gguf.extend_from_slice(&block); - let base = - std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id())); - let source_path = base.with_extension("gguf"); - let output = base.with_extension("kar"); - let provenance = output.with_file_name(format!( - "{}.provenance.json", - output.file_name().unwrap().to_string_lossy() - )); - let _ = fs::remove_file(&output); - let _ = fs::remove_file(&provenance); - fs::write(&source_path, gguf).unwrap(); - let identity = derived_iq3::fingerprint(&source_path).unwrap(); - let result = prepare_iq3(&source_path, &output, 2).unwrap(); + block + } + + fn assert_iq3_preview_identity( + result: &PreviewSummary, + identity: &derived_iq3::Identity, + source: &Path, + output: &Path, + provenance: &Path, + ) { assert_eq!(result.archive.source_digest, identity.derived_sha256); assert_eq!(result.archive.source_bytes, identity.derived_bytes); + let canonical_provenance = fs::canonicalize(provenance).unwrap(); assert_eq!( result.provenance_path.as_deref(), - Some(provenance.as_path()) + Some(canonical_provenance.as_path()) ); - assert_eq!(kar::verify(&output).unwrap(), result.archive); - let record: serde_json::Value = - serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); + assert_eq!(kar::verify(output).unwrap(), result.archive); + let record = read_json(provenance); assert_eq!( record["original_gguf_sha256"], hex::encode(identity.gguf_sha256) @@ -2230,63 +4378,96 @@ mod tests { ); assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest)); assert!(result.maximum_relative_l2.is_finite()); - assert_eq!(verify_iq3(&source_path, &output).unwrap(), result.archive); - let saved_provenance = fs::read(&provenance).unwrap(); - let mut changed = record.clone(); + assert_eq!(verify_iq3(source, output).unwrap(), result.archive); + } + + fn assert_iq3_provenance_reuse(source: &Path, output: &Path, provenance: &Path) { + assert!(read_json(provenance).is_object()); + assert!(verify_iq3(source, output).is_ok()); + let saved = fs::read(provenance).unwrap(); + let mut changed: serde_json::Value = serde_json::from_slice(&saved).unwrap(); changed["archive_sha256"] = serde_json::Value::String("00".repeat(32)); - fs::write(&provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); + fs::write(provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); assert!( - verify_iq3(&source_path, &output) + verify_iq3(source, output) .unwrap_err() .contains("provenance differs") ); - fs::write(&provenance, saved_provenance).unwrap(); - assert!(verify_iq3(&source_path, &output).is_ok()); - let blocked_output = base.with_file_name(format!( - "strata-preview-iq3-blocked-{}.kar", - std::process::id() - )); - let blocked_provenance = blocked_output.with_file_name(format!( - "{}.provenance.json", - blocked_output.file_name().unwrap().to_string_lossy() - )); - let _ = fs::remove_file(&blocked_output); - fs::write(&blocked_provenance, b"reserved").unwrap(); + fs::write(provenance, saved).unwrap(); + assert!(verify_iq3(source, output).is_ok()); + } + + fn read_json(path: &Path) -> serde_json::Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() + } + + fn assert_iq3_preflight_rejects_reserved_provenance(source: &Path) { + let output = preview_test_path("iq3-blocked", "kar"); + let provenance = provenance_path(&output).unwrap(); + let _ = fs::remove_file(&output); + fs::write(&provenance, b"reserved").unwrap(); assert!( - prepare_iq3(&source_path, &blocked_output, 2) + prepare_iq3(source, &output, 2) .unwrap_err() .contains("provenance destination already exists") ); - assert!(!blocked_output.exists()); - fs::remove_file(blocked_provenance).unwrap(); + assert!(!output.exists()); fs::remove_file(provenance).unwrap(); - fs::remove_file(output).unwrap(); - fs::remove_file(source_path).unwrap(); } #[test] fn prepares_and_verifies_mixed_preview_with_each_source_kind() { - let tensors = [ + let source = preview_test_path("mixed", "gguf"); + let output = preview_test_path("mixed", "kar"); + let provenance = provenance_path(&output).unwrap(); + let _ = fs::remove_file(&output); + let _ = fs::remove_file(&provenance); + fs::write(&source, mixed_preview_gguf()).unwrap(); + let identity = derived_mixed::fingerprint(&source).unwrap(); + let result = prepare_mixed(&source, &output, 2).unwrap(); + assert_mixed_preview(&result, &identity, &source, &output, &provenance); + fs::remove_file(provenance).unwrap(); + fs::remove_file(output).unwrap(); + fs::remove_file(source).unwrap(); + } + + fn mixed_preview_gguf() -> Vec { + let specs = [ ("bf16", 30u32, 320u64, 32u64), ("iq3", 21, 0, 256), ("f16", 1, 256, 32), ("f32", 0, 128, 32), ]; - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - for (name, kind, offset, elements) in tensors { - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&elements.to_le_bytes()); - gguf.extend_from_slice(&kind.to_le_bytes()); - gguf.extend_from_slice(&offset.to_le_bytes()); + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&(specs.len() as u64).to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + string(&mut bytes, "general.architecture"); + bytes.extend_from_slice(&8u32.to_le_bytes()); + string(&mut bytes, "qwen35"); + for (name, kind, offset, elements) in specs { + append_preview_tensor_record(&mut bytes, name, kind, offset, elements); } - gguf.resize(gguf.len().div_ceil(32) * 32, 0); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend_from_slice(&mixed_preview_payload()); + bytes + } + + fn append_preview_tensor_record( + bytes: &mut Vec, + name: &str, + kind: u32, + offset: u64, + elements: u64, + ) { + string(bytes, name); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&elements.to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(&offset.to_le_bytes()); + } + + fn mixed_preview_payload() -> Vec { let mut payload = vec![0u8; 384]; payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); for (index, byte) in payload[2..66].iter_mut().enumerate() { @@ -2295,111 +4476,187 @@ mod tests { payload[74] = 0x55; let values = [-1.0f32, -0.25, 0.25, 1.0]; for index in 0..32 { - let value = values[index % values.len()]; - payload[128 + 4 * index..132 + 4 * index].copy_from_slice(&value.to_le_bytes()); - let f16 = kar_codec::f32_to_f16_bits(value).to_le_bytes(); - payload[256 + 2 * index..258 + 2 * index].copy_from_slice(&f16); - let bf16 = (value.to_bits() >> 16) as u16; - payload[320 + 2 * index..322 + 2 * index].copy_from_slice(&bf16.to_le_bytes()); + write_mixed_value(&mut payload, index, values[index % values.len()]); } - gguf.extend_from_slice(&payload); - let base = - std::env::temp_dir().join(format!("strata-preview-mixed-{}", std::process::id())); - let source_path = base.with_extension("gguf"); - let output = base.with_extension("kar"); - let provenance = provenance_path(&output).unwrap(); - let _ = fs::remove_file(&output); - let _ = fs::remove_file(&provenance); - fs::write(&source_path, gguf).unwrap(); - let identity = derived_mixed::fingerprint(&source_path).unwrap(); - let result = prepare_mixed(&source_path, &output, 2).unwrap(); + payload + } + + fn write_mixed_value(payload: &mut [u8], index: usize, value: f32) { + payload[128 + 4 * index..132 + 4 * index].copy_from_slice(&value.to_le_bytes()); + payload[256 + 2 * index..258 + 2 * index] + .copy_from_slice(&kar_codec::f32_to_f16_bits(value).to_le_bytes()); + payload[320 + 2 * index..322 + 2 * index] + .copy_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); + } + + fn assert_mixed_preview( + result: &PreviewSummary, + identity: &derived_mixed::Identity, + source: &Path, + output: &Path, + provenance: &Path, + ) { assert_eq!(result.archive.source_digest, identity.derived_sha256); assert_eq!(result.archive.source_bytes, identity.derived_bytes); assert_eq!(result.archive.tensor_count, 4); - assert_eq!(verify_mixed(&source_path, &output).unwrap(), result.archive); - assert!(verify_iq3(&source_path, &output).is_err()); - let record: serde_json::Value = - serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); + assert_eq!(verify_mixed(source, output).unwrap(), result.archive); + assert!(verify_iq3(source, output).is_err()); + let record = read_json(provenance); assert_eq!(record["schema"], "strata-next/mixed-preview-provenance-v1"); assert_eq!(record["tensors"][0]["source_kind"], 30); assert!(result.maximum_relative_l2.is_finite()); - fs::remove_file(provenance).unwrap(); - fs::remove_file(output).unwrap(); - fs::remove_file(source_path).unwrap(); } #[tokio::test] async fn prepares_and_verifies_manifest_pinned_sharded_preview() { - let directory = - std::env::temp_dir().join(format!("strata-preview-shards-{}", std::process::id())); + let directory = preview_test_path("shards", "dir"); let _ = fs::remove_dir_all(&directory); fs::create_dir(&directory).unwrap(); - let mut dense = Vec::new(); - for index in 0..32 { - dense.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()); - } + let (mut manifest, dense) = manifest_pinned_fixture(&directory); + let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); + let eager = directory.join("sharded.kar"); + assert_eager_sharded_preview(&manifest, &directory, &eager, &identity).await; + let streamed = directory.join("streamed.kar"); + assert_streamed_sharded_preview(&manifest, &directory, &streamed, &identity, &dense); + assert_sharded_hash_fail_closed(&mut manifest, &directory, &eager, &streamed, &identity) + .await; + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn streamed_prepare_parent_symlink_retarget_keeps_archive_and_provenance_together() { + let directory = preview_test_path("stream-symlink-output", "dir"); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let (manifest, _) = manifest_pinned_fixture(&directory); + assert_streamed_prepare_stays_in_canonical_parent(&directory, &manifest); + fs::remove_dir_all(directory).unwrap(); + } + + fn assert_streamed_prepare_stays_in_canonical_parent(directory: &Path, manifest: &Manifest) { + let original = directory.join("original-output"); + let replacement = directory.join("replacement-output"); + fs::create_dir(&original).unwrap(); + fs::create_dir(&replacement).unwrap(); + let link = directory.join("output-parent"); + std::os::unix::fs::symlink(&original, &link).unwrap(); + let destination = link.join("streamed.kar"); + retarget_preview_parent_after_staging(link, replacement.clone()); + let result = prepare_sharded_streamed(manifest, directory, &destination, 2).unwrap(); + assert_streamed_outputs_are_canonical(&result, &original, &replacement); + } + + fn assert_streamed_outputs_are_canonical( + result: &PreviewSummary, + original: &Path, + replacement: &Path, + ) { + let original = fs::canonicalize(original).unwrap(); + let archive = original.join("streamed.kar"); + let provenance = original.join("streamed.kar.provenance.json"); + assert!(archive.is_file() && provenance.is_file()); + assert!(!original.join("streamed.kar.pending.json").exists()); + assert_eq!(fs::read_dir(replacement).unwrap().count(), 0); + assert_eq!( + result.provenance_path.as_deref(), + Some(provenance.as_path()) + ); + kar::verify(&archive).unwrap(); + } + + fn manifest_pinned_fixture(directory: &Path) -> (Manifest, Vec) { + let dense = (0..32) + .flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()) + .collect::>(); let f32 = one_shard("dense", 0, 32, &dense); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in block[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - block[74] = 0x55; - let iq3 = one_shard_with_arch("expert", 21, 256, &block, false); + let iq3 = one_shard_with_arch("expert", 21, 256, &iq3_preview_block(), false); fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); - let mut manifest = Manifest { + (shard_manifest(&f32, &iq3), dense) + } + + fn shard_manifest(f32: &[u8], iq3: &[u8]) -> Manifest { + let files = [("z-iq3.gguf", iq3), ("a-f32.gguf", f32)] + .into_iter() + .map(|(name, bytes)| ModelFile { + name: name.into(), + url: format!("https://example.invalid/{}", name), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(bytes)), + }) + .collect(); + Manifest { schema_version: 1, - files: vec![ - ModelFile { - name: "z-iq3.gguf".into(), - url: "https://example.invalid/z".into(), - size: iq3.len() as u64, - sha256: hex::encode(Sha256::digest(&iq3)), - }, - ModelFile { - name: "a-f32.gguf".into(), - url: "https://example.invalid/a".into(), - size: f32.len() as u64, - sha256: hex::encode(Sha256::digest(&f32)), - }, - ], - }; - let output = directory.join("sharded.kar"); - let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); - let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap(); + files, + } + } + + async fn assert_eager_sharded_preview( + manifest: &Manifest, + directory: &Path, + output: &Path, + identity: &derived_mixed::ShardedIdentity, + ) { + let result = prepare_sharded(manifest, directory, output, 2).unwrap(); assert_eq!(result.archive.tensor_count, 2); assert_eq!(result.archive.source_digest, identity.derived_sha256); assert_eq!(result.archive.source_bytes, identity.derived_bytes); assert_eq!( - verify_sharded(&manifest, &directory, &output).unwrap(), + verify_sharded(manifest, directory, output).unwrap(), result.archive ); assert!(matches!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) + crate::model_pipeline::ensure_sharded_preview(manifest, directory, output, 2) .await .unwrap(), crate::model_pipeline::PreviewOutcome::Reused(_) )); assert!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 3) + crate::model_pipeline::ensure_sharded_preview(manifest, directory, output, 3) .await .is_err() ); - let record: serde_json::Value = - serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eager_sharded_provenance(&result); + } + + fn assert_eager_sharded_provenance(result: &PreviewSummary) { + let record = read_json(result.provenance_path.as_ref().unwrap()); assert_eq!( record["schema"], "strata-next/sharded-preview-provenance-v1" ); assert_eq!(record["shards"][0]["name"], "a-f32.gguf"); assert_eq!(record["tensors"][1]["derived_offset"], 128); - let streamed_output = directory.join("streamed.kar"); - let streamed = - prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(); - assert_eq!(streamed.archive.source_digest, identity.derived_sha256); - assert_eq!(streamed.archive.tensor_count, 2); - let decoded = kar::decode_preview_tensor(&streamed_output, "dense", 2).unwrap(); + } + + fn assert_streamed_sharded_preview( + manifest: &Manifest, + directory: &Path, + output: &Path, + identity: &derived_mixed::ShardedIdentity, + dense: &[u8], + ) { + let result = prepare_sharded_streamed(manifest, directory, output, 2).unwrap(); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.tensor_count, 2); + assert_streamed_tensor_quality(manifest, directory, output, &result.archive, dense); + assert_streamed_provenance(&result); + } + + fn assert_streamed_tensor_quality( + manifest: &Manifest, + directory: &Path, + output: &Path, + summary: &kar::Summary, + dense: &[u8], + ) { + assert_decoded_dense_payload(output, dense); + assert_streamed_quality_matches_summary(manifest, directory, output, summary); + assert_alternate_streamed_verification_rejected(manifest, directory, output); + } + + fn assert_decoded_dense_payload(output: &Path, dense: &[u8]) { + let decoded = kar::decode_preview_tensor(output, "dense", 2).unwrap(); let reference = dense .as_chunks::<4>() .0 @@ -2413,96 +4670,136 @@ mod tests { .zip(&reference) .all(|(actual, expected)| (actual - expected).abs() < 0.1) ); - assert_eq!( - verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(), - streamed.archive - ); - let sampled = - crate::kar_quality::analyze(&manifest, &directory, &streamed_output, 2).unwrap(); - assert_eq!( - sampled.records.len(), - streamed.archive.tensor_count as usize - ); + } + + fn assert_streamed_quality_matches_summary( + manifest: &Manifest, + directory: &Path, + output: &Path, + summary: &kar::Summary, + ) { + let verified = verify_sharded_streamed(manifest, directory, output, 2).unwrap(); + assert_eq!(verified.source_digest, summary.source_digest); + assert_eq!(verified.source_bytes, summary.source_bytes); + assert_eq!(verified.tensor_count, summary.tensor_count); + let sampled = crate::kar_quality::analyze(manifest, directory, output, 2).unwrap(); + assert_eq!(sampled.records.len(), summary.tensor_count as usize); assert!( sampled .records .iter() - .all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() }) + .all(|record| record.sampled_elements > 0 && record.relative_l2.is_finite()) ); - let reused = crate::kar_quality::analyze_previously_verified( - &manifest, - &directory, - &streamed_output, - 2, - ) - .unwrap(); + let reused = + crate::kar_quality::analyze_previously_verified(manifest, directory, output, 2) + .unwrap(); assert!( reused .records .iter() .zip(&sampled.records) - .all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 }) + .all(|(a, b)| a.name == b.name && a.relative_l2 == b.relative_l2) ); - assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err()); - assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err()); - let streamed_record: serde_json::Value = - serde_json::from_slice(&fs::read(streamed.provenance_path.unwrap()).unwrap()).unwrap(); - assert_eq!( - streamed_record["schema"], - "strata-next/sharded-stream-provenance-v4" - ); - assert_eq!( - streamed_record["partitioned_tensors"], - serde_json::json!([]) - ); - assert_eq!(streamed_record["levels"], 2); - assert!(prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); + } + + fn assert_alternate_streamed_verification_rejected( + manifest: &Manifest, + directory: &Path, + output: &Path, + ) { + assert!(verify_sharded_streamed(manifest, directory, output, 3).is_err()); + assert!(verify_sharded(manifest, directory, output).is_err()); + } + + fn assert_streamed_provenance(result: &PreviewSummary) { + let record = read_json(result.provenance_path.as_ref().unwrap()); + assert_eq!(record["schema"], "strata-next/sharded-stream-provenance-v4"); + assert_eq!(record["partitioned_tensors"], serde_json::json!([])); + assert_eq!(record["levels"], 2); + } + + async fn assert_sharded_hash_fail_closed( + manifest: &mut Manifest, + directory: &Path, + eager: &Path, + streamed: &Path, + identity: &derived_mixed::ShardedIdentity, + ) { + let original = manifest.files[0].sha256.clone(); manifest.files[0].sha256 = "00".repeat(32); - assert!(verify_sharded(&manifest, &directory, &output).is_err()); - assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); - manifest.files[0].sha256 = hex::encode(Sha256::digest(&iq3)); - let mut corrupted = fs::read(&output).unwrap(); - let last = corrupted.len() - 1; - corrupted[last] ^= 1; - fs::write(&output, corrupted).unwrap(); + assert!(verify_sharded(manifest, directory, eager).is_err()); + assert!(verify_sharded_streamed(manifest, directory, streamed, 2).is_err()); + manifest.files[0].sha256 = original; + assert_eq!( + derived_mixed::fingerprint_shards(manifest, directory) + .unwrap() + .derived_sha256, + identity.derived_sha256 + ); + corrupt_archive_and_reject_reuse(eager, manifest, directory).await; + } + + async fn corrupt_archive_and_reject_reuse( + archive: &Path, + manifest: &Manifest, + directory: &Path, + ) { + let mut bytes = fs::read(archive).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 1; + fs::write(archive, bytes).unwrap(); assert!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) + crate::model_pipeline::ensure_sharded_preview(manifest, directory, archive, 2) .await .is_err() ); - fs::remove_dir_all(directory).unwrap(); } #[test] fn streamed_preparation_keeps_unsplittable_tensors_exact() { - let directory = - std::env::temp_dir().join(format!("strata-stream-raw-{}", std::process::id())); + let directory = preview_test_path("stream-raw", "dir"); let _ = fs::remove_dir_all(&directory); fs::create_dir(&directory).unwrap(); - let mut files = Vec::new(); - for (name, kind, elements, payload) in [ - ("a", 21, 256, vec![0u8; iq3_s::BLOCK_BYTES]), - ("b", 20, 32, vec![0u8; 18]), - ] { - let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a"); - let filename = format!("{name}.gguf"); - fs::write(directory.join(&filename), &bytes).unwrap(); - files.push(ModelFile { - name: filename, - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - }); - } - let manifest = Manifest { - schema_version: 1, - files, - }; + let manifest = unsplittable_tensor_manifest(&directory); let archive = directory.join("raw.kar"); let result = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); assert_eq!(result.archive.max_planes, 0); assert_eq!(result.maximum_relative_l2, 0.0); - let sampled = crate::kar_quality::analyze(&manifest, &directory, &archive, 2).unwrap(); + assert_exact_raw_quality(&manifest, &directory, &archive); + assert_eq!( + verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), + result.archive + ); + fs::remove_dir_all(directory).unwrap(); + } + + fn unsplittable_tensor_manifest(directory: &Path) -> Manifest { + let entries = [ + ("a", 21u32, 256u64, vec![0u8; iq3_s::BLOCK_BYTES]), + ("b", 20, 32, vec![0u8; 18]), + ]; + let files = entries + .into_iter() + .map(|(name, kind, elements, payload)| { + let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a"); + let filename = format!("{name}.gguf"); + fs::write(directory.join(&filename), &bytes).unwrap(); + ModelFile { + name: filename, + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + Manifest { + schema_version: 1, + files, + } + } + + fn assert_exact_raw_quality(manifest: &Manifest, directory: &Path, archive: &Path) { + let sampled = crate::kar_quality::analyze(manifest, directory, archive, 2).unwrap(); assert_eq!(sampled.records.len(), 2); assert!( sampled @@ -2511,7 +4808,7 @@ mod tests { .all(|record| record.relative_l2 == 0.0) ); let reused = - crate::kar_quality::analyze_previously_verified(&manifest, &directory, &archive, 2) + crate::kar_quality::analyze_previously_verified(manifest, directory, archive, 2) .unwrap(); assert!( reused @@ -2519,31 +4816,115 @@ mod tests { .iter() .all(|record| record.relative_l2 == 0.0) ); - assert_eq!( - verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), - result.archive - ); - fs::remove_dir_all(directory).unwrap(); } #[test] fn selected_overlay_reconstructs_source_and_cleans_staging() { - let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id())); + let fixture = overlay_fixture(); + crate::kar_writer::fail_next_archive_temp_cleanup(); + let result = fixture.prepare().unwrap(); + assert_eq!(result.record_count, 1); + assert!(result.maximum_relative_l2.is_finite()); + assert_eq!(kar::verify(&fixture.overlay).unwrap().max_planes, 3); + check_overlay_reconstruction(&fixture, &result); + check_overlay_selection(&fixture, &result); + assert_overlay_staging_removed(&fixture); + reject_corrupt_overlay_provenance(&fixture, &result); + } + + #[test] + fn overlay_publication_recovers_each_process_death_boundary() { + for stage in 1..=4 { + let fixture = overlay_fixture(); + crate::kar_overlay::fail_overlay_publication_at(stage); + assert!(fixture.prepare().is_err()); + assert_overlay_interrupted(&fixture, stage); + let archive_before_retry = fixture + .overlay + .exists() + .then(|| hash_file(&fixture.overlay).unwrap()); + fixture.prepare().unwrap(); + if let Some(before) = archive_before_retry { + assert_eq!(hash_file(&fixture.overlay).unwrap(), before); + } + assert_overlay_recovered(&fixture); + } + } + + #[test] + fn overlay_parent_symlink_retarget_keeps_publication_canonical() { + let fixture = overlay_fixture(); + let original = fixture.directory.join("original"); + let replacement = fixture.directory.join("replacement"); + fs::create_dir(&original).unwrap(); + fs::create_dir(&replacement).unwrap(); + let link = fixture.directory.join("output-link"); + std::os::unix::fs::symlink(&original, &link).unwrap(); + let archive = link.join("overlay.kar"); + crate::kar_overlay::retarget_overlay_parent_at_publish(link.clone(), replacement.clone()); + let result = fixture.prepare_to(&archive).unwrap(); + assert_canonical_overlay_outputs(&result, &link, &original, &replacement, &fixture.base); + } + + fn assert_canonical_overlay_outputs( + result: &crate::kar_overlay::Summary, + link: &Path, + original: &Path, + replacement: &Path, + base: &Path, + ) { + let original = fs::canonicalize(original).unwrap(); + assert_eq!( + fs::canonicalize(link).unwrap(), + fs::canonicalize(replacement).unwrap() + ); + let archive = original.join("overlay.kar"); + let sidecar = original.join("overlay.kar.provenance.json"); + assert!(archive.is_file() && sidecar.is_file()); + assert!(!original.join("overlay.kar.pending.json").exists()); + assert_eq!(fs::read_dir(replacement).unwrap().count(), 0); + assert_eq!(result.provenance_path, sidecar); + crate::kar_overlay::resolve_verified(base, &archive).unwrap(); + } + + #[test] + fn overlay_retry_never_replaces_unrelated_archive_or_sidecar() { + preserve_unrelated_overlay_outputs(); + } + + #[test] + fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { + let directory = preview_test_path("stream-split", "dir"); let _ = fs::remove_dir_all(&directory); fs::create_dir(&directory).unwrap(); - let values = (0..256) - .map(|index| (index as f32 - 127.5) / 128.0) - .collect::>(); - let dense = values - .iter() - .flat_map(|value| value.to_le_bytes()) + let (manifest, dense) = split_tensor_fixture(&directory); + let archive = directory.join("split.kar"); + let result = + prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); + assert_split_archive_identity(&result, &manifest, &directory, &archive); + assert_split_provenance_and_tensor_bytes(&result, &archive, &dense); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn partitioned_overlay_resolves_against_complete_virtual_source() { + let directory = preview_test_path("partitioned-overlay", "dir"); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let manifest = partitionable_overlay_manifest(&directory); + assert_partitioned_overlay_resolves(&directory, &manifest); + fs::remove_dir_all(directory).unwrap(); + } + + fn partitionable_overlay_manifest(directory: &Path) -> Manifest { + let dense = (0..512) + .map(|index| (index as f32 - 255.5) / 256.0) + .flat_map(f32::to_le_bytes) .collect::>(); + let iq3 = one_shard_with_arch("expert", 21, 256, &iq3_preview_block(), false); let files = [ - ("a.gguf", one_shard("dense", 0, 256, &dense)), - ( - "b.gguf", - one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false), - ), + ("a-dense.gguf", one_shard("dense", 0, 512, &dense)), + ("z-iq3.gguf", iq3), ] .into_iter() .map(|(name, bytes)| { @@ -2556,81 +4937,284 @@ mod tests { } }) .collect(); - let manifest = Manifest { + Manifest { schema_version: 1, files, - }; - let base = directory.join("base.kar"); - let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); - let policy = directory.join("candidates.json"); - fs::write( - &policy, - serde_json::to_vec(&serde_json::json!({ - "schema": "strata-next/proposed-kar-precision-candidates-v1", - "source_archive_sha256": hex::encode(prepared.archive_digest), - "proposed_levels": 3, - "records": [{"name": "dense", "elements": 256}], - })) - .unwrap(), - ) - .unwrap(); - let overlay = directory.join("overlay.kar"); - let result = - crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); - assert_eq!(result.record_count, 1); - assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); - assert!(result.maximum_relative_l2.is_finite()); - let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap(); - let error_sum = decoded - .iter() - .zip(&values) - .map(|(actual, expected)| f64::from(actual - expected).powi(2)) - .sum::(); - let reference_sum = values - .iter() - .map(|value| f64::from(*value).powi(2)) - .sum::(); - assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7); - assert!(result.provenance_path.exists()); - let comparison = - crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); - assert_eq!(comparison.records.len(), 1); - assert_eq!(comparison.records[0].name, "dense"); - let selection = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap(); - assert_eq!(selection.replacement_count, 1); - assert_eq!(selection.records.len(), 2); - assert_eq!(selection.records[0].name, "dense"); - assert_eq!(selection.records[0].archive, "overlay"); - assert_eq!(selection.records[1].archive, "base"); - let mut provenance: serde_json::Value = - serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap(); - provenance["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); - fs::write( - &result.provenance_path, - serde_json::to_vec(&provenance).unwrap(), - ) - .unwrap(); - assert!(crate::kar_overlay::resolve_verified(&base, &overlay).is_err()); - assert!( - (comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7 - ); - assert!( - !directory - .join(format!( - "overlay.kar.overlay-sections-{}", - std::process::id() - )) - .exists() - ); - fs::remove_dir_all(directory).unwrap(); + } } - #[test] - fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { - let directory = - std::env::temp_dir().join(format!("strata-stream-split-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); + fn assert_partitioned_overlay_resolves(directory: &Path, manifest: &Manifest) { + let base = directory.join("partitioned-base.kar"); + prepare_sharded_streamed_with_limit(manifest, directory, &base, 2, 256).unwrap(); + let base_record = read_json(&provenance_path(&base).unwrap()); + let parts = base_record["partitioned_tensors"][0]["parts"] + .as_array() + .unwrap() + .clone(); + let candidates = directory.join("partitioned-candidates.json"); + write_partition_candidate_policy(&candidates, &base_record, &parts); + let overlay = directory.join("partitioned-overlay.kar"); + let result = + crate::kar_overlay::prepare(manifest, directory, &base, &candidates, &overlay).unwrap(); + let resolved = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap(); + assert_eq!(resolved.replacement_count, 2); + assert!( + resolved + .records + .iter() + .any(|record| record.archive == "overlay") + ); + assert_missing_overlay_sidecars_rejected(&base, &overlay, &result.provenance_path); + assert_partitioned_provenance_rejections(&base, &overlay, &result.provenance_path); + } + + fn assert_missing_overlay_sidecars_rejected(base: &Path, overlay: &Path, sidecar: &Path) { + let base_sidecar = provenance_path(base).unwrap(); + let base_bytes = fs::read(&base_sidecar).unwrap(); + fs::remove_file(&base_sidecar).unwrap(); + assert!(crate::kar_overlay::resolve_verified(base, overlay).is_err()); + fs::write(&base_sidecar, base_bytes).unwrap(); + let overlay_bytes = fs::read(sidecar).unwrap(); + fs::remove_file(sidecar).unwrap(); + assert!(crate::kar_overlay::resolve_verified(base, overlay).is_err()); + fs::write(sidecar, overlay_bytes).unwrap(); + } + + fn write_partition_candidate_policy( + path: &Path, + base: &serde_json::Value, + parts: &[serde_json::Value], + ) { + let policy = serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": base["archive_sha256"], + "proposed_levels": 3, + "records": parts.iter().map(|part| serde_json::json!({ + "name": part["name"], "elements": part["dimensions"][0] + })).collect::>() + }); + fs::write(path, serde_json::to_vec(&policy).unwrap()).unwrap(); + } + + fn assert_partitioned_provenance_rejections( + base: &Path, + overlay: &Path, + overlay_sidecar: &Path, + ) { + let base_sidecar = provenance_path(base).unwrap(); + let base_valid = read_json(&base_sidecar); + let overlay_valid = read_json(overlay_sidecar); + assert_resolver_rejects_json_mutations( + &base_sidecar, + base, + overlay, + &base_valid, + &[ + bad_base_schema, + bad_base_source_digest_format, + bad_base_digest, + bad_base_source_digest, + bad_base_source_bytes, + duplicate_base_record, + duplicate_parent, + missing_parent_dimensions, + too_few_partition_parts, + bad_part_shape, + bad_part_offset, + bad_part_digest_format, + duplicate_part, + bad_parent_coverage, + base_part_collision, + missing_base_record, + bad_base_record_digest, + bad_base_record_digest_format, + partition_dimensions_mismatch, + ], + ); + assert_resolver_rejects_json_mutations( + overlay_sidecar, + base, + overlay, + &overlay_valid, + &[ + bad_overlay_schema, + bad_overlay_low_level, + bad_overlay_levels, + bad_overlay_base_digest, + bad_overlay_archive_digest, + empty_overlay_records, + bad_overlay_record_name, + duplicate_overlay_record, + bad_overlay_record, + bad_overlay_offset, + bad_overlay_section_bytes, + negative_overlay_error, + ], + ); + write_json_value(&base_sidecar, &base_valid); + write_json_value(overlay_sidecar, &overlay_valid); + } + + fn assert_resolver_rejects_json_mutations( + sidecar: &Path, + base: &Path, + overlay: &Path, + original: &serde_json::Value, + mutations: &[fn(&mut serde_json::Value)], + ) { + for mutate in mutations { + let mut corrupt = original.clone(); + mutate(&mut corrupt); + write_json_value(sidecar, &corrupt); + assert!(crate::kar_overlay::resolve_verified(base, overlay).is_err()); + } + write_json_value(sidecar, original); + } + + fn write_json_value(path: &Path, value: &serde_json::Value) { + fs::write(path, serde_json::to_vec(value).unwrap()).unwrap(); + } + + fn bad_base_schema(value: &mut serde_json::Value) { + value["schema"] = serde_json::json!("unsupported"); + } + + fn bad_base_digest(value: &mut serde_json::Value) { + value["archive_sha256"] = serde_json::json!("00".repeat(32)); + } + + fn bad_base_source_digest(value: &mut serde_json::Value) { + value["derived_f32_sha256"] = serde_json::json!("00".repeat(32)); + } + + fn bad_base_source_bytes(value: &mut serde_json::Value) { + value["derived_f32_bytes"] = serde_json::json!(1); + } + + fn bad_base_source_digest_format(value: &mut serde_json::Value) { + value["derived_f32_sha256"] = serde_json::json!("not-a-digest"); + } + + fn duplicate_base_record(value: &mut serde_json::Value) { + let record = value["tensors"][0].clone(); + value["tensors"].as_array_mut().unwrap().push(record); + } + + fn duplicate_parent(value: &mut serde_json::Value) { + let parent = value["partitioned_tensors"][0].clone(); + value["partitioned_tensors"] + .as_array_mut() + .unwrap() + .push(parent); + } + + fn missing_parent_dimensions(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parent_dimensions"] = serde_json::json!([]); + } + + fn too_few_partition_parts(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"] + .as_array_mut() + .unwrap() + .pop(); + } + + fn bad_part_shape(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([128]); + } + + fn bad_part_offset(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][1]["derived_offset"] = serde_json::json!(1); + } + + fn bad_part_digest_format(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][0]["f32_sha256"] = serde_json::json!("bad"); + } + + fn duplicate_part(value: &mut serde_json::Value) { + let first = value["partitioned_tensors"][0]["parts"][0]["name"].clone(); + value["partitioned_tensors"][0]["parts"][1]["name"] = first; + } + + fn bad_parent_coverage(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parent_dimensions"] = serde_json::json!([511]); + } + + fn base_part_collision(value: &mut serde_json::Value) { + let part = value["partitioned_tensors"][0]["parts"][0]["name"].clone(); + value["tensors"][1]["name"] = part; + } + + fn missing_base_record(value: &mut serde_json::Value) { + value["tensors"].as_array_mut().unwrap().pop(); + } + + fn bad_base_record_digest(value: &mut serde_json::Value) { + value["tensors"][1]["f32_sha256"] = serde_json::json!("00".repeat(32)); + } + + fn bad_base_record_digest_format(value: &mut serde_json::Value) { + value["tensors"][1]["f32_sha256"] = serde_json::json!("bad"); + } + + fn partition_dimensions_mismatch(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([128]); + value["partitioned_tensors"][0]["parts"][0]["derived_bytes"] = serde_json::json!(512); + value["partitioned_tensors"][0]["parts"][1]["dimensions"] = serde_json::json!([384]); + value["partitioned_tensors"][0]["parts"][1]["derived_offset"] = serde_json::json!(512); + value["partitioned_tensors"][0]["parts"][1]["derived_bytes"] = serde_json::json!(1536); + } + + fn bad_overlay_schema(value: &mut serde_json::Value) { + value["schema"] = serde_json::json!("unsupported"); + } + + fn bad_overlay_levels(value: &mut serde_json::Value) { + value["levels"] = serde_json::json!(9); + } + + fn bad_overlay_low_level(value: &mut serde_json::Value) { + value["levels"] = serde_json::json!(1); + } + + fn bad_overlay_base_digest(value: &mut serde_json::Value) { + value["base_archive_sha256"] = serde_json::json!("00".repeat(32)); + } + + fn bad_overlay_archive_digest(value: &mut serde_json::Value) { + value["overlay_archive_sha256"] = serde_json::json!("00".repeat(32)); + } + + fn empty_overlay_records(value: &mut serde_json::Value) { + value["records"] = serde_json::json!([]); + } + + fn bad_overlay_record_name(value: &mut serde_json::Value) { + value["records"][0]["name"] = serde_json::json!("missing tensor"); + } + + fn duplicate_overlay_record(value: &mut serde_json::Value) { + let first = value["records"][0].clone(); + value["records"][1] = first; + } + + fn bad_overlay_record(value: &mut serde_json::Value) { + value["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); + } + + fn bad_overlay_offset(value: &mut serde_json::Value) { + value["records"][0]["derived_offset"] = serde_json::json!(1); + } + + fn bad_overlay_section_bytes(value: &mut serde_json::Value) { + value["records"][0]["section_bytes"] = serde_json::json!(1); + } + + fn negative_overlay_error(value: &mut serde_json::Value) { + value["records"][0]["relative_l2"] = serde_json::json!(-1.0); + } + + fn split_tensor_fixture(directory: &Path) -> (Manifest, Vec) { let dense = (0..512) .flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()) .collect::>(); @@ -2650,13 +5234,21 @@ mod tests { } }) .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let archive = directory.join("split.kar"); - let result = - prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); + ( + Manifest { + schema_version: 1, + files, + }, + dense, + ) + } + + fn assert_split_archive_identity( + result: &PreviewSummary, + manifest: &Manifest, + directory: &Path, + archive: &Path, + ) { assert_eq!(result.archive.tensor_count, 3); assert_eq!(result.tensor_distortions.len(), 3); assert_eq!( @@ -2673,120 +5265,172 @@ mod tests { .iter() .all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite()) ); - assert_eq!( - verify_sharded_inner(StreamVerifyRequest { - manifest: &manifest, - source_dir: &directory, - archive_path: &archive, - streamed_levels: Some(2), - max_part_elements: 256, - ple_part_elements: None, - }) - .unwrap(), - result.archive - ); - assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); - let provenance: serde_json::Value = - serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); - let parts = provenance["partitioned_tensors"][0]["parts"] + let verified = verify_sharded_inner(StreamVerifyRequest { + manifest, + source_dir: directory, + archive_path: archive, + streamed_levels: Some(2), + max_part_elements: 256, + ple_part_elements: None, + }) + .unwrap(); + assert_eq!(verified.tensor_count, result.archive.tensor_count); + assert!(verify_sharded_streamed(manifest, directory, archive, 2).is_err()); + } + + fn assert_split_provenance_and_tensor_bytes( + result: &PreviewSummary, + archive: &Path, + dense: &[u8], + ) { + let record = read_json(result.provenance_path.as_ref().unwrap()); + let parts = record["partitioned_tensors"][0]["parts"] .as_array() .unwrap(); assert_eq!(parts.len(), 2); assert_eq!(parts[0]["dimensions"], serde_json::json!([256])); assert_eq!(parts[1]["derived_offset"], 1024); for (number, part) in parts.iter().enumerate() { - let name = part["name"].as_str().unwrap(); - let decoded = kar::decode_preview_tensor(&archive, name, 2).unwrap(); - assert_eq!(decoded.len(), 256); - for (actual, original) in decoded.iter().zip( - dense[number * 1024..(number + 1) * 1024] - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ) { - assert!((actual - original).abs() < 0.1); + assert_split_part_roundtrips(archive, part, dense, number); + } + } + + fn assert_split_part_roundtrips( + archive: &Path, + part: &serde_json::Value, + dense: &[u8], + number: usize, + ) { + let decoded = + kar::decode_preview_tensor(archive, part["name"].as_str().unwrap(), 2).unwrap(); + let original = dense[number * 1024..(number + 1) * 1024] + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)); + assert_eq!(decoded.len(), 256); + assert!( + decoded + .iter() + .zip(original) + .all(|(actual, expected)| (actual - expected).abs() < 0.1) + ); + } + + struct RecoveryCheck<'a> { + manifest: &'a Manifest, + directory: &'a Path, + archive: &'a Path, + provenance: &'a Path, + pending: &'a Path, + expected: &'a kar::Summary, + } + + impl RecoveryCheck<'_> { + fn request(&self) -> StreamVerifyRequest<'_> { + StreamVerifyRequest { + manifest: self.manifest, + source_dir: self.directory, + archive_path: self.archive, + streamed_levels: Some(2), + max_part_elements: stream_parts::MAX_PART_ELEMENTS, + ple_part_elements: None, } } - fs::remove_dir_all(directory).unwrap(); } #[tokio::test] async fn streamed_publication_recovers_only_its_matching_archive_after_faults() { - let directory = std::env::temp_dir().join(format!( - "strata-stream-recovery-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); + let directory = preview_test_path("stream-recovery", "dir"); fs::create_dir(&directory).unwrap(); let manifest = two_f32_shard_manifest(&directory); let archive = directory.join("recover.kar"); let provenance = provenance_path(&archive).unwrap(); let pending = streamed_publish_intent_path(&archive).unwrap(); let prepared = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); - let expected_summary = prepared.archive; + let expected = prepared.archive; fs::remove_file(&provenance).unwrap(); let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); let parts = stream_parts::plan_shards(&identity, &directory).unwrap(); let intent = streamed_publish_intent(&identity, &parts, 2, None); write_provenance(&pending, &intent).unwrap(); - let verify_request = StreamVerifyRequest { + let check = RecoveryCheck { manifest: &manifest, - source_dir: &directory, - archive_path: &archive, - streamed_levels: Some(2), - max_part_elements: stream_parts::MAX_PART_ELEMENTS, - ple_part_elements: None, + directory: &directory, + archive: &archive, + provenance: &provenance, + pending: &pending, + expected: &expected, }; + assert_recovery_hash_and_sidecar_faults(&check); + assert_recovery_preserves_reserved_sidecar(&check); + assert_recovery_reuses_matching_archive(&check).await; + write_provenance(&pending, &intent).unwrap(); + assert_cleanup_failure_keeps_verified_intent(&check, &intent); + fs::remove_dir_all(directory).unwrap(); + } + fn assert_recovery_hash_and_sidecar_faults(check: &RecoveryCheck<'_>) { let hash_failure = StreamPublicationOps { hash_archive: fail_archive_hash, write_sidecar: write_provenance, remove_intent: remove_pending_intent, }; - assert!(recover_streamed_publication(&verify_request, &hash_failure).is_err()); - assert!(archive.is_file() && pending.is_file() && !provenance.exists()); - + assert!(recover_streamed_publication(&check.request(), &hash_failure).is_err()); + assert!(check.archive.is_file() && check.pending.is_file() && !check.provenance.exists()); let provenance_failure = StreamPublicationOps { hash_archive: hash_file, write_sidecar: fail_sidecar, remove_intent: remove_pending_intent, }; - assert!(recover_streamed_publication(&verify_request, &provenance_failure).is_err()); - assert!(pending.is_file() && !provenance.exists()); + assert!(recover_streamed_publication(&check.request(), &provenance_failure).is_err()); + assert!(check.pending.is_file() && !check.provenance.exists()); + } - fs::write(&provenance, b"unrelated reservation").unwrap(); - assert!(recover_streamed_publication(&verify_request, &FILE_PUBLICATION_OPS).is_err()); - assert_eq!(fs::read(&provenance).unwrap(), b"unrelated reservation"); - assert!(pending.is_file()); - fs::remove_file(&provenance).unwrap(); + fn assert_recovery_preserves_reserved_sidecar(check: &RecoveryCheck<'_>) { + fs::write(check.provenance, b"unrelated reservation").unwrap(); + assert!(recover_streamed_publication(&check.request(), &FILE_PUBLICATION_OPS).is_err()); + assert_eq!( + fs::read(check.provenance).unwrap(), + b"unrelated reservation" + ); + assert!(check.pending.is_file()); + fs::remove_file(check.provenance).unwrap(); + } - assert!(matches!( - crate::model_pipeline::ensure_sharded_streamed(&manifest, &directory, &archive, 2) - .await - .unwrap(), - crate::model_pipeline::PreviewOutcome::Reused(summary) if summary == expected_summary - )); - assert!(!pending.exists()); - fs::remove_file(&provenance).unwrap(); - write_provenance(&pending, &intent).unwrap(); + async fn assert_recovery_reuses_matching_archive(check: &RecoveryCheck<'_>) { + let outcome = crate::model_pipeline::ensure_sharded_streamed( + check.manifest, + check.directory, + check.archive, + 2, + ) + .await + .unwrap(); + assert!( + matches!(outcome, crate::model_pipeline::PreviewOutcome::Reused(summary) if summary == *check.expected) + ); + assert!(!check.pending.exists()); + fs::remove_file(check.provenance).unwrap(); + } + fn assert_cleanup_failure_keeps_verified_intent( + check: &RecoveryCheck<'_>, + intent: &serde_json::Value, + ) { let cleanup_failure = StreamPublicationOps { hash_archive: hash_file, write_sidecar: write_provenance, remove_intent: fail_intent_cleanup, }; - let recovered = recover_streamed_publication(&verify_request, &cleanup_failure).unwrap(); - assert_eq!(recovered.as_ref(), Some(&expected_summary)); - assert!(pending.is_file()); + let recovered = recover_streamed_publication(&check.request(), &cleanup_failure).unwrap(); + assert_eq!(recovered.as_ref(), Some(check.expected)); + assert!(check.pending.is_file()); assert_eq!( - verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), - expected_summary + verify_sharded_streamed(check.manifest, check.directory, check.archive, 2).unwrap(), + *check.expected ); - fs::remove_dir_all(directory).unwrap(); + assert_eq!(read_json(check.pending), *intent); } #[test] @@ -2810,31 +5454,42 @@ mod tests { fail_provenance_temp_cleanup, ) .unwrap(); - - let recorded: serde_json::Value = - serde_json::from_reader(File::open(&destination).unwrap()).unwrap(); - assert_eq!(recorded, expected); - let temporary = fs::read_dir(&directory) - .unwrap() - .map(|entry| entry.unwrap().path()) - .find(|path| path != &destination) - .expect("injected cleanup failure should leave the hard-link name"); + assert_published_provenance(&destination, &expected); + let temporary = leftover_provenance_link(&directory, &destination); fs::remove_file(temporary).unwrap(); fs::remove_file(destination).unwrap(); fs::remove_dir(directory).unwrap(); } + fn assert_published_provenance(destination: &Path, expected: &serde_json::Value) { + let recorded: serde_json::Value = + serde_json::from_reader(File::open(destination).unwrap()).unwrap(); + assert_eq!(&recorded, expected); + } + + fn leftover_provenance_link(directory: &Path, destination: &Path) -> PathBuf { + fs::read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| path != destination) + .expect("injected cleanup failure should leave the hard-link name") + } + #[test] fn ple_partition_policy_is_versioned_and_verified() { - let directory = std::env::temp_dir().join(format!( - "strata-ple-parts-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); + let directory = preview_test_path("ple-parts", "dir"); fs::create_dir(&directory).unwrap(); + let manifest = ple_partition_fixture(&directory); + let archive = directory.join("ple.kar"); + let prepared = + prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); + assert_ple_partition_archive(&prepared, &manifest, &directory, &archive); + assert_ple_candidate_overlay(&prepared, &manifest, &directory, &archive); + assert_ple_corrupt_provenance_rejected(&manifest, &directory, &archive); + fs::remove_dir_all(directory).unwrap(); + } + + fn ple_partition_fixture(directory: &Path) -> Manifest { let ple_values = (0..512) .flat_map(|index| ((index as f32 - 255.5) / 256.0).to_le_bytes()) .collect::>(); @@ -2844,7 +5499,7 @@ mod tests { .map(|index| (index as f32 - 127.5) / 128.0) .flat_map(f32::to_le_bytes) .collect::>(); - let files = [ + let entries = [ ("a-ple.gguf", ple_shard(&ple_values)), ( "m-dense.gguf", @@ -2854,67 +5509,85 @@ mod tests { "z-expert.gguf", one_shard_with_arch("expert", 21, 256, &block, false), ), - ] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { + ]; + Manifest { schema_version: 1, - files, - }; - let archive = directory.join("ple.kar"); - let prepared = - prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); + files: write_model_files(directory, entries), + } + } + + fn write_model_files( + directory: &Path, + entries: impl IntoIterator)>, + ) -> Vec { + entries + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect() + } + + fn assert_ple_partition_archive( + prepared: &PreviewSummary, + manifest: &Manifest, + directory: &Path, + archive: &Path, + ) { assert_eq!(prepared.archive.tensor_count, 6); + let verified = verify_sharded_streamed_ple(manifest, directory, archive, 2, 128).unwrap(); + assert_eq!(verified.tensor_count, prepared.archive.tensor_count); + assert!(verify_sharded_streamed(manifest, directory, archive, 2).is_err()); + assert!(verify_sharded_streamed_ple(manifest, directory, archive, 2, 256).is_err()); + assert_ple_provenance(prepared); + } + + fn assert_ple_provenance(prepared: &PreviewSummary) { + let record = read_json(prepared.provenance_path.as_ref().unwrap()); + assert_eq!(record["schema"], "strata-next/sharded-stream-provenance-v5"); + assert_eq!(record["ple_part_elements"], 128); assert_eq!( - verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(), - prepared.archive - ); - assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); - assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err()); - let provenance: serde_json::Value = - serde_json::from_slice(&fs::read(prepared.provenance_path.unwrap()).unwrap()).unwrap(); - assert_eq!( - provenance["schema"], - "strata-next/sharded-stream-provenance-v5" - ); - assert_eq!(provenance["ple_part_elements"], 128); - assert_eq!( - provenance["partitioned_tensors"][0]["parts"] + record["partitioned_tensors"][0]["parts"] .as_array() .unwrap() .len(), 4 ); - let policy = directory.join("candidates.json"); - fs::write( - &policy, - serde_json::to_vec(&serde_json::json!({ - "schema": "strata-next/proposed-kar-precision-candidates-v1", - "source_archive_sha256": hex::encode(prepared.archive_digest), - "proposed_levels": 3, - "records": [ - {"name": "dense", "elements": 256}, - {"name": "per_layer_token_embd.weight#strata-part-001-of-004", "elements": 128} - ], - })) - .unwrap(), - ) - .unwrap(); + } + + fn assert_ple_candidate_overlay( + prepared: &PreviewSummary, + manifest: &Manifest, + directory: &Path, + archive: &Path, + ) { + let policy = ple_candidate_policy(prepared.archive_digest); + let policy_path = directory.join("candidates.json"); + fs::write(&policy_path, serde_json::to_vec(&policy).unwrap()).unwrap(); let overlay = directory.join("overlay.kar"); - crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap(); - let selection = crate::kar_overlay::resolve_verified(&archive, &overlay).unwrap(); + crate::kar_overlay::prepare(manifest, directory, archive, &policy_path, &overlay).unwrap(); + let selection = crate::kar_overlay::resolve_verified(archive, &overlay).unwrap(); assert_eq!(selection.replacement_count, 2); assert_eq!(selection.records.len(), 6); - let memory = crate::kar_memory::plan_selected(&archive, &overlay, 2, 3, 1 << 20).unwrap(); + assert_ple_memory_plan(archive, &overlay); + assert_ple_comparison(manifest, directory, archive, &overlay); + } + + fn ple_candidate_policy(digest: [u8; 32]) -> serde_json::Value { + serde_json::json!({"schema":"strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256":hex::encode(digest), "proposed_levels":3, + "records":[{"name":"dense","elements":256}, + {"name":"per_layer_token_embd.weight#strata-part-001-of-004","elements":128}]}) + } + + fn assert_ple_memory_plan(archive: &Path, overlay: &Path) { + let memory = crate::kar_memory::plan_selected(archive, overlay, 2, 3, 1 << 20).unwrap(); assert_eq!(memory.record_count, 6); assert_eq!(memory.replacement_count, 2); assert!(memory.selected_overlay_compressed_bytes > 0); @@ -2930,16 +5603,30 @@ mod tests { memory.selected_compressed_bytes, memory.selected_base_compressed_bytes + memory.selected_overlay_compressed_bytes ); + } + + fn assert_ple_comparison( + manifest: &Manifest, + directory: &Path, + archive: &Path, + overlay: &Path, + ) { let comparison = - crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap(); + crate::kar_overlay::compare(manifest, directory, archive, overlay).unwrap(); assert_eq!(comparison.records.len(), 2); assert_eq!(comparison.records[1].elements, 128); - let sidecar = archive.with_file_name("ple.kar.provenance.json"); - let mut corrupted: serde_json::Value = - serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); + } + + fn assert_ple_corrupt_provenance_rejected( + manifest: &Manifest, + directory: &Path, + archive: &Path, + ) { + let overlay = directory.join("overlay.kar"); + let sidecar = provenance_path(archive).unwrap(); + let mut corrupted = read_json(&sidecar); corrupted["partitioned_tensors"][0]["parts"][0]["source_byte_offset"] = 4.into(); fs::write(&sidecar, serde_json::to_vec(&corrupted).unwrap()).unwrap(); - assert!(crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).is_err()); - fs::remove_dir_all(directory).unwrap(); + assert!(crate::kar_overlay::compare(manifest, directory, archive, &overlay).is_err()); } } diff --git a/control-plane/src/stream_parts.rs b/control-plane/src/stream_parts.rs index 943f4a52..61cf12ca 100644 --- a/control-plane/src/stream_parts.rs +++ b/control-plane/src/stream_parts.rs @@ -226,6 +226,11 @@ struct ParentHashes { f32: Sha256, } +struct LayoutHashAccumulator<'a> { + part: ParentHashes, + parent: &'a mut ParentHashes, +} + struct PartBuildContext<'a> { index: &'a gguf::TensorIndex, tensor: &'a gguf::TensorInfo, @@ -264,12 +269,20 @@ impl<'a> ShardPlanner<'a> { } fn plan_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> { + self.plan_shard_with_open(shard, |path| File::open(path)) + } + + fn plan_shard_with_open( + &mut self, + shard: &derived_mixed::ShardIdentity, + open: fn(&Path) -> std::io::Result, + ) -> Result<(), String> { let path = self.source_dir.join(&shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; if index.tensors.len() != shard.tensor_count { return Err("GGUF shard changed during KAR part planning".into()); } - let mut source = File::open(path).map_err(|error| error.to_string())?; + let mut source = open(&path).map_err(|error| error.to_string())?; for tensor in &index.tensors { self.plan_tensor(&index, &mut source, tensor)?; } @@ -361,30 +374,8 @@ impl<'a> ShardPlanner<'a> { hashes: &mut ParentHashes, ) -> Result { let tensor = context.tensor; - let (source_sha256, f32_sha256) = if context.split { - hash_layout( - source, - context.index.summary.data_start, - tensor, - layout, - hashes, - )? - } else { - (context.original.source_sha256, context.original.f32_sha256) - }; - Ok(PartIdentity { - name: layout.name.clone(), - parent_name: tensor.name.clone(), - parent_dimensions: tensor.dimensions.clone(), - dimensions: layout.dimensions.clone(), - source_kind: tensor.kind, - source_byte_offset: layout.source_byte_offset, - source_bytes: layout.source_bytes, - source_sha256, - derived_offset: layout.derived_offset, - derived_bytes: layout.derived_bytes, - f32_sha256, - }) + let hashes = part_hashes(source, layout, context, hashes)?; + Ok(part_identity(tensor, layout, hashes)) } fn verify_parent_hashes( @@ -418,6 +409,45 @@ impl<'a> ShardPlanner<'a> { } } +fn part_hashes( + source: &mut File, + layout: &Layout, + context: &PartBuildContext<'_>, + parent: &mut ParentHashes, +) -> Result<([u8; 32], [u8; 32]), String> { + if context.split { + hash_layout( + source, + context.index.summary.data_start, + context.tensor, + layout, + parent, + ) + } else { + Ok((context.original.source_sha256, context.original.f32_sha256)) + } +} + +fn part_identity( + tensor: &gguf::TensorInfo, + layout: &Layout, + hashes: ([u8; 32], [u8; 32]), +) -> PartIdentity { + PartIdentity { + name: layout.name.clone(), + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: layout.dimensions.clone(), + source_kind: tensor.kind, + source_byte_offset: layout.source_byte_offset, + source_bytes: layout.source_bytes, + source_sha256: hashes.0, + derived_offset: layout.derived_offset, + derived_bytes: layout.derived_bytes, + f32_sha256: hashes.1, + } +} + fn hash_layout( source: &mut File, data_start: u64, @@ -425,39 +455,439 @@ fn hash_layout( layout: &Layout, parent: &mut ParentHashes, ) -> Result<([u8; 32], [u8; 32]), String> { - let absolute = data_start - .checked_add(tensor.offset) - .and_then(|offset| offset.checked_add(layout.source_byte_offset)) - .ok_or("GGUF part offset overflow")?; - let mut hashes = ParentHashes { - source: Sha256::new(), - f32: Sha256::new(), - }; + let absolute = layout_absolute(data_start, tensor.offset, layout.source_byte_offset)?; + let mut hashes = LayoutHashAccumulator::new(parent); let count = gguf_f32_stream::visit( source, absolute, tensor.kind, layout.source_bytes, - |raw, f32_bytes| { - hashes.source.update(raw); - hashes.f32.update(f32_bytes); - parent.source.update(raw); - parent.f32.update(f32_bytes); - Ok(()) - }, + |raw, f32_bytes| hashes.update(raw, f32_bytes), )?; if count != layout.derived_bytes { return Err("GGUF part derived byte count mismatch".into()); } - Ok(( - hashes.source.finalize().into(), - hashes.f32.finalize().into(), - )) + Ok(hashes.finish()) +} + +fn layout_absolute(data_start: u64, tensor_offset: u64, part_offset: u64) -> Result { + data_start + .checked_add(tensor_offset) + .and_then(|offset| offset.checked_add(part_offset)) + .ok_or_else(|| "GGUF part offset overflow".into()) +} + +impl LayoutHashAccumulator<'_> { + fn new(parent: &mut ParentHashes) -> LayoutHashAccumulator<'_> { + LayoutHashAccumulator { + part: ParentHashes { + source: Sha256::new(), + f32: Sha256::new(), + }, + parent, + } + } + + fn update(&mut self, source: &[u8], f32: &[u8]) -> Result<(), String> { + self.part.source.update(source); + self.part.f32.update(f32); + self.parent.source.update(source); + self.parent.f32.update(f32); + Ok(()) + } + + fn finish(self) -> ([u8; 32], [u8; 32]) { + ( + self.part.source.finalize().into(), + self.part.f32.finalize().into(), + ) + } } #[cfg(test)] mod tests { use super::*; + use std::path::PathBuf; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn gguf_f32(name: &str) -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.extend_from_slice(&(name.len() as u64).to_le_bytes()); + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&32u64.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend((0..32u32).flat_map(|value| (value as f32).to_le_bytes())); + bytes + } + + fn identity_fixture( + directory: &Path, + names: &[(&str, &str)], + ) -> derived_mixed::ShardedIdentity { + let entries = names + .iter() + .enumerate() + .map(|(index, (file, tensor))| identity_fixture_entry(directory, index, file, tensor)) + .collect::>(); + let (shards, tensors): (Vec<_>, Vec<_>) = entries.into_iter().unzip(); + derived_mixed::ShardedIdentity { + derived_sha256: [0; 32], + derived_bytes: tensors.len() as u64 * 128, + shards, + tensors, + } + } + + fn identity_fixture_entry( + directory: &Path, + index: usize, + file_name: &str, + tensor_name: &str, + ) -> (derived_mixed::ShardIdentity, derived_mixed::TensorIdentity) { + let bytes = gguf_f32(tensor_name); + std::fs::write(directory.join(file_name), &bytes).unwrap(); + let digest = Sha256::digest(&bytes).into(); + let f32_bytes = (0..32u32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let f32_digest = Sha256::digest(f32_bytes).into(); + let shard = derived_mixed::ShardIdentity { + name: file_name.into(), + gguf_sha256: digest, + gguf_bytes: bytes.len() as u64, + tensor_count: 1, + }; + let tensor = derived_mixed::TensorIdentity { + name: tensor_name.into(), + source_kind: 0, + source_sha256: f32_digest, + derived_offset: index as u64 * 128, + derived_bytes: 128, + f32_sha256: f32_digest, + }; + (shard, tensor) + } + + fn plan_test_dir(label: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!( + "strata-{label}-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&path).unwrap(); + path + } + + fn layout_hash_test_file() -> PathBuf { + let path = std::env::temp_dir().join(format!( + "strata-layout-hash-{}-{}.gguf", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::write(&path, 1.0f32.to_le_bytes()).unwrap(); + path + } + + fn layout_hash_fixture( + derived_bytes: u64, + ) -> (PathBuf, File, gguf::TensorInfo, Layout, ParentHashes) { + let path = layout_hash_test_file(); + let source = File::open(&path).unwrap(); + let tensor = gguf::TensorInfo { + name: "tensor".into(), + dimensions: vec![1], + kind: 0, + offset: 0, + bytes: 4, + }; + let layout = Layout { + name: "tensor".into(), + dimensions: vec![1], + source_byte_offset: 0, + source_bytes: 4, + derived_offset: 0, + derived_bytes, + }; + let parent = ParentHashes { + source: Sha256::new(), + f32: Sha256::new(), + }; + (path, source, tensor, layout, parent) + } + + #[test] + fn layout_absolute_checks_both_offset_additions() { + assert_eq!(layout_absolute(10, 20, 30), Ok(60)); + assert_eq!( + layout_absolute(u64::MAX, 1, 0), + Err("GGUF part offset overflow".into()) + ); + assert_eq!( + layout_absolute(0, u64::MAX, 1), + Err("GGUF part offset overflow".into()) + ); + } + + #[test] + fn shard_planner_preserves_manifest_tensor_order_and_rejects_missing_source() { + let directory = std::env::temp_dir().join(format!( + "strata-plan-parts-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&directory).unwrap(); + let identity = identity_fixture(&directory, &[("a.gguf", "weight")]); + let parts = plan_shards_with_limit(&identity, &directory, 32).unwrap(); + assert_eq!(parts[0][0].name, "weight"); + std::fs::remove_file(directory.join("a.gguf")).unwrap(); + assert!(plan_shards_with_limit(&identity, &directory, 32).is_err()); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn shard_planner_rejects_missing_ple_and_duplicate_part_names() { + let directory = plan_test_dir("plan-invalid"); + assert_missing_ple_is_rejected(&directory); + assert_duplicate_names_are_rejected(&directory); + assert_unsplit_ple_is_rejected(&directory); + std::fs::remove_dir_all(directory).unwrap(); + } + + fn assert_missing_ple_is_rejected(directory: &Path) { + let identity = identity_fixture(directory, &[("a.gguf", "weight")]); + let limits = PlanLimits { + max_part_elements: 32, + ple_part_elements: Some(32), + }; + assert!( + matches!(plan_shards_with_limits(&identity, directory, limits), Err(error) if error.contains("requires per_layer_token_embd.weight")) + ); + } + + fn assert_duplicate_names_are_rejected(directory: &Path) { + let identity = identity_fixture(directory, &[("b.gguf", "weight"), ("c.gguf", "weight")]); + let error = plan_shards_with_limit(&identity, directory, 32).unwrap_err(); + assert!(error.contains("duplicate KAR part name")); + } + + fn assert_unsplit_ple_is_rejected(directory: &Path) { + let identity = identity_fixture(directory, &[("ple.gguf", PLE_TENSOR_NAME)]); + let limits = PlanLimits { + max_part_elements: 32, + ple_part_elements: Some(32), + }; + let error = plan_shards_with_limits(&identity, directory, limits).unwrap_err(); + assert!(error.contains("must split the PLE tensor")); + } + + #[test] + fn shard_planner_checks_virtual_tensor_count_and_identity() { + let directory = plan_test_dir("plan-count"); + let mut identity = identity_fixture(&directory, &[("a.gguf", "weight")]); + identity.shards.clear(); + let error = plan_shards_with_limit(&identity, &directory, 32).unwrap_err(); + assert!(error.contains("tensor count differs")); + assert_virtual_source_mismatch_rejected(&directory); + std::fs::remove_dir_all(directory).unwrap(); + } + + fn assert_virtual_source_mismatch_rejected(directory: &Path) { + let bytes = gguf_f32("other"); + let identity = derived_mixed::ShardedIdentity { + derived_sha256: [0; 32], + derived_bytes: 128, + shards: vec![derived_mixed::ShardIdentity { + name: "a.gguf".into(), + gguf_sha256: Sha256::digest(&bytes).into(), + gguf_bytes: bytes.len() as u64, + tensor_count: 1, + }], + tensors: identity_fixture(directory, &[("a.gguf", "weight")]).tensors, + }; + std::fs::write(directory.join("a.gguf"), &bytes).unwrap(); + let error = plan_shards_with_limit(&identity, directory, 32).unwrap_err(); + assert!(error.contains("differs from virtual source")); + } + + #[test] + fn shard_planner_rejects_changed_tensor_count_and_kind() { + let directory = std::env::temp_dir().join(format!( + "strata-plan-changed-tensor-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&directory).unwrap(); + let mut identity = identity_fixture(&directory, &[("a.gguf", "weight")]); + identity.shards[0].tensor_count += 1; + assert!(plan_shards_with_limit(&identity, &directory, 32).is_err()); + identity.shards[0].tensor_count -= 1; + identity.tensors[0].source_kind = 1; + assert!(plan_shards_with_limit(&identity, &directory, 32).is_err()); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn shard_open_failure_is_returned_after_index_validation() { + let directory = std::env::temp_dir().join(format!( + "strata-plan-open-failure-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&directory).unwrap(); + let identity = identity_fixture(&directory, &[("a.gguf", "weight")]); + let mut planner = ShardPlanner::new( + &identity, + &directory, + PlanLimits { + max_part_elements: 32, + ple_part_elements: None, + }, + ); + let error = planner.plan_shard_with_open(&identity.shards[0], |_| { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + }); + assert_eq!( + error.unwrap_err(), + std::io::Error::from(std::io::ErrorKind::PermissionDenied).to_string() + ); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn split_parent_hashes_must_match_both_source_digests() { + let directory = std::env::temp_dir(); + let identity = identity_fixture(&directory, &[]); + let planner = ShardPlanner::new( + &identity, + &directory, + PlanLimits { + max_part_elements: 32, + ple_part_elements: None, + }, + ); + let tensor = parent_hash_test_tensor(); + let original = parent_hash_test_identity(); + assert!( + planner + .verify_parent_hashes(&tensor, &original, true, matching_parent_hashes()) + .is_ok() + ); + assert_source_hash_mismatch_rejected(&planner, &tensor); + assert_f32_hash_mismatch_rejected(&planner, &tensor); + } + + fn parent_hash_test_tensor() -> gguf::TensorInfo { + gguf::TensorInfo { + name: "weight".into(), + dimensions: vec![1], + kind: 0, + offset: 0, + bytes: 4, + } + } + + fn parent_hash_test_identity() -> derived_mixed::TensorIdentity { + derived_mixed::TensorIdentity { + name: "weight".into(), + source_kind: 0, + source_sha256: Sha256::digest(b"source").into(), + derived_offset: 0, + derived_bytes: 4, + f32_sha256: Sha256::digest(b"derived").into(), + } + } + + fn matching_parent_hashes() -> ParentHashes { + let mut hashes = ParentHashes { + source: Sha256::new(), + f32: Sha256::new(), + }; + hashes.source.update(b"source"); + hashes.f32.update(b"derived"); + hashes + } + + fn assert_source_hash_mismatch_rejected(planner: &ShardPlanner<'_>, tensor: &gguf::TensorInfo) { + let mut changed = parent_hash_test_identity(); + changed.source_sha256[0] ^= 1; + assert!( + planner + .verify_parent_hashes(tensor, &changed, true, matching_parent_hashes()) + .is_err() + ); + } + + fn assert_f32_hash_mismatch_rejected(planner: &ShardPlanner<'_>, tensor: &gguf::TensorInfo) { + let mut changed = parent_hash_test_identity(); + changed.f32_sha256[0] ^= 1; + assert!( + planner + .verify_parent_hashes(tensor, &changed, true, matching_parent_hashes()) + .is_err() + ); + } + + #[test] + fn hash_layout_streams_matching_source_and_derived_bytes() { + let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(4); + assert_matching_layout_hash(&mut source, &tensor, &layout, &mut parent); + drop(source); + std::fs::remove_file(path).unwrap(); + } + + fn assert_matching_layout_hash( + source: &mut File, + tensor: &gguf::TensorInfo, + layout: &Layout, + parent: &mut ParentHashes, + ) { + let expected: [u8; 32] = Sha256::digest(1.0f32.to_le_bytes()).into(); + assert_eq!( + hash_layout(source, 0, tensor, layout, parent).unwrap().0, + expected + ); + } + + #[test] + fn hash_layout_rejects_derived_byte_count_mismatch() { + let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(8); + assert_eq!( + hash_layout(&mut source, 0, &tensor, &layout, &mut parent).unwrap_err(), + "GGUF part derived byte count mismatch" + ); + drop(source); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn hash_layout_propagates_truncated_source_reads() { + let (path, mut source, tensor, layout, mut parent) = layout_hash_fixture(8); + std::fs::write(&path, []).unwrap(); + assert!(hash_layout(&mut source, 0, &tensor, &layout, &mut parent).is_err()); + drop(source); + std::fs::remove_file(path).unwrap(); + } #[test] fn giant_per_layer_tensor_becomes_two_contiguous_kar_parts() { diff --git a/docs/build-validation.md b/docs/build-validation.md index 693a2a2d..0785694b 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -1,5 +1,12 @@ # Build validation +## 2026-10-06 — KAR overlay publication recovery + +- Overlay preparation records a source/policy-bound pending intent before archive publication, verifies the archive before atomically publishing its separate sidecar, reads the sidecar back, and removes the intent last. Retry tests cover interruption before archive creation and after archive, sidecar, or intent publication; unrelated archive and sidecar bytes are preserved. +- `cargo fmt --manifest-path control-plane/Cargo.toml --check`, all-target Clippy with warnings denied, `cargo test --manifest-path control-plane/Cargo.toml --locked` (198 Rust tests), and `scripts/check-local.sh`'s Python/Rust/replay stages passed. The script stops at the host CPU build because CMake is unavailable on this macOS host. +- The CPU CMake/CTest stage passed separately inside GPU-hidden Docker using Ubuntu 24.04 arm64 digest `sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55`, CMake 3.28.3, and GCC 13.3.0: five CTest tests passed. The container had no GPU device or NVIDIA runtime and was removed automatically. +- Required §702.1 changed-scope 100% line/function/branch coverage remains **unverified**. The permitted branch-capable coverage attempt was SIGKILLed before it produced a valid machine-readable report; no partial percentage is treated as a pass. This validation does not establish installed-driver inference, model quality, or rollback. + ## 2026-10-03 — experimental PLE quality arm The imported engine builds on Linux CUDA 13.2/sm_120 with the optional diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 755177c4..f070981d 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -148,10 +148,20 @@ when that intent matches the current pinned shards and policy and a fresh independent archive verification succeeds; it then writes the sidecar with a no-replace link. An archive without a matching intent is never adopted, and an existing sidecar or archive is never overwritten. Temporary-link cleanup after -a successful archive or provenance publication can fail without invalidating -the atomically linked destination; any leftover `.part` file is not treated as -an archive or sidecar. Recovery proves artifact integrity only, not lossy model -quality or serving readiness. +a successful archive publication is retried once and cannot invalidate the +atomically linked destination; overlay preparation continues to provenance +publication after that final link. KAR writer temporary names are scoped to the +destination and one of eight fixed slots, created exclusively with mode `0600`, +and held under an advisory lock while being written and verified. This bounds +crash-left archive temp files per destination. A later write reaps only matching +temporary files when it can acquire the lock and confirm current-user ownership +and inode identity. Writers also verify that a newly locked slot still names +their opened inode before using it, closing the race with reaping. An unlinked +pre-publication crash partial is never confused with a final archive; a +published hard-link temporary is removed only when it is the same inode as +that destination. Recovery proves artifact integrity only, not lossy model +quality or serving readiness. Unknown or legacy temporary names are preserved +rather than guessed at or deleted. `model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally. @@ -169,6 +179,8 @@ For the target compressed runtime, copy the selected KAR data to VRAM in compres The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test. +Experimental `model prepare-kar-overlay` writes a matching `.pending.json` intent before publishing its archive. On retry it verifies the intent, KAR records/CRC and source identity before completing a missing provenance sidecar; the sidecar is no-replace and the intent is removed only after sidecar read-back verification. A complete archive and sidecar without an intent are reused only when both match the current inputs. Incomplete or unrelated outputs fail closed and are never overwritten. This is publication recovery, not approval of the lossy overlay for serving. + ## Cache profiles | Profile | Attention state | Status | diff --git a/scripts/check-changed-scope-coverage.py b/scripts/check-changed-scope-coverage.py new file mode 100644 index 00000000..4721b3e9 --- /dev/null +++ b/scripts/check-changed-scope-coverage.py @@ -0,0 +1,617 @@ +#!/usr/bin/env python3 +"""Run the pinned Linux unit suite and enforce changed-production Rust coverage.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +BASELINE = "d3e63a7" +NIGHTLY = "nightly-2026-10-05" +RUSTC_VERSION = "rustc 1.101.0-nightly (282215592 2026-10-04)" +LLVM_VERSION = "LLVM version 23.1.3-rust-1.101.0-nightly" +RUST_FILES = ( + "control-plane/src/kar_overlay.rs", + "control-plane/src/kar_stream_encode.rs", + "control-plane/src/kar_writer.rs", + "control-plane/src/model_pipeline.rs", + "control-plane/src/prepare_preview.rs", + "control-plane/src/stream_parts.rs", +) +DOCUMENT_FILES = ("docs/build-validation.md", "docs/compressed-runtime.md") +SCOPE_FILES = (*RUST_FILES, *DOCUMENT_FILES) +SCOPE_DEFINITION = ( + "Full bodies of production functions with added lines or corresponding deleted baseline lines; " + "cfg(test) item/block lines are excluded; generated production closures remain included." +) + + +def _blank(chars: list[str], start: int, end: int) -> None: + for index in range(start, end): + if chars[index] != "\n": + chars[index] = " " + + +def _block_end(source: str, start: int) -> int: + depth, index = 1, start + 2 + while index < len(source) and depth: + if source.startswith("/*", index): + depth, index = depth + 1, index + 2 + elif source.startswith("*/", index): + depth, index = depth - 1, index + 2 + else: + index += 1 + if depth: + raise ValueError(f"unclosed Rust block comment at byte {start}") + return index + + +def _raw_string_end(source: str, start: int) -> int | None: + match = re.match(r"(?:br|r)(#{0,})\"", source[start:]) + if not match: + return None + marker = '"' + match.group(1) + end = source.find(marker, start + match.end()) + return len(source) if end < 0 else end + len(marker) + + +def _quoted_end(source: str, start: int) -> int: + index = start + 1 + while index < len(source): + if source[index] == "\\": + index += 2 + elif source[index] == '"': + return index + 1 + else: + index += 1 + raise ValueError(f"unclosed Rust string at byte {start}") + + +def _char_end(source: str, start: int) -> int | None: + if start + 2 >= len(source): + return None + index = start + 1 + if source[index] == "\\": + index += 2 + if source[start + 1 : start + 3] == "\\u": + close = source.find("}", start + 3) + if close < 0: + return None + index = close + 1 + else: + index += 1 + return index + 1 if index < len(source) and source[index] == "'" else None + + +def mask_rust(source: str) -> str: + chars, index = list(source), 0 + while index < len(source): + raw_end = _raw_string_end(source, index) + if raw_end is not None: + _blank(chars, index, raw_end) + index = raw_end + elif source.startswith("//", index): + end = source.find("\n", index) + end = len(source) if end < 0 else end + _blank(chars, index, end) + index = end + elif source.startswith("/*", index): + end = _block_end(source, index) + _blank(chars, index, end) + index = end + elif source[index] == '"': + end = _quoted_end(source, index) + _blank(chars, index, end) + index = end + elif source[index] == "'" and (end := _char_end(source, index)): + _blank(chars, index, end) + index = end + else: + index += 1 + return "".join(chars) + + +def matching(mask: str, start: int, left: str, right: str) -> int: + depth = 0 + for index in range(start, len(mask)): + depth += mask[index] == left + depth -= mask[index] == right + if depth == 0: + return index + raise ValueError(f"unclosed Rust delimiter {left!r} at byte {start}") + + +def _body_depths(depths: list[int], char: str, previous: str) -> None: + if char == "(": depths[0] += 1 + elif char == ")": depths[0] -= 1 + elif char == "[": depths[1] += 1 + elif char == "]": depths[1] -= 1 + elif char == "<": depths[2] += 1 + elif char == ">" and previous != "-" and depths[2]: depths[2] -= 1 + + +def _body_open(mask: str, start: int) -> int: + depths = [0, 0, 0] + for index in range(start, len(mask)): + char = mask[index] + _body_depths(depths, char, mask[index - 1] if index else "") + if char in "{;" and not any(depths): + return index + return len(mask) + + +def _skip_space(mask: str, index: int) -> int: + while index < len(mask) and mask[index].isspace(): + index += 1 + return index + + +def _skip_attributes(mask: str, index: int) -> int: + while True: + index = _skip_space(mask, index) + if not mask.startswith("#[", index): + return index + index = matching(mask, index + 1, "[", "]") + 1 + + +def _skip_visibility(mask: str, index: int) -> int: + if not re.match(r"pub\b", mask[index:]): + return index + index = _skip_space(mask, index + 3) + if index < len(mask) and mask[index] == "(": + index = matching(mask, index, "(", ")") + 1 + return _skip_space(mask, index) + + +def _statement_depths(depths: list[int], char: str) -> bool: + if char == "(": depths[0] += 1 + elif char == ")": depths[0] -= 1 + elif char == "[": depths[1] += 1 + elif char == "]": depths[1] -= 1 + elif char == "{": depths[2] += 1 + elif char == "}": depths[2] -= 1 + return char == "}" and not any(depths) + + +def _statement_end(mask: str, start: int) -> int: + depths = [0, 0, 0] + for index, char in enumerate(mask[start:], start): + if _statement_depths(depths, char): + return index + 1 + if char == ";" and not any(depths): + return index + 1 + raise ValueError(f"cannot find end of Rust statement at byte {start}") + + +def _item_end(mask: str, start: int) -> int: + macro = re.match(r"(?:macro_rules!\s*[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_:][A-Za-z0-9_:]*!)\s*", mask[start:]) + if macro: + group = _skip_space(mask, start + macro.end()) + if group >= len(mask) or mask[group] not in "{([": + raise ValueError(f"unsupported cfg(test) macro at byte {start}") + close = {"{": "}", "(": ")", "[": "]"}[mask[group]] + return matching(mask, group, mask[group], close) + 1 + item = re.match(r"(fn|mod|impl|struct|enum|trait|use|const|static|type|extern)\b", mask[start:]) + if not item: + return _statement_end(mask, start) + kind, cursor = item.group(1), start + item.end() + if kind == "fn": + paren = mask.find("(", cursor) + close = matching(mask, paren, "(", ")") + cursor = _body_open(mask, close + 1) + if kind in {"use", "const", "static", "type"}: + return _statement_end(mask, cursor) + opening = _body_open(mask, cursor) + if opening < len(mask) and mask[opening] == "{": + return matching(mask, opening, "{", "}") + 1 + return _statement_end(mask, cursor) + + +def cfg_test_spans(source: str, mask: str) -> list[tuple[int, int]]: + spans = [] + pattern = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]") + for attr in pattern.finditer(mask): + if attr.start() and mask[attr.start() - 1] == "!": + spans.append((0, len(source))) + continue + start = _skip_visibility(mask, _skip_attributes(mask, attr.end())) + end = _item_end(mask, start) + spans.append((attr.start(), end)) + return _merge_spans(spans) + + +def _merge_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]: + merged = [] + for start, end in sorted(spans): + if merged and start <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(merged[-1][1], end)) + else: + merged.append((start, end)) + return merged + + +def _span_lines(source: str, spans: list[tuple[int, int]]) -> set[int]: + lines = set() + for start, end in spans: + first = source.count("\n", 0, start) + 1 + last = source.count("\n", 0, end) + 1 + lines.update(range(first, last + 1)) + return lines + + +def rust_functions(source: str) -> tuple[list[dict], set[int]]: + mask, found = mask_rust(source), [] + test_spans = cfg_test_spans(source, mask) + test_lines = _span_lines(source, test_spans) + for match in re.finditer(r"\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\b", mask): + if any(start <= match.start() < end for start, end in test_spans): + continue + paren = mask.find("(", match.end()) + close = matching(mask, paren, "(", ")") + opening = _body_open(mask, close + 1) + if opening >= len(mask) or mask[opening] != "{": + continue + end = matching(mask, opening, "{", "}") + 1 + found.append({"name": match.group(1), "start": source.count("\n", 0, match.start()) + 1, + "end": source.count("\n", 0, end) + 1}) + return found, test_lines + + +def parse_diff_hunks(diff: str) -> tuple[set[int], set[int]]: + added, deleted, new_line, old_line = set(), set(), 0, 0 + for line in diff.splitlines(): + if line.startswith("@@"): + match = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line) + if not match: + raise ValueError(f"invalid unified diff hunk: {line}") + old_line, new_line = int(match.group(1)), int(match.group(2)) + elif line.startswith("+++") or line.startswith("---") or line.startswith("\\"): + continue + elif line.startswith("+"): + added.add(new_line) + new_line += 1 + elif line.startswith("-"): + deleted.add(old_line) + old_line += 1 + elif line.startswith(" "): + old_line += 1 + new_line += 1 + return added, deleted + + +def select_production_functions(source: str, baseline_source: str, diff: str) -> tuple[list[dict], set[int]]: + additions, deletions = parse_diff_hunks(diff) + current, test_lines = rust_functions(source) + old, old_test_lines = rust_functions(baseline_source) + additions.difference_update(test_lines) + deletions.difference_update(old_test_lines) + deleted_names = {item["name"] for item in old if any(item["start"] <= line <= item["end"] for line in deletions)} + selected = [item for item in current if item["name"] in deleted_names or + any(item["start"] <= line <= item["end"] for line in additions)] + if not selected: + raise ValueError("baseline diff selects no current production functions") + return selected, test_lines + + +def parse_lcov(text: str) -> list[dict]: + records, record = [], None + for line in text.splitlines(): + if line.startswith("SF:"): + if record is not None: + raise ValueError("LCOV source record lacks end_of_record") + record = {"sf": line[3:], "da": [], "fn": [], "fnda": [], "brda": []} + elif line == "end_of_record": + if record is None: + raise ValueError("LCOV end_of_record without SF") + records.append(record) + record = None + elif record is not None: + _parse_lcov_row(record, line) + if record is not None: + raise ValueError("LCOV source record lacks end_of_record") + return records + + +def _parse_lcov_row(record: dict, line: str) -> None: + try: + if line.startswith("DA:"): + parts = line[3:].split(",") + record["da"].append((int(parts[0]), int(parts[1]))) + elif line.startswith("FN:"): + number, name = line[3:].split(",", 1) + record["fn"].append((int(number), name)) + elif line.startswith("FNDA:"): + count, name = line[5:].split(",", 1) + record["fnda"].append((int(count), name)) + elif line.startswith("BRDA:"): + number, block, branch, taken = line[5:].split(",", 3) + record["brda"].append((int(number), block, branch, taken)) + except (IndexError, ValueError) as error: + raise ValueError(f"invalid LCOV row: {line}") from error + + +def _record_path(record: dict) -> str: + path = record["sf"].replace("\\", "/") + return next((name for name in RUST_FILES if path == name or path.endswith("/" + name)), "") + + +def _inside(line: int, functions: list[dict], test_lines: set[int]) -> bool: + return line not in test_lines and any(item["start"] <= line <= item["end"] for item in functions) + + +def _merge_lcov(records: list[dict]) -> dict: + by_path = {} + for record in records: + path = _record_path(record) + if path: + by_path.setdefault(path, []).append(record) + return by_path + + +def _file_metrics(records: list[dict], functions: list[dict], test_lines: set[int]) -> dict: + da, fn, fnda, branch = _merge_record_metrics(records) + lines = {line: count for line, count in da.items() if _inside(line, functions, test_lines)} + funcs = {key: fnda.get(key[1], 0) for key in fn if _inside(key[0], functions, test_lines)} + branches = {key: value for key, value in branch.items() if _inside(key[0], functions, test_lines)} + return _metrics(lines, funcs, branches) + + +def _merge_record_metrics(records: list[dict]) -> tuple[dict, dict, dict, dict]: + da, fn, fnda, branch = {}, {}, {}, {} + for record in records: + _merge_record(record, da, fn, fnda, branch) + return da, fn, fnda, branch + + +def _merge_record(record: dict, da: dict, fn: dict, fnda: dict, branch: dict) -> None: + for line, count in record["da"]: + da[line] = da.get(line, 0) + count + for line, name in record["fn"]: + fn[(line, name)] = fn.get((line, name), 0) + for count, name in record["fnda"]: + fnda[name] = fnda.get(name, 0) + count + for line, block, number, taken in record["brda"]: + key = (line, block, number) + branch[key] = _branch_total(branch.get(key), taken) + + +def _branch_total(previous: str | None, taken: str) -> str: + if previous is None or taken == "-" or previous == "-": + return taken + return str(int(previous) + int(taken)) + + +def _metrics(lines: dict, functions: dict, branches: dict) -> dict: + line_misses = sorted(line for line, hits in lines.items() if hits == 0) + fn_misses = [{"line": line, "name": name} for (line, name), hits in functions.items() if hits == 0] + branch_misses = [{"line": line, "block": block, "branch": branch, "taken": taken} + for (line, block, branch), taken in branches.items() if taken in {"0", "-"}] + return {"lines": _metric(len(lines) - len(line_misses), len(lines), line_misses), + "functions": _metric(len(functions) - len(fn_misses), len(functions), fn_misses), + "branches": _metric(len(branches) - len(branch_misses), len(branches), branch_misses)} + + +def _metric(hit: int, total: int, misses: list) -> dict: + return {"hit": hit, "total": total, "percent": (100.0 * hit / total) if total else 0.0, + "misses": misses} + + +def coverage_report(records: list[dict], scopes: dict[str, tuple[list[dict], set[int]]]) -> dict: + by_path, files = _merge_lcov(records), {} + totals = {kind: {"hit": 0, "total": 0, "misses": []} for kind in ("lines", "functions", "branches")} + for path in RUST_FILES: + if path not in by_path: + raise ValueError(f"LCOV is missing required Rust source record: {path}") + functions, test_lines = scopes[path] + metrics = _file_metrics(by_path[path], functions, test_lines) + files[path] = {"functions": functions, "metrics": metrics} + for kind, values in metrics.items(): + totals[kind]["hit"] += values["hit"] + totals[kind]["total"] += values["total"] + totals[kind]["misses"].extend({**miss, "file": path} if isinstance(miss, dict) + else {"line": miss, "file": path} for miss in values["misses"]) + for kind, values in totals.items(): + values["percent"] = 100.0 * values["hit"] / values["total"] if values["total"] else 0.0 + return {"baseline": BASELINE, "files": files, "totals": totals} + + +def _run(command: list[str], root: Path, env: dict | None = None) -> subprocess.CompletedProcess: + return subprocess.run(command, cwd=root, env=env, text=True, capture_output=True, check=False) + + +def _rust_tools(root: Path) -> tuple[Path, Path, dict]: + rustc = _run(["rustc", f"+{NIGHTLY}", "-vV"], root) + if rustc.returncode: + raise RuntimeError(f"pinned rustc is unavailable: {rustc.stderr.strip()}") + versions = rustc.stdout.strip() + if RUSTC_VERSION not in versions: + raise RuntimeError(f"unexpected pinned rustc version: {versions.splitlines()[0]}") + details = dict(line.split(": ", 1) for line in versions.splitlines() if ": " in line) + sysroot = _run(["rustc", f"+{NIGHTLY}", "--print", "sysroot"], root) + if sysroot.returncode or "host" not in details: + raise RuntimeError("cannot resolve pinned LLVM tool directory") + bindir = Path(sysroot.stdout.strip()) / "lib" / "rustlib" / details["host"] / "bin" + tools = (bindir / "llvm-cov", bindir / "llvm-profdata") + for tool in tools: + version = _run([str(tool), "--version"], root) + if version.returncode or LLVM_VERSION not in version.stdout: + raise RuntimeError(f"unexpected {tool.name} version: {version.stdout.strip()}") + return tools[0], tools[1], {"rustc": versions.splitlines()[0], "llvm": LLVM_VERSION, "host": details["host"]} + + +def _package_id(root: Path) -> str: + result = _run(["cargo", "metadata", "--manifest-path", "control-plane/Cargo.toml", + "--locked", "--format-version=1", "--no-deps"], root) + if result.returncode: + raise RuntimeError(f"cargo metadata failed: {result.stderr.strip()}") + packages = [item["id"] for item in json.loads(result.stdout)["packages"] + if item["name"] == "strata-control"] + if len(packages) != 1: + raise RuntimeError(f"expected one strata-control package, found {len(packages)}") + return packages[0] + + +def _cargo_harness(json_path: Path, package_id: str) -> Path: + found = [] + for line in json_path.read_text().splitlines(): + try: item = json.loads(line) + except json.JSONDecodeError: continue + if _is_test_lib_artifact(item, package_id): + found.append(Path(item["executable"])) + if len(found) != 1 or not found[0].is_file(): + raise RuntimeError(f"expected one built strata-control lib test binary, found {len(found)}") + return found[0] + + +def _is_test_lib_artifact(item: dict, package_id: str) -> bool: + target = item.get("target", {}) + return (item.get("reason") == "compiler-artifact" and item.get("package_id") == package_id + and target.get("name") == "strata_control" and target.get("kind") == ["lib"] + and target.get("test") and item.get("executable")) + + +def _changed_scopes(root: Path) -> tuple[dict, dict]: + if _run(["git", "cat-file", "-e", f"{BASELINE}^{{commit}}"], root).returncode: + raise RuntimeError(f"baseline commit {BASELINE} is unavailable") + if _run(["git", "merge-base", "--is-ancestor", BASELINE, "HEAD"], root).returncode: + raise RuntimeError(f"baseline {BASELINE} is not an ancestor of HEAD") + scopes, functions_by_file = {}, {} + for path in RUST_FILES: + source = (root / path).read_text() + old = _run(["git", "show", f"{BASELINE}:{path}"], root) + diff = _run(["git", "diff", "--no-ext-diff", "--unified=0", BASELINE, "--", path], root) + if old.returncode or diff.returncode: + raise RuntimeError(f"cannot read baseline/diff for {path}") + funcs, test_lines = select_production_functions(source, old.stdout, diff.stdout) + scopes[path] = (funcs, test_lines) + functions_by_file[path] = funcs + return scopes, functions_by_file + + +def _diff_hash(root: Path, paths: tuple[str, ...]) -> str: + result = _run(["git", "diff", "--binary", BASELINE, "--", *paths], root) + if result.returncode: + raise RuntimeError(f"cannot hash changed paths: {', '.join(paths)}") + return hashlib.sha256(result.stdout.encode()).hexdigest() + + +def _commit(root: Path, revision: str) -> str: + result = _run(["git", "rev-parse", revision], root) + if result.returncode: + raise RuntimeError(f"cannot resolve commit {revision}") + return result.stdout.strip() + + +def _coverage_env(out: Path) -> dict: + env = os.environ.copy() + flags = "-C instrument-coverage -Zcoverage-options=branch --cfg=coverage " + flags += "--cfg=coverage_nightly -C link-arg=-Wl,--no-keep-memory" + env.update({"RUSTFLAGS": flags, + "CARGO_BUILD_JOBS": "1", "CARGO_INCREMENTAL": "0", "RUST_TEST_THREADS": "1", + "CARGO_PROFILE_DEV_DEBUG": "0", "CARGO_PROFILE_TEST_DEBUG": "0", + "LLVM_PROFILE_FILE": str(out / "profraw" / "%m-%p.profraw")}) + (out / "profraw").mkdir(parents=True, exist_ok=True) + return env + + +def _write_summary(out: Path, report: dict) -> None: + (out / "summary.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + rows = [f"Changed-production coverage vs {report['baseline']}"] + for kind, value in report.get("totals", {}).items(): + rows.append(f"{kind}: {value['hit']}/{value['total']} ({value.get('percent', 0.0):.2f}%)") + rows.append(f"Gate: {'PASS' if report.get('passed') else 'FAIL'}") + rows.append(f"Reason: {report.get('failure', 'all required gates passed')}") + (out / "summary.txt").write_text("\n".join(rows) + "\n") + + +def _run_instrumented_tests(root: Path, out: Path, env: dict) -> tuple[int, Path, int]: + cargo_json, cargo_stderr = out / "cargo.jsonl", out / "cargo.stderr" + command = ["cargo", f"+{NIGHTLY}", "test", "--manifest-path", "control-plane/Cargo.toml", + "--locked", "-p", "strata-control", "--lib", "--message-format=json-render-diagnostics"] + with cargo_json.open("w") as stdout, cargo_stderr.open("w") as stderr: + test = subprocess.run(command, cwd=root, env=env, stdout=stdout, stderr=stderr, check=False) + binary = _cargo_harness(cargo_json, _package_id(root)) + profiles = sorted((out / "profraw").glob("*.profraw")) + if not profiles: + raise RuntimeError("instrumented tests produced no profraw files") + return test.returncode, binary, len(profiles) + + +def _export_lcov(root: Path, out: Path, llvm_cov: Path, llvm_profdata: Path, + binary: Path) -> str: + profiles = sorted((out / "profraw").glob("*.profraw")) + profile = out / "merged.profdata" + merge = _run([str(llvm_profdata), "merge", "-sparse", "-o", str(profile), *map(str, profiles)], root) + if merge.returncode: + (out / "llvm-profdata.stderr").write_text(merge.stderr) + raise RuntimeError("llvm-profdata merge failed") + export = _run([str(llvm_cov), "export", "--format=lcov", f"--instr-profile={profile}", str(binary)], root) + (out / "llvm-cov.stderr").write_text(export.stderr) + if export.returncode: + raise RuntimeError("llvm-cov export failed") + (out / "coverage.raw.lcov").write_text(export.stdout) + return export.stdout + + +def _coverage_passed(state: dict, test_exit: int) -> bool: + exact = all(values["total"] > 0 and values["hit"] == values["total"] + for values in state["totals"].values()) + return test_exit == 0 and exact + + +def _stable_diff(root: Path, state: dict) -> None: + if state["rust_six_path_diff_sha256"] != _diff_hash(root, RUST_FILES): + raise RuntimeError("Rust source diff changed during coverage collection") + if state["full_eight_path_diff_sha256"] != _diff_hash(root, SCOPE_FILES): + raise RuntimeError("eight-path source/docs diff changed during coverage collection") + + +def _attach_scope_result(state: dict, test_exit: int) -> None: + state["scope_files"] = list(RUST_FILES) + state["scope_definition"] = SCOPE_DEFINITION + state["measurement"] = "unit line/function/branch coverage; literal 100 percent required" + state["source_diff_sha256"] = state["rust_six_path_diff_sha256"] + state["passed"] = _coverage_passed(state, test_exit) + state["failure"] = "" if state["passed"] else "unit tests failed or changed-scope coverage was not exactly 100%" + + +def run_coverage(root: Path, out: Path) -> int: + out.mkdir(parents=True, exist_ok=True) + state = {"baseline": BASELINE, "head": "unknown", "passed": False, "failure": "not started"} + try: + state["head"] = _commit(root, "HEAD") + state["baseline_commit"] = _commit(root, BASELINE) + scopes, _ = _changed_scopes(root) + state["rust_six_path_diff_sha256"] = _diff_hash(root, RUST_FILES) + state["full_eight_path_diff_sha256"] = _diff_hash(root, SCOPE_FILES) + llvm_cov, llvm_profdata, versions = _rust_tools(root) + state["toolchain"] = versions + test_exit, binary, profile_count = _run_instrumented_tests(root, out, _coverage_env(out)) + state.update(cargo_exit_code=test_exit, selected_test_binary=str(binary), profraw_files=profile_count) + raw = _export_lcov(root, out, llvm_cov, llvm_profdata, binary) + report = coverage_report(parse_lcov(raw), scopes) + state.update(report) + _stable_diff(root, state) + _attach_scope_result(state, test_exit) + except Exception as error: + state["failure"] = f"{type(error).__name__}: {error}" + _write_summary(out, state) + print((out / "summary.txt").read_text(), end="") + return 0 if state["passed"] else 1 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path.cwd()) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + return run_coverage(args.root.resolve(), args.output_dir.resolve()) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test-changed-scope-coverage.py b/scripts/test-changed-scope-coverage.py new file mode 100644 index 00000000..9d8e223f --- /dev/null +++ b/scripts/test-changed-scope-coverage.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Deterministic parser and workflow-contract tests for the manual coverage gate.""" +from __future__ import annotations + +import importlib.util +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +EXISTING_JOBS_SHA256 = "26cf64e51e207b9f81cef306e4ec31f3ed817334699e0b0fe7c7a031cb848a25" +PUSH_PULL_SHA256 = "cefb2858cd9b21076e171fa764dbf2df1472b911cc0743caa6fac7d09a216c89" +SPEC = importlib.util.spec_from_file_location("changed_scope", ROOT / "scripts/check-changed-scope-coverage.py") +COVERAGE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(COVERAGE) + + +def _job_block(text: str, name: str) -> str: + lines = text.splitlines(keepends=True) + start = next(index for index, line in enumerate(lines) if line == f" {name}:\n") + end = next((index for index in range(start + 1, len(lines)) + if lines[index].startswith(" ") and not lines[index].startswith(" ") + and lines[index].strip().endswith(":")), len(lines)) + return "".join(lines[start:end]) + + +def _lcov(path: str, branch: str = "1") -> str: + return (f"SF:{path}\nFN:1,live\nFNDA:1,live\nDA:1,1\nDA:2,1\n" + f"BRDA:2,0,0,{branch}\nend_of_record\n") + + +class ChangedScopeCoverageTests(unittest.TestCase): + def test_rust_mask_and_cfg_test_exclusion(self) -> None: + source = ''' +// fn comment() {} +const TEXT: &str = r###"fn raw_fake() {}"###; +pub fn live(value: u8) -> u8 { if value > 0 { value } else { 0 } } +#[cfg(test)] +mod tests { #[test] fn hidden() {} } +pub fn with_test_only_block() { + #[cfg(test)] if true { unreachable!(); } +} +''' + functions, test_lines = COVERAGE.rust_functions(source) + self.assertEqual([item["name"] for item in functions], ["live", "with_test_only_block"]) + self.assertTrue(test_lines) + self.assertNotIn("fn raw_fake", COVERAGE.mask_rust(source)) + + def test_diff_hunks_select_only_added_and_deleted_new_lines(self) -> None: + diff = "--- a/x\n+++ b/x\n@@ -2,2 +2,2 @@\n old\n+added\n-gone\n" + self.assertEqual(COVERAGE.parse_diff_hunks(diff), ({3}, {3})) + + def test_changed_scope_selects_body_but_excludes_test_additions(self) -> None: + old = "fn stable() { 1 }\nfn live() { 2 }\n#[cfg(test)]\nmod tests { fn sample() {} }\n" + new = "fn stable() { 1 }\nfn live() { 3 }\n#[cfg(test)]\nmod tests { fn sample() { 4 } }\n" + diff = ("@@ -2 +2 @@\n-fn live() { 2 }\n+fn live() { 3 }\n" + "@@ -4 +4 @@\n-mod tests { fn sample() {} }\n+mod tests { fn sample() { 4 } }\n") + selected, _ = COVERAGE.select_production_functions(new, old, diff) + self.assertEqual([item["name"] for item in selected], ["live"]) + + def test_lcov_zero_and_unknown_branches_fail_closed(self) -> None: + record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "-"))[0] + metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set()) + self.assertEqual(metrics["branches"]["hit"], 0) + self.assertEqual(metrics["branches"]["misses"][0]["taken"], "-") + record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "0"))[0] + metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set()) + self.assertEqual(metrics["branches"]["hit"], 0) + + def test_coverage_requires_every_production_file_and_exact_hits(self) -> None: + scopes = {path: ([{"name": "live", "start": 1, "end": 3}], set()) + for path in COVERAGE.RUST_FILES} + records = [COVERAGE.parse_lcov(_lcov(path))[0] for path in COVERAGE.RUST_FILES] + report = COVERAGE.coverage_report(records, scopes) + self.assertTrue(all(item["hit"] == item["total"] for item in report["totals"].values())) + with self.assertRaisesRegex(ValueError, "missing required Rust source"): + COVERAGE.coverage_report(records[:-1], scopes) + records[0]["brda"][0] = (2, "0", "0", "0") + report = COVERAGE.coverage_report(records, scopes) + self.assertNotEqual(report["totals"]["branches"]["hit"], report["totals"]["branches"]["total"]) + + def test_cargo_json_selects_only_the_package_lib_test_executable(self) -> None: + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / "strata_control-test" + binary.touch() + rows = [{"reason": "compiler-artifact", "package_id": "other 1.0.0", + "target": {"name": "strata_control", "kind": ["lib"], "test": True}, + "executable": str(binary)}, + {"reason": "compiler-artifact", "package_id": "strata-control 1.0.0", + "target": {"name": "strata_control", "kind": ["lib"], "test": True}, + "executable": str(binary)}] + log = Path(directory) / "cargo.jsonl" + log.write_text("\n".join(json.dumps(row) for row in rows)) + self.assertEqual(COVERAGE._cargo_harness(log, "strata-control 1.0.0"), binary) + + def test_workflow_adds_opt_in_cpu_job_without_changing_existing_jobs(self) -> None: + current = (ROOT / ".github/workflows/linux.yml").read_text() + original = subprocess.run(["git", "show", "HEAD:.github/workflows/linux.yml"], + cwd=ROOT, capture_output=True, text=True, check=True).stdout + job_names = ("verify", "keyless-cuda", "hosted-cuda-package", "linux-static-cli", + "linux-cli-container", "release-cli") + self.assertEqual(_digest("".join(_job_block(current, name) for name in job_names)), + EXISTING_JOBS_SHA256) + self.assertEqual(_digest(_push_pull_block(current)), PUSH_PULL_SHA256) + for name in job_names: + self.assertEqual(_job_block(current, name), _job_block(original, name), name) + self.assertIn("pull_request:\n workflow_dispatch:", current) + self.assertIn("changed_scope_coverage:\n description:", current) + self.assertIn("type: boolean\n default: false", current) + job = _job_block(current, "changed-scope-coverage") + self.assertIn("needs: verify", job) + self.assertIn("runs-on: ubuntu-latest", job) + self.assertNotIn("self-hosted", job) + self.assertNotIn("strata-gpu", job) + self.assertIn("inputs.changed_scope_coverage", job) + self.assertIn("nightly-2026-10-05", job) + self.assertIn("scripts/check-changed-scope-coverage.py", job) + self.assertIn("if: always()", job) + self.assertIn("actions/upload-artifact@v4.4.3", job) + self.assertIn("coverage.raw.lcov", job) + self.assertIn("summary.json", job) + self.assertIn("summary.txt", job) + + +def _digest(value: str) -> str: + import hashlib + return hashlib.sha256(value.encode()).hexdigest() + + +def _push_pull_block(text: str) -> str: + start = text.index("on:\n") + len("on:\n") + end = text.index(" workflow_dispatch:", start) + return text[start:end] + + +if __name__ == "__main__": + unittest.main(verbosity=2) -- 2.54.0 From 8b6ed672dd8cac97d2b9be9b5f1ce7c8b7fe533e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 01:07:51 +0200 Subject: [PATCH 35/58] Fix portable sticky-bit mask lint --- control-plane/src/kar_writer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index a4ad4603..9d0fe1e8 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -292,7 +292,7 @@ fn validate_private_archive_parent(parent: &Path) -> Result<(), String> { return Err("KAR parent is not owned by the service or root".into()); } let mode = metadata.mode(); - let sticky = mode & libc::S_ISVTX as u32 != 0; + let sticky = mode & 0o1000 != 0; // POSIX S_ISVTX is mode bit 01000. if mode & 0o022 != 0 && !sticky { return Err("KAR parent allows untrusted path replacement".into()); } -- 2.54.0 From 08e8f81eda6309bc115573d92f04c79d690527a5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 01:16:26 +0200 Subject: [PATCH 36/58] Report changed coverage misses in workflow logs --- .github/workflows/linux.yml | 14 --------- scripts/check-changed-scope-coverage.py | 38 +++++++++++++++++++++++-- scripts/test-changed-scope-coverage.py | 26 +++++++++++++---- 3 files changed, 57 insertions(+), 21 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index b28d792a..cfd1fa54 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -64,20 +64,6 @@ jobs: run: python3 scripts/test-changed-scope-coverage.py - name: Run exact changed-production coverage gate run: python3 scripts/check-changed-scope-coverage.py --root "$GITHUB_WORKSPACE" --output-dir "$RUNNER_TEMP/changed-scope-coverage" - - name: Archive raw LCOV and machine-readable summary - if: always() - uses: actions/upload-artifact@v4.4.3 - with: - name: changed-scope-coverage-${{ github.run_id }}-${{ github.run_attempt }} - path: | - ${{ runner.temp }}/changed-scope-coverage/coverage.raw.lcov - ${{ runner.temp }}/changed-scope-coverage/summary.json - ${{ runner.temp }}/changed-scope-coverage/summary.txt - ${{ runner.temp }}/changed-scope-coverage/cargo.stderr - ${{ runner.temp }}/changed-scope-coverage/llvm-cov.stderr - ${{ runner.temp }}/changed-scope-coverage/llvm-profdata.stderr - if-no-files-found: warn - retention-days: 14 keyless-cuda: if: github.event_name == 'workflow_dispatch' && github.event.inputs.keyless_gpu == 'true' diff --git a/scripts/check-changed-scope-coverage.py b/scripts/check-changed-scope-coverage.py index 4721b3e9..5e674a10 100644 --- a/scripts/check-changed-scope-coverage.py +++ b/scripts/check-changed-scope-coverage.py @@ -521,12 +521,46 @@ def _coverage_env(out: Path) -> dict: def _write_summary(out: Path, report: dict) -> None: (out / "summary.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + rows = summary_lines(report) + (out / "summary.txt").write_text("\n".join(rows) + "\n") + + +def summary_lines(report: dict) -> list[str]: rows = [f"Changed-production coverage vs {report['baseline']}"] - for kind, value in report.get("totals", {}).items(): + totals = report.get("totals", {}) + for kind in ("lines", "functions", "branches"): + value = totals.get(kind, {}) rows.append(f"{kind}: {value['hit']}/{value['total']} ({value.get('percent', 0.0):.2f}%)") rows.append(f"Gate: {'PASS' if report.get('passed') else 'FAIL'}") rows.append(f"Reason: {report.get('failure', 'all required gates passed')}") - (out / "summary.txt").write_text("\n".join(rows) + "\n") + if not report.get("passed"): + rows.extend(_miss_inventory(totals)) + return rows + + +def _miss_inventory(totals: dict) -> list[str]: + rows = ["Miss inventory (file:line; deterministic order):"] + for kind in ("lines", "functions", "branches"): + misses = totals.get(kind, {}).get("misses", []) + rows.append(f"{kind} misses: {len(misses)}") + for miss in sorted(misses, key=_miss_sort_key): + rows.append(f" {_format_miss(kind, miss)}") + return rows + + +def _miss_sort_key(miss: dict) -> tuple: + return (miss.get("file", ""), miss.get("line", 0), miss.get("block", ""), + miss.get("branch", ""), miss.get("name", ""), miss.get("taken", "")) + + +def _format_miss(kind: str, miss: dict) -> str: + location = f"{miss.get('file', '')}:{miss.get('line', 0)}" + if kind == "functions": + return f"{location} {miss.get('name', '')}" + if kind == "branches": + return (f"{location} block={miss.get('block', '')} " + f"branch={miss.get('branch', '')} taken={miss.get('taken', '')}") + return location def _run_instrumented_tests(root: Path, out: Path, env: dict) -> tuple[int, Path, int]: diff --git a/scripts/test-changed-scope-coverage.py b/scripts/test-changed-scope-coverage.py index 9d8e223f..b98d0e9a 100644 --- a/scripts/test-changed-scope-coverage.py +++ b/scripts/test-changed-scope-coverage.py @@ -81,6 +81,25 @@ pub fn with_test_only_block() { report = COVERAGE.coverage_report(records, scopes) self.assertNotEqual(report["totals"]["branches"]["hit"], report["totals"]["branches"]["total"]) + def test_failure_summary_prints_deterministic_complete_miss_inventory(self) -> None: + report = {"baseline": "d3e63a7", "passed": False, "failure": "coverage below 100%", + "totals": {"lines": {"hit": 0, "total": 1, + "misses": [{"file": "b.rs", "line": 9}, + {"file": "a.rs", "line": 4}]}, + "functions": {"hit": 0, "total": 1, + "misses": [{"file": "a.rs", "line": 7, "name": "f"}]}, + "branches": {"hit": 0, "total": 1, + "misses": [{"file": "b.rs", "line": 9, "block": "1", + "branch": "0", "taken": "-"}]}}} + lines = COVERAGE.summary_lines(report) + self.assertEqual(lines[6:9], ["Miss inventory (file:line; deterministic order):", + "lines misses: 2", " a.rs:4"]) + self.assertIn(" a.rs:7 f", lines) + self.assertIn(" b.rs:9 block=1 branch=0 taken=-", lines) + self.assertEqual(lines, COVERAGE.summary_lines(report)) + self.assertFalse(any("a.rs:4" in line for line in COVERAGE.summary_lines( + {**report, "passed": True}))) + def test_cargo_json_selects_only_the_package_lib_test_executable(self) -> None: with tempfile.TemporaryDirectory() as directory: binary = Path(directory) / "strata_control-test" @@ -117,11 +136,8 @@ pub fn with_test_only_block() { self.assertIn("inputs.changed_scope_coverage", job) self.assertIn("nightly-2026-10-05", job) self.assertIn("scripts/check-changed-scope-coverage.py", job) - self.assertIn("if: always()", job) - self.assertIn("actions/upload-artifact@v4.4.3", job) - self.assertIn("coverage.raw.lcov", job) - self.assertIn("summary.json", job) - self.assertIn("summary.txt", job) + self.assertNotIn("actions/upload-artifact", job) + self.assertNotIn("download-artifact", job) def _digest(value: str) -> str: -- 2.54.0 From 64635378590e6eb7e463c31b405f0d86a07fd54e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 01:45:40 +0200 Subject: [PATCH 37/58] Test remaining STRA-8 resolver coverage branches --- control-plane/src/kar_overlay.rs | 10 ++ control-plane/src/kar_writer.rs | 14 +++ control-plane/src/prepare_preview.rs | 161 ++++++++++++++++++++++++++- 3 files changed, 183 insertions(+), 2 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index efe40bf1..44a3ef62 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -1362,6 +1362,16 @@ mod tests { } } + #[test] + fn resolver_rejects_missing_archive_parent_before_opening_sidecars() { + let directory = TestDir::new("missing-parent"); + let missing = directory.0.join("missing"); + assert!(resolve_verified(&missing.join("base.kar"), &missing.join("overlay.kar")).is_err()); + assert!( + resolve_verified(&directory.0.join("base.kar"), &missing.join("overlay.kar")).is_err() + ); + } + fn candidate_value( schema: &str, levels: u8, diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 9d0fe1e8..dd1a8648 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -2420,6 +2420,20 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + #[test] + fn sticky_private_archive_parent_allows_shared_directory_mode() { + let root = test_dir("sticky-private-parent"); + let parent = fs::canonicalize(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o770)).unwrap(); + assert!(validate_private_archive_parent(&parent).is_err()); + fs::set_permissions(&root, fs::Permissions::from_mode(0o1770)).unwrap(); + assert_eq!(fs::metadata(&root).unwrap().mode() & 0o1777, 0o1770); + validate_private_archive_parent(&parent).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] #[test] fn archive_temp_metadata_matching_fails_closed_on_metadata_errors() { diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 4ca106d8..2a5d1407 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -2956,6 +2956,145 @@ mod tests { assert_changed_size_source_rejected(&request, &index, &identity); } + #[test] + fn single_tensor_read_rejects_source_truncated_after_indexing() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("truncated-after-index.gguf"); + let original = two_tensor_f32_gguf(); + fs::write(&path, &original).unwrap(); + let index = gguf::tensor_index(&path).unwrap(); + let identity = single_source_identity_for(&path, &index, &original); + let request = SingleSourcePrepare { + source_path: &path, + destination: Path::new("unused.kar"), + levels: 2, + kind: PreviewKind::F32, + }; + let staging_path = fixture.directory.join("staging"); + fs::create_dir(&staging_path).unwrap(); + assert_truncated_tensor_read_fails(&path, &request, &index, &identity, &staging_path); + } + + #[test] + fn prepared_shard_verification_detects_size_and_digest_changes() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("prepared-check.gguf"); + fs::write(&path, b"verified source").unwrap(); + let source = File::open(&path).unwrap(); + let mut shard = derived_mixed::ShardIdentity { + name: "prepared-check.gguf".into(), + gguf_sha256: hash_file(&path).unwrap(), + gguf_bytes: fs::metadata(&path).unwrap().len(), + tensor_count: 1, + }; + shard.gguf_bytes += 1; + assert!(verify_prepared_shard(&path, &shard, &source).is_err()); + shard.gguf_bytes -= 1; + fs::write(&path, b"changed source!").unwrap(); + assert!(verify_prepared_shard(&path, &shard, &source).is_err()); + } + + #[test] + fn shard_index_rejects_architecture_count_and_size_drift() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("index-check.gguf"); + fs::write(&path, two_tensor_f32_gguf()).unwrap(); + let mut index = gguf::tensor_index(&path).unwrap(); + let shard = derived_mixed::ShardIdentity { + name: "index-check.gguf".into(), + gguf_sha256: hash_file(&path).unwrap(), + gguf_bytes: index.summary.file_size, + tensor_count: index.tensors.len(), + }; + assert!(check_shard_index(&index, &shard, &mut None).is_ok()); + assert!(check_shard_index(&index, &shard, &mut Some("other".into())).is_err()); + assert_bad_shard_counts(&index, &shard); + index.summary.architecture = None; + assert!(check_shard_index(&index, &shard, &mut None).is_ok()); + } + + #[test] + fn sharded_tensor_read_rejects_payload_truncated_after_indexing() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("truncated-shard.gguf"); + let raw = 1.25f32.to_le_bytes(); + fs::write(&path, one_shard("weight", 0, 1, &raw)).unwrap(); + let index = gguf::tensor_index(&path).unwrap(); + let tensor = &index.tensors[0]; + let identity = derived_mixed::ShardedIdentity { + derived_sha256: [0; 32], + derived_bytes: 4, + shards: Vec::new(), + tensors: vec![sharded_identity_for(tensor, &raw, &[1.25])], + }; + assert_sharded_payload_read_fails(&path, &index, tensor, &identity); + } + + fn assert_sharded_payload_read_fails( + path: &Path, + index: &gguf::TensorIndex, + tensor: &gguf::TensorInfo, + identity: &derived_mixed::ShardedIdentity, + ) { + fs::write( + path, + &fs::read(path).unwrap()[..index.summary.data_start as usize], + ) + .unwrap(); + assert!( + read_sharded_weights(identity, index, tensor, &mut File::open(path).unwrap(), 0) + .is_err() + ); + } + + fn assert_bad_shard_counts(index: &gguf::TensorIndex, shard: &derived_mixed::ShardIdentity) { + let wrong_count = derived_mixed::ShardIdentity { + name: shard.name.clone(), + gguf_sha256: shard.gguf_sha256, + gguf_bytes: shard.gguf_bytes, + tensor_count: shard.tensor_count + 1, + }; + assert!(check_shard_index(index, &wrong_count, &mut None).is_err()); + let wrong_size = derived_mixed::ShardIdentity { + name: shard.name.clone(), + gguf_sha256: shard.gguf_sha256, + gguf_bytes: shard.gguf_bytes + 1, + tensor_count: shard.tensor_count, + }; + assert!(check_shard_index(index, &wrong_size, &mut None).is_err()); + } + + fn assert_truncated_tensor_read_fails( + path: &Path, + source: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, + identity: &SingleSourceIdentity, + staging_path: &Path, + ) { + fs::write( + path, + &fs::read(path).unwrap()[..index.summary.data_start as usize], + ) + .unwrap(); + let mut source_file = File::open(path).unwrap(); + let mut progress = SingleTensorProgress { + total_elements: 0, + maximum_relative_l2: 0.0, + prepared: Vec::new(), + }; + let staging = StagingDir(staging_path.to_path_buf()); + let request = SingleTensorRequest { + source, + index, + identity, + staging: &staging, + tensor: &index.tensors[0], + number: 0, + }; + assert!(prepare_single_tensor(request, &mut source_file, &mut progress).is_err()); + assert!(progress.prepared.is_empty()); + } + fn single_source_identity_for( path: &Path, index: &gguf::TensorIndex, @@ -4832,6 +4971,23 @@ mod tests { reject_corrupt_overlay_provenance(&fixture, &result); } + #[test] + fn resolver_rejects_malformed_overlay_sidecar() { + let fixture = overlay_fixture(); + fixture.prepare().unwrap(); + fs::write(fixture.overlay_sidecar(), b"{").unwrap(); + assert!(crate::kar_overlay::resolve_verified(&fixture.base, &fixture.overlay).is_err()); + } + + #[test] + fn resolver_rejects_malformed_base_sidecar() { + let fixture = overlay_fixture(); + fixture.prepare().unwrap(); + let sidecar = fixture.base.with_file_name("base.kar.provenance.json"); + fs::write(sidecar, b"{").unwrap(); + assert!(crate::kar_overlay::resolve_verified(&fixture.base, &fixture.overlay).is_err()); + } + #[test] fn overlay_publication_recovers_each_process_death_boundary() { for stage in 1..=4 { @@ -5137,7 +5293,8 @@ mod tests { } fn bad_parent_coverage(value: &mut serde_json::Value) { - value["partitioned_tensors"][0]["parent_dimensions"] = serde_json::json!([511]); + value["partitioned_tensors"][0]["parts"][1]["dimensions"] = serde_json::json!([255]); + value["partitioned_tensors"][0]["parts"][1]["derived_bytes"] = serde_json::json!(255 * 4); } fn base_part_collision(value: &mut serde_json::Value) { @@ -5195,7 +5352,7 @@ mod tests { fn duplicate_overlay_record(value: &mut serde_json::Value) { let first = value["records"][0].clone(); - value["records"][1] = first; + value["records"].as_array_mut().unwrap().push(first); } fn bad_overlay_record(value: &mut serde_json::Value) { -- 2.54.0 From 65a01a851609e94ff45e1efbd7fd4a7240c20257 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 02:08:18 +0200 Subject: [PATCH 38/58] test: cover sharded KAR failure recovery paths --- control-plane/src/kar_writer.rs | 12 ++++++ control-plane/src/prepare_preview.rs | 60 ++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index dd1a8648..a9d5b105 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -2993,6 +2993,18 @@ mod tests { assert!(round_up(u64::MAX, 256).is_err()); } + #[test] + fn nested_layout_propagates_section_alignment_overflow() { + let offsets = NestedOffsets { + books: 0, + planes: u64::MAX - 1, + stride: 1, + end: u64::MAX, + }; + let result = finish_nested_layout(0, 32, 1, 2, offsets); + assert!(result.is_err_and(|error| error.contains("aligned offset overflow"))); + } + fn assert_invalid_nested_layout_parameters() { for (group, nesting, min, max, levels) in [ (0, 0, 1, 2, 2), diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 2a5d1407..41dcbcd0 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -4662,6 +4662,66 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } + #[test] + fn eager_sharded_prepare_preserves_reserved_sidecar_and_removes_archive() { + let fixture = overlay_fixture(); + let output = fixture.directory.join("legacy.kar"); + let sidecar = provenance_path(&output).unwrap(); + fs::write(&sidecar, b"reserved provenance").unwrap(); + + assert!(prepare_sharded(&fixture.manifest, &fixture.directory, &output, 2).is_err()); + + assert!(!output.exists()); + assert_eq!(fs::read(&sidecar).unwrap(), b"reserved provenance"); + assert!(!legacy_staging_path(&output).exists()); + } + + #[test] + fn eager_sharded_prepare_rejects_reserved_staging_without_mutation() { + let fixture = overlay_fixture(); + let output = fixture.directory.join("legacy.kar"); + let staging = legacy_staging_path(&output); + fs::create_dir(&staging).unwrap(); + let sentinel = staging.join("owned-by-another-writer"); + fs::write(&sentinel, b"keep").unwrap(); + + assert!(prepare_sharded(&fixture.manifest, &fixture.directory, &output, 2).is_err()); + + assert!(!output.exists()); + assert_eq!(fs::read(sentinel).unwrap(), b"keep"); + fs::remove_dir_all(staging).unwrap(); + } + + #[test] + fn eager_sharded_prepare_rejects_invalid_levels_before_staging() { + let fixture = overlay_fixture(); + let output = fixture.directory.join("legacy.kar"); + + assert!( + prepare_sharded(&fixture.manifest, &fixture.directory, &output, 0) + .unwrap_err() + .contains("1..=8") + ); + + assert!(!output.exists()); + assert!(!legacy_staging_path(&output).exists()); + } + + #[test] + fn preview_kind_names_are_stable_for_validation_errors() { + assert_eq!(preview_kind_name(PreviewKind::F32), "F32"); + assert_eq!(preview_kind_name(PreviewKind::Iq3), "IQ3_S"); + assert_eq!(preview_kind_name(PreviewKind::Mixed), "F32/F16/BF16/IQ3_S"); + } + + fn legacy_staging_path(output: &Path) -> PathBuf { + output.with_file_name(format!( + "{}.parts-{}", + output.file_name().unwrap().to_string_lossy(), + std::process::id() + )) + } + #[test] fn streamed_prepare_parent_symlink_retarget_keeps_archive_and_provenance_together() { let directory = preview_test_path("stream-symlink-output", "dir"); -- 2.54.0 From ed4199464da4041a0fedebe3ea284f49c8cde69a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 02:26:10 +0200 Subject: [PATCH 39/58] test: cover overlay provenance validation paths --- control-plane/src/kar_overlay.rs | 4 +- control-plane/src/prepare_preview.rs | 151 +++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 3 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index 44a3ef62..d1d66809 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -530,9 +530,7 @@ pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result Vec { + let dtype = u8::from(mismatch == 3); + if dtype == 0 { + fixture + .values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect() + } else { + vec![0; fixture.values.len() * 2] + } + } + + fn mismatched_overlay_dimensions(source: &kar::TensorSource, mismatch: u8) -> Vec { + if mismatch == 2 { + vec![128, 2] + } else { + source.dimensions.clone() + } + } + + fn mismatched_overlay_tensor<'a>( + source: &kar::TensorSource, + raw: &'a [u8], + dimensions: &'a [u64], + mismatch: u8, + ) -> kar_writer::Tensor<'a> { + kar_writer::Tensor { + name: "dense", + dims: dimensions, + source_dtype: u8::from(mismatch == 3), + source_digest: if mismatch == 0 { + [0xa5; 32] + } else { + source.digest + }, + source_offset: source.offset + u64::from(mismatch == 1) * 4, + data: kar_writer::TensorData::Raw(raw), + } + } + + fn write_mismatched_overlay_with_base( + destination: &Path, + base: kar::Summary, + tensor: kar_writer::Tensor<'_>, + ) { + let identity = kar_writer::SourceIdentity { + name: "qwen35", + architecture: "qwen35", + builder: "test", + digest: base.source_digest, + total_elements: base.source_total_elements, + bytes: base.source_bytes, + }; + kar_writer::write_archive(destination, &identity, &[tensor]).unwrap(); + } + + fn write_mismatched_overlay_sidecar( + fixture: &OverlayFixture, + archive: &Path, + record: &kar::TensorSource, + ) { + let mut value = read_json(&fixture.overlay_sidecar()); + value["overlay_archive_sha256"] = + serde_json::json!(hex::encode(hash_file(archive).unwrap())); + value["records"][0]["f32_sha256"] = serde_json::json!(hex::encode(record.digest)); + value["records"][0]["derived_offset"] = serde_json::json!(record.offset); + value["records"][0]["section_bytes"] = serde_json::json!(record.section_bytes); + fs::write( + provenance_path(archive).unwrap(), + serde_json::to_vec(&value).unwrap(), + ) + .unwrap(); + } + #[test] fn resolver_rejects_malformed_base_sidecar() { let fixture = overlay_fixture(); -- 2.54.0 From 11f42fa03a58bb831be5b69b54e725aa39b0bd75 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 02:38:44 +0200 Subject: [PATCH 40/58] test: cover archive and seek error paths --- control-plane/src/kar_overlay.rs | 20 +++++- control-plane/src/prepare_preview.rs | 98 ++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 3 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index d1d66809..a9395b4c 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -519,11 +519,12 @@ pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result(&json).is_err(), + "{number}" + ); + } + } + struct TestDir(PathBuf); impl TestDir { diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index be1b5fb2..c9c1e4b6 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -3047,6 +3047,84 @@ mod tests { ); } + #[cfg(target_os = "linux")] + #[test] + fn nonseekable_sources_return_seek_errors_for_sharded_and_single_reads() { + assert_nonseekable_sharded_read_fails(&overlay_fixture()); + assert_nonseekable_single_read_fails(&overlay_fixture()); + } + + #[cfg(target_os = "linux")] + fn assert_nonseekable_sharded_read_fails(fixture: &OverlayFixture) { + let path = fixture.directory.join("nonseekable-shard.gguf"); + let raw = 1.25f32.to_le_bytes(); + fs::write(&path, one_shard("weight", 0, 1, &raw)).unwrap(); + let index = gguf::tensor_index(&path).unwrap(); + let tensor = &index.tensors[0]; + let identity = derived_mixed::ShardedIdentity { + derived_sha256: [0; 32], + derived_bytes: 4, + shards: Vec::new(), + tensors: vec![sharded_identity_for(tensor, &raw, &[1.25])], + }; + let pipe = fixture.directory.join("nonseekable-sharded.pipe"); + assert!(read_sharded_weights(&identity, &index, tensor, &mut open_fifo(&pipe), 0).is_err()); + fs::remove_file(pipe).unwrap(); + } + + #[cfg(target_os = "linux")] + fn assert_nonseekable_single_read_fails(fixture: &OverlayFixture) { + let path = fixture.directory.join("nonseekable-single.gguf"); + let bytes = two_tensor_f32_gguf(); + fs::write(&path, &bytes).unwrap(); + let index = gguf::tensor_index(&path).unwrap(); + let source = SingleSourcePrepare { + source_path: &path, + destination: Path::new("unused.kar"), + levels: 2, + kind: PreviewKind::F32, + }; + let identity = single_source_identity_for(&path, &index, &bytes); + let staging_path = fixture.directory.join("nonseekable-staging"); + fs::create_dir(&staging_path).unwrap(); + let staging = StagingDir(staging_path); + let request = SingleTensorRequest { + source: &source, + index: &index, + identity: &identity, + staging: &staging, + tensor: &index.tensors[0], + number: 0, + }; + let mut progress = SingleTensorProgress { + total_elements: 0, + maximum_relative_l2: 0.0, + prepared: Vec::new(), + }; + let pipe = fixture.directory.join("nonseekable-single.pipe"); + assert!(prepare_single_tensor(request, &mut open_fifo(&pipe), &mut progress).is_err()); + fs::remove_file(pipe).unwrap(); + } + + #[cfg(target_os = "linux")] + fn open_fifo(path: &Path) -> File { + use std::os::unix::ffi::OsStrExt; + + let name = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `name` is NUL-terminated and points to this test's private FIFO path. + assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); + let writer_path = path.to_path_buf(); + let writer = std::thread::spawn(move || { + fs::OpenOptions::new() + .write(true) + .open(writer_path) + .unwrap() + }); + let reader = File::open(path).unwrap(); + drop(writer.join().unwrap()); + reader + } + fn assert_bad_shard_counts(index: &gguf::TensorIndex, shard: &derived_mixed::ShardIdentity) { let wrong_count = derived_mixed::ShardIdentity { name: shard.name.clone(), @@ -5074,6 +5152,26 @@ mod tests { assert_overlay_record_source_mismatch(&overlay_fixture()); } + #[test] + fn resolver_rejects_archive_bytes_changed_after_provenance() { + let fixture = overlay_fixture(); + fixture.prepare().unwrap(); + assert_archive_hash_mismatch(&fixture.base, &fixture.overlay, &fixture.base); + assert_archive_hash_mismatch(&fixture.base, &fixture.overlay, &fixture.overlay); + } + + fn assert_archive_hash_mismatch(base: &Path, overlay: &Path, changed: &Path) { + let original = fs::read(changed).unwrap(); + let mut corrupt = original.clone(); + corrupt[0] ^= 1; + fs::write(changed, corrupt).unwrap(); + let error = crate::kar_overlay::resolve_verified(base, overlay) + .err() + .unwrap(); + assert!(error.contains("archive differs from its provenance")); + fs::write(changed, original).unwrap(); + } + fn assert_overlay_record_source_mismatch(fixture: &OverlayFixture) { fixture.prepare().unwrap(); for mismatch in 0..4 { -- 2.54.0 From 117910ef3b581a13583b38234d140ae6bcb137dd Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 03:00:02 +0200 Subject: [PATCH 41/58] test: cover strict KAR provenance rejection paths --- control-plane/src/kar_writer.rs | 37 +++- control-plane/src/prepare_preview.rs | 283 +++++++++++++++++++++++++-- 2 files changed, 307 insertions(+), 13 deletions(-) diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index a9d5b105..0af4a18d 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -288,7 +288,8 @@ fn validate_private_archive_parent(parent: &Path) -> Result<(), String> { let uid = unsafe { libc::geteuid() }; for directory in parent.ancestors().collect::>().into_iter().rev() { let metadata = fs::symlink_metadata(directory).map_err(|error| error.to_string())?; - if !metadata.file_type().is_dir() || (metadata.uid() != 0 && metadata.uid() != uid) { + // The caller passes a canonicalized parent, so every ancestor is a directory. + if !archive_parent_owner_allowed(metadata.uid(), uid) { return Err("KAR parent is not owned by the service or root".into()); } let mode = metadata.mode(); @@ -300,6 +301,11 @@ fn validate_private_archive_parent(parent: &Path) -> Result<(), String> { Ok(()) } +#[cfg(unix)] +fn archive_parent_owner_allowed(owner: u32, service: u32) -> bool { + owner == 0 || owner == service +} + fn private_archive_pair( temporary: &Path, destination: &Path, @@ -2434,6 +2440,35 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + #[test] + fn archive_parent_owner_policy_accepts_root_and_service_only() { + assert!(archive_parent_owner_allowed(0, 1000)); + assert!(archive_parent_owner_allowed(1000, 1000)); + assert!(!archive_parent_owner_allowed(65534, 1000)); + } + + #[cfg(unix)] + #[test] + fn published_temp_requires_the_destination_inode_and_two_links() { + let root = test_dir("published-temp-inode"); + let destination = root.join("archive.kar"); + let temporary = archive_temp_path(&destination, 0); + write_temp(&temporary); + fs::hard_link(&temporary, &destination).unwrap(); + let published = fs::symlink_metadata(&temporary).unwrap(); + assert!(is_published_temp(&published, &destination)); + let extra = root.join("extra.link"); + fs::hard_link(&temporary, &extra).unwrap(); + let multiply_linked = fs::symlink_metadata(&temporary).unwrap(); + assert!(!is_published_temp(&multiply_linked, &destination)); + fs::remove_file(extra).unwrap(); + fs::remove_file(&destination).unwrap(); + fs::write(&destination, b"different inode").unwrap(); + assert!(!is_published_temp(&published, &destination)); + fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] #[test] fn archive_temp_metadata_matching_fails_closed_on_metadata_errors() { diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index c9c1e4b6..22364a2c 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -3215,6 +3215,28 @@ mod tests { assert_oversized_single_source_rejected(&fixture.directory); } + #[test] + fn single_source_index_rejects_tensor_count_above_limit() { + let path = preview_test_path("too-many-tensors", "gguf"); + fs::write(&path, many_tensor_gguf(MAX_TENSORS + 1)).unwrap(); + let error = load_single_source_index(&path).unwrap_err(); + assert!(error.contains("tensor-count limit"), "{error}"); + fs::remove_file(path).unwrap(); + } + + fn many_tensor_gguf(count: usize) -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&(count as u64).to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + for number in 0..count { + append_f32_tensor_record(&mut bytes, &format!("tensor-{number}"), number as u64 * 128); + } + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.resize(bytes.len() + count * 128, 0); + bytes + } + #[test] fn zero_tensor_gguf_is_rejected_by_indexer_before_preview_validation() { let fixture = overlay_fixture(); @@ -4126,6 +4148,26 @@ mod tests { gguf } + fn one_shard_with_dimensions(name: &str, dimensions: &[u64], payload: &[u8]) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, name); + gguf.extend_from_slice(&(dimensions.len() as u32).to_le_bytes()); + for dimension in dimensions { + gguf.extend_from_slice(&dimension.to_le_bytes()); + } + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(payload); + gguf + } + struct OverlayFixture { directory: PathBuf, values: Vec, @@ -5160,6 +5202,161 @@ mod tests { assert_archive_hash_mismatch(&fixture.base, &fixture.overlay, &fixture.overlay); } + #[test] + fn resolver_rejects_overlay_source_digest_bytes_and_dtype_mismatches() { + assert_minimal_identity_pair_rejected(IdentityMismatch { + base_digest: [0x11; 32], + overlay_digest: [0x22; 32], + base_bytes: 16, + overlay_bytes: 16, + base_dtype: 0, + }); + assert_minimal_identity_pair_rejected(IdentityMismatch { + base_digest: [0x11; 32], + overlay_digest: [0x11; 32], + base_bytes: 16, + overlay_bytes: 20, + base_dtype: 0, + }); + assert_minimal_identity_pair_rejected(IdentityMismatch { + base_digest: [0x11; 32], + overlay_digest: [0x11; 32], + base_bytes: 16, + overlay_bytes: 16, + base_dtype: 1, + }); + } + + struct IdentityMismatch { + base_digest: [u8; 32], + overlay_digest: [u8; 32], + base_bytes: u64, + overlay_bytes: u64, + base_dtype: u8, + } + + struct IdentityPair { + root: PathBuf, + base: PathBuf, + overlay: PathBuf, + } + + fn assert_minimal_identity_pair_rejected(case: IdentityMismatch) { + let pair = write_minimal_identity_pair(case); + assert!(crate::kar_overlay::resolve_verified(&pair.base, &pair.overlay).is_err()); + fs::remove_dir_all(pair.root).unwrap(); + } + + fn write_minimal_identity_pair(case: IdentityMismatch) -> IdentityPair { + let root = preview_test_path("identity-mismatch", "dir"); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let base = root.join("base.kar"); + let overlay = root.join("overlay.kar"); + let payload = [1.0f32, 2.0, 3.0, 4.0] + .into_iter() + .flat_map(f32::to_le_bytes) + .collect::>(); + let tensor_digest = Sha256::digest(&payload).into(); + let base_identity = identity_source(case.base_digest, case.base_bytes, case.base_dtype); + let overlay_identity = identity_source(case.overlay_digest, case.overlay_bytes, 0); + write_identity_archive( + &base, + &base_identity, + case.base_dtype, + &payload, + tensor_digest, + ); + write_identity_archive(&overlay, &overlay_identity, 0, &payload, tensor_digest); + write_identity_sidecars( + &base, + &overlay, + case.base_digest, + case.base_bytes, + tensor_digest, + ); + IdentityPair { + root, + base, + overlay, + } + } + + fn identity_source( + digest: [u8; 32], + bytes: u64, + dtype: u8, + ) -> kar_writer::SourceIdentity<'static> { + kar_writer::SourceIdentity { + name: "test", + architecture: "test", + builder: "test", + digest, + total_elements: if dtype == 1 { 8 } else { 4 }, + bytes, + } + } + + fn write_identity_archive( + path: &Path, + identity: &kar_writer::SourceIdentity<'_>, + dtype: u8, + payload: &[u8], + tensor_digest: [u8; 32], + ) { + let dimensions = if dtype == 1 { &[8][..] } else { &[4][..] }; + let tensor = kar_writer::Tensor { + name: "weight", + dims: dimensions, + source_dtype: dtype, + source_digest: tensor_digest, + source_offset: 0, + data: kar_writer::TensorData::Raw(payload), + }; + kar_writer::write_archive(path, identity, &[tensor]).unwrap(); + } + + fn write_identity_sidecars( + base: &Path, + overlay: &Path, + source_digest: [u8; 32], + source_bytes: u64, + tensor_digest: [u8; 32], + ) { + let base_sidecar = serde_json::json!({ + "schema": "strata-next/sharded-stream-provenance-v4", + "archive_sha256": hex::encode(hash_file(base).unwrap()), + "derived_f32_sha256": hex::encode(source_digest), "derived_f32_bytes": source_bytes, + "shards": [], "partitioned_tensors": [], "tensors": [{ + "name": "weight", "source_kind": 0, "source_sha256": hex::encode(tensor_digest), + "derived_offset": 0, "derived_bytes": 16, "f32_sha256": hex::encode(tensor_digest) + }] + }); + fs::write( + provenance_path(base).unwrap(), + serde_json::to_vec(&base_sidecar).unwrap(), + ) + .unwrap(); + write_identity_overlay_sidecar(overlay, base, tensor_digest); + } + + fn write_identity_overlay_sidecar(overlay: &Path, base: &Path, tensor_digest: [u8; 32]) { + let (_, records) = kar::verify_with_sources(overlay).unwrap(); + let sidecar = serde_json::json!({ + "schema": "strata-next/kar-overlay-provenance-v1", + "base_archive_sha256": hex::encode(hash_file(base).unwrap()), + "overlay_archive_sha256": hex::encode(hash_file(overlay).unwrap()), "levels": 2, + "records": [{ "name": "weight", "derived_offset": 0, + "f32_sha256": hex::encode(tensor_digest), "section_bytes": records[0].section_bytes, + "relative_l2": 0.0 }] + }); + fs::write( + provenance_path(overlay).unwrap(), + serde_json::to_vec(&sidecar).unwrap(), + ) + .unwrap(); + } + fn assert_archive_hash_mismatch(base: &Path, overlay: &Path, changed: &Path) { let original = fs::read(changed).unwrap(); let mut corrupt = original.clone(); @@ -5388,7 +5585,10 @@ mod tests { .collect::>(); let iq3 = one_shard_with_arch("expert", 21, 256, &iq3_preview_block(), false); let files = [ - ("a-dense.gguf", one_shard("dense", 0, 512, &dense)), + ( + "a-dense.gguf", + one_shard_with_dimensions("dense", &[32, 16], &dense), + ), ("z-iq3.gguf", iq3), ] .into_iter() @@ -5455,7 +5655,8 @@ mod tests { "source_archive_sha256": base["archive_sha256"], "proposed_levels": 3, "records": parts.iter().map(|part| serde_json::json!({ - "name": part["name"], "elements": part["dimensions"][0] + "name": part["name"], "elements": part["dimensions"].as_array().unwrap() + .iter().map(|dimension| dimension.as_u64().unwrap()).product::() })).collect::>() }); fs::write(path, serde_json::to_vec(&policy).unwrap()).unwrap(); @@ -5469,26 +5670,59 @@ mod tests { let base_sidecar = provenance_path(base).unwrap(); let base_valid = read_json(&base_sidecar); let overlay_valid = read_json(overlay_sidecar); + assert_base_identity_rejections(base, overlay, &base_sidecar, &base_valid); + assert_partition_shape_rejections(base, overlay, &base_sidecar, &base_valid); + assert_overlay_record_rejections(base, overlay, overlay_sidecar, &overlay_valid); + write_json_value(&base_sidecar, &base_valid); + write_json_value(overlay_sidecar, &overlay_valid); + } + + fn assert_base_identity_rejections( + base: &Path, + overlay: &Path, + sidecar: &Path, + original: &serde_json::Value, + ) { assert_resolver_rejects_json_mutations( - &base_sidecar, + sidecar, base, overlay, - &base_valid, + original, &[ bad_base_schema, bad_base_source_digest_format, bad_base_digest, bad_base_source_digest, bad_base_source_bytes, + bad_base_record_offset, duplicate_base_record, + ], + ); + } + + fn assert_partition_shape_rejections( + base: &Path, + overlay: &Path, + sidecar: &Path, + original: &serde_json::Value, + ) { + assert_resolver_rejects_json_mutations( + sidecar, + base, + overlay, + original, + &[ duplicate_parent, missing_parent_dimensions, too_few_partition_parts, bad_part_shape, + bad_part_prefix, bad_part_offset, bad_part_digest_format, + bad_part_digest, duplicate_part, bad_parent_coverage, + bad_parent_dimensions, base_part_collision, missing_base_record, bad_base_record_digest, @@ -5496,11 +5730,19 @@ mod tests { partition_dimensions_mismatch, ], ); + } + + fn assert_overlay_record_rejections( + base: &Path, + overlay: &Path, + sidecar: &Path, + original: &serde_json::Value, + ) { assert_resolver_rejects_json_mutations( - overlay_sidecar, + sidecar, base, overlay, - &overlay_valid, + original, &[ bad_overlay_schema, bad_overlay_low_level, @@ -5516,8 +5758,6 @@ mod tests { negative_overlay_error, ], ); - write_json_value(&base_sidecar, &base_valid); - write_json_value(overlay_sidecar, &overlay_valid); } fn assert_resolver_rejects_json_mutations( @@ -5588,6 +5828,10 @@ mod tests { value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([128]); } + fn bad_part_prefix(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([31, 8]); + } + fn bad_part_offset(value: &mut serde_json::Value) { value["partitioned_tensors"][0]["parts"][1]["derived_offset"] = serde_json::json!(1); } @@ -5596,14 +5840,24 @@ mod tests { value["partitioned_tensors"][0]["parts"][0]["f32_sha256"] = serde_json::json!("bad"); } + fn bad_part_digest(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][0]["f32_sha256"] = + serde_json::json!("00".repeat(32)); + } + fn duplicate_part(value: &mut serde_json::Value) { let first = value["partitioned_tensors"][0]["parts"][0]["name"].clone(); value["partitioned_tensors"][0]["parts"][1]["name"] = first; } fn bad_parent_coverage(value: &mut serde_json::Value) { - value["partitioned_tensors"][0]["parts"][1]["dimensions"] = serde_json::json!([255]); - value["partitioned_tensors"][0]["parts"][1]["derived_bytes"] = serde_json::json!(255 * 4); + value["partitioned_tensors"][0]["parts"][1]["dimensions"] = serde_json::json!([32, 7]); + value["partitioned_tensors"][0]["parts"][1]["derived_bytes"] = + serde_json::json!(32 * 7 * 4); + } + + fn bad_parent_dimensions(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parent_dimensions"] = serde_json::json!([32, 15]); } fn base_part_collision(value: &mut serde_json::Value) { @@ -5623,10 +5877,15 @@ mod tests { value["tensors"][1]["f32_sha256"] = serde_json::json!("bad"); } + fn bad_base_record_offset(value: &mut serde_json::Value) { + let offset = value["tensors"][1]["derived_offset"].as_u64().unwrap(); + value["tensors"][1]["derived_offset"] = serde_json::json!(offset + 4); + } + fn partition_dimensions_mismatch(value: &mut serde_json::Value) { - value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([128]); + value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([32, 4]); value["partitioned_tensors"][0]["parts"][0]["derived_bytes"] = serde_json::json!(512); - value["partitioned_tensors"][0]["parts"][1]["dimensions"] = serde_json::json!([384]); + value["partitioned_tensors"][0]["parts"][1]["dimensions"] = serde_json::json!([32, 12]); value["partitioned_tensors"][0]["parts"][1]["derived_offset"] = serde_json::json!(512); value["partitioned_tensors"][0]["parts"][1]["derived_bytes"] = serde_json::json!(1536); } -- 2.54.0 From 1068d3a4d3cf3e18636d4a57d030bf7ed3a34895 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 03:11:32 +0200 Subject: [PATCH 42/58] test: cover remaining KAR validation branches --- control-plane/src/kar_writer.rs | 24 ++++++++++++++++++++ control-plane/src/prepare_preview.rs | 34 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 0af4a18d..05dfcfdc 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -2466,6 +2466,30 @@ mod tests { fs::remove_file(&destination).unwrap(); fs::write(&destination, b"different inode").unwrap(); assert!(!is_published_temp(&published, &destination)); + #[cfg(target_os = "linux")] + assert!(!same_inode( + &published, + &fs::metadata("/proc/self").unwrap() + )); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn private_archive_parent_rejects_a_foreign_owner() { + use std::os::unix::ffi::OsStrExt; + + if unsafe { libc::geteuid() } != 0 { + return; + } + let root = fs::canonicalize(test_dir("foreign-parent-owner")).unwrap(); + let path = std::ffi::CString::new(root.as_os_str().as_bytes()).unwrap(); + assert_eq!(unsafe { libc::chown(path.as_ptr(), 65534, 65534) }, 0); + assert!( + validate_private_archive_parent(&root) + .unwrap_err() + .contains("not owned by the service or root") + ); fs::remove_dir_all(root).unwrap(); } diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 22364a2c..4705628f 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -5695,6 +5695,7 @@ mod tests { bad_base_source_digest, bad_base_source_bytes, bad_base_record_offset, + bad_base_record_byte_count, duplicate_base_record, ], ); @@ -5717,11 +5718,13 @@ mod tests { too_few_partition_parts, bad_part_shape, bad_part_prefix, + bad_part_byte_product, bad_part_offset, bad_part_digest_format, bad_part_digest, duplicate_part, bad_parent_coverage, + bad_parent_last_dimension_coverage, bad_parent_dimensions, base_part_collision, missing_base_record, @@ -5856,6 +5859,28 @@ mod tests { serde_json::json!(32 * 7 * 4); } + fn bad_parent_last_dimension_coverage(value: &mut serde_json::Value) { + let parent_name = value["partitioned_tensors"][0]["parent_name"] + .as_str() + .unwrap() + .to_owned(); + let parent = value["tensors"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|record| record["name"] == parent_name) + .unwrap(); + let offset = parent["derived_offset"].as_u64().unwrap(); + parent["derived_bytes"] = serde_json::json!(0); + let tensor = &mut value["partitioned_tensors"][0]; + tensor["parent_dimensions"] = serde_json::json!([0, 16]); + tensor["parts"][0]["dimensions"] = serde_json::json!([0, 8]); + tensor["parts"][0]["derived_bytes"] = serde_json::json!(0); + tensor["parts"][1]["dimensions"] = serde_json::json!([0, 7]); + tensor["parts"][1]["derived_offset"] = serde_json::json!(offset); + tensor["parts"][1]["derived_bytes"] = serde_json::json!(0); + } + fn bad_parent_dimensions(value: &mut serde_json::Value) { value["partitioned_tensors"][0]["parent_dimensions"] = serde_json::json!([32, 15]); } @@ -5882,6 +5907,15 @@ mod tests { value["tensors"][1]["derived_offset"] = serde_json::json!(offset + 4); } + fn bad_base_record_byte_count(value: &mut serde_json::Value) { + let bytes = value["tensors"][1]["derived_bytes"].as_u64().unwrap(); + value["tensors"][1]["derived_bytes"] = serde_json::json!(bytes + 4); + } + + fn bad_part_byte_product(value: &mut serde_json::Value) { + value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([32, 7]); + } + fn partition_dimensions_mismatch(value: &mut serde_json::Value) { value["partitioned_tensors"][0]["parts"][0]["dimensions"] = serde_json::json!([32, 4]); value["partitioned_tensors"][0]["parts"][0]["derived_bytes"] = serde_json::json!(512); -- 2.54.0 From 4cb41467dd59860c4e1d701c593da4091a4602c3 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 03:23:47 +0200 Subject: [PATCH 43/58] Add raw LCOV function diagnostics --- scripts/check-changed-scope-coverage.py | 39 +++++++++++++++++++++++++ scripts/test-changed-scope-coverage.py | 27 +++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/scripts/check-changed-scope-coverage.py b/scripts/check-changed-scope-coverage.py index 5e674a10..016d52a7 100644 --- a/scripts/check-changed-scope-coverage.py +++ b/scripts/check-changed-scope-coverage.py @@ -420,6 +420,40 @@ def coverage_report(records: list[dict], scopes: dict[str, tuple[list[dict], set return {"baseline": BASELINE, "files": files, "totals": totals} +def raw_function_diagnostics(records: list[dict], scopes: dict[str, tuple[list[dict], set[int]]]) -> str: + """Render raw LCOV function rows for selected zero-hit entries without changing metrics.""" + by_path = _merge_lcov(records) + rows = ["Raw LCOV FN/FNDA diagnostics for selected zero-hit functions:"] + for path in RUST_FILES: + functions, test_lines = scopes[path] + source_records = by_path.get(path, []) + metrics = _file_metrics(source_records, functions, test_lines) + misses = {(item["line"], item["name"]) + for item in metrics["functions"]["misses"]} + if not misses: + continue + raw_fn = sorted({(line, name) for record in source_records for line, name in record["fn"] + if _inside(line, functions, test_lines)}) + raw_fnda = {} + for record in source_records: + for count, name in record["fnda"]: + raw_fnda.setdefault(name, []).append(count) + rows.append(f"{path}:") + for line, name in sorted(misses): + rows.append(f" zero-hit FN:{line},{name}") + enclosing = [item for item in functions if item["start"] <= line <= item["end"]] + related = [(fn_line, fn_name) for fn_line, fn_name in raw_fn + if any(item["start"] <= fn_line <= item["end"] for item in enclosing)] + for fn_line, fn_name in related: + counts = raw_fnda.get(fn_name, []) + raw_counts = ",".join(str(value) for value in counts) if counts else "" + rows.append(f" raw FN:{fn_line},{fn_name}") + rows.append(f" exact raw FNDA:{raw_counts},{fn_name}") + if len(rows) == 1: + return "" + return "\n".join(rows) + "\n" + + def _run(command: list[str], root: Path, env: dict | None = None) -> subprocess.CompletedProcess: return subprocess.run(command, cwd=root, env=env, text=True, capture_output=True, check=False) @@ -636,6 +670,11 @@ def run_coverage(root: Path, out: Path) -> int: state["failure"] = f"{type(error).__name__}: {error}" _write_summary(out, state) print((out / "summary.txt").read_text(), end="") + if "totals" in state: + diagnostics = raw_function_diagnostics(parse_lcov((out / "coverage.raw.lcov").read_text()), scopes) + if diagnostics: + (out / "function-diagnostics.txt").write_text(diagnostics) + print(diagnostics, end="") return 0 if state["passed"] else 1 diff --git a/scripts/test-changed-scope-coverage.py b/scripts/test-changed-scope-coverage.py index b98d0e9a..76f03821 100644 --- a/scripts/test-changed-scope-coverage.py +++ b/scripts/test-changed-scope-coverage.py @@ -100,6 +100,33 @@ pub fn with_test_only_block() { self.assertFalse(any("a.rs:4" in line for line in COVERAGE.summary_lines( {**report, "passed": True}))) + def test_raw_function_diagnostics_show_fn_and_exact_fnda_without_changing_metrics(self) -> None: + path = "control-plane/src/kar_writer.rs" + lcov = (f"SF:{path}\nFN:10,crate::write_section\nFNDA:1,crate::write_section\n" + "FN:12,crate::write_section::{closure#0}\n" + "FNDA:0,crate::write_section::{closure#0}\nDA:10,1\nDA:12,0\n" + "BRDA:12,0,0,0\nend_of_record\n") + records = [COVERAGE.parse_lcov(lcov)[0]] + records.extend(COVERAGE.parse_lcov(_lcov(other))[0] + for other in COVERAGE.RUST_FILES if other != path) + scopes = {name: ([], set()) for name in COVERAGE.RUST_FILES} + scopes[path] = ([{"name": "write_section", "start": 10, "end": 14}], set()) + before = COVERAGE.coverage_report(records, scopes) + diagnostics = COVERAGE.raw_function_diagnostics(records, scopes) + after = COVERAGE.coverage_report(records, scopes) + self.assertEqual(before, after) + self.assertIn("zero-hit FN:12,crate::write_section::{closure#0}", diagnostics) + self.assertIn("raw FN:12,crate::write_section::{closure#0}", diagnostics) + self.assertIn("exact raw FNDA:0,crate::write_section::{closure#0}", diagnostics) + self.assertNotIn("zero-hit FN:10,crate::write_section", diagnostics) + + def test_raw_function_diagnostics_are_empty_when_all_selected_functions_hit(self) -> None: + path = "control-plane/src/kar_writer.rs" + records = COVERAGE.parse_lcov(_lcov(path))[0:] + scopes = {name: ([], set()) for name in COVERAGE.RUST_FILES} + scopes[path] = ([{"name": "live", "start": 1, "end": 3}], set()) + self.assertEqual(COVERAGE.raw_function_diagnostics(records, scopes), "") + def test_cargo_json_selects_only_the_package_lib_test_executable(self) -> None: with tempfile.TemporaryDirectory() as directory: binary = Path(directory) / "strata_control-test" -- 2.54.0 From 3253c8fc36b7e8ef640397d28895d5e2efd886ee Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 03:49:04 +0200 Subject: [PATCH 44/58] test: cover STRA-8 I/O failure closures --- control-plane/src/kar_stream_encode.rs | 43 +++ control-plane/src/kar_writer.rs | 414 +++++++++++++++++++++++-- control-plane/src/prepare_preview.rs | 254 +++++++++++++-- 3 files changed, 649 insertions(+), 62 deletions(-) diff --git a/control-plane/src/kar_stream_encode.rs b/control-plane/src/kar_stream_encode.rs index 2cfbdf3c..0e3783c7 100644 --- a/control-plane/src/kar_stream_encode.rs +++ b/control-plane/src/kar_stream_encode.rs @@ -563,6 +563,49 @@ mod tests { assert!(!path.exists()); } + fn assert_slice_reader_destination_error(root: &Path, calibration: &kar_codec::Calibration) { + let path = root.join("slice-occupied.section"); + fs::write(&path, b"keep existing bytes").unwrap(); + let bytes = vec![0u8; 128]; + let mut source = Cursor::new(bytes.as_slice()); + let request = section_request(&path, calibration); + let result = encode_section_with_set_len(&mut source, &request, File::set_len); + assert!(result.is_err()); + assert_eq!(fs::read(path).unwrap(), b"keep existing bytes"); + } + + fn assert_slice_reader_set_len_error(root: &Path, calibration: &kar_codec::Calibration) { + let path = root.join("slice-cannot-size.section"); + let bytes = vec![0u8; 128]; + let mut source = Cursor::new(bytes.as_slice()); + let request = section_request(&path, calibration); + assert!(encode_section_with_set_len(&mut source, &request, reject_section_size).is_err()); + assert!(!path.exists()); + } + + fn section_request<'a>( + destination: &'a Path, + calibration: &'a kar_codec::Calibration, + ) -> SectionRequest<'a> { + SectionRequest { + absolute_offset: 0, + source_kind: 0, + source_bytes: 128, + elements: 32, + calibration, + destination, + } + } + + #[test] + fn borrowed_slice_reader_preserves_destination_and_cleans_sizing_failure() { + let root = test_dir("slice-reader-errors"); + let calibration = test_calibration(); + assert_slice_reader_destination_error(&root, &calibration); + assert_slice_reader_set_len_error(&root, &calibration); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn section_encoder_accepts_borrowed_and_file_readers() { let root = test_dir("reader-types"); diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 05dfcfdc..23337b82 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -286,8 +286,21 @@ pub(crate) fn canonical_archive_destination(destination: &Path) -> Result Result<(), String> { let uid = unsafe { libc::geteuid() }; + validate_private_archive_parent_with(parent, uid, archive_symlink_metadata) +} + +fn archive_symlink_metadata(path: &Path) -> io::Result { + fs::symlink_metadata(path) +} + +#[cfg(unix)] +fn validate_private_archive_parent_with( + parent: &Path, + uid: u32, + metadata: fn(&Path) -> io::Result, +) -> Result<(), String> { for directory in parent.ancestors().collect::>().into_iter().rev() { - let metadata = fs::symlink_metadata(directory).map_err(|error| error.to_string())?; + let metadata = metadata(directory).map_err(|error| error.to_string())?; // The caller passes a canonicalized parent, so every ancestor is a directory. if !archive_parent_owner_allowed(metadata.uid(), uid) { return Err("KAR parent is not owned by the service or root".into()); @@ -374,11 +387,23 @@ fn archive_temp_metadata_matches( } fn remove_archive_temp_locked(path: &Path, file: &File) -> Result<(), String> { + remove_archive_temp_locked_with(path, file, archive_remove_file) +} + +fn archive_remove_file(path: &Path) -> io::Result<()> { + fs::remove_file(path) +} + +fn remove_archive_temp_locked_with( + path: &Path, + file: &File, + remove: fn(&Path) -> io::Result<()>, +) -> Result<(), String> { let path = private_archive_destination(path)?; if !archive_temp_path_matches(&path, file) { return Ok(()); } - fs::remove_file(path).map_err(|error| error.to_string()) + remove(&path).map_err(|error| error.to_string()) } fn archive_temp_options() -> OpenOptions { @@ -397,16 +422,43 @@ fn archive_temp_path(destination: &Path, slot: u8) -> PathBuf { } fn reap_stale_archive_temps(destination: &Path) -> Result<(), String> { + reap_stale_archive_temps_with(destination, archive_read_dir) +} + +fn archive_read_dir(path: &Path) -> io::Result { + fs::read_dir(path) +} + +#[cfg(unix)] +fn reap_stale_archive_temps_with( + destination: &Path, + read_directory: fn(&Path) -> io::Result, +) -> Result<(), String> { let destination = private_archive_destination(destination)?; - #[cfg(unix)] - { - let parent = destination.parent().unwrap_or_else(|| Path::new(".")); - for entry in fs::read_dir(parent).map_err(|error| error.to_string())? { - reap_archive_temp_entry(&destination, entry.map_err(|error| error.to_string())?)?; - } + let parent = destination + .parent() + .expect("canonical archive destination always has a parent"); + let entries = read_directory(parent).map_err(|error| error.to_string())?; + reap_archive_temp_entries(&destination, entries) +} + +#[cfg(not(unix))] +fn reap_stale_archive_temps_with( + destination: &Path, + _read_directory: fn(&Path) -> io::Result, +) -> Result<(), String> { + let _ = private_archive_destination(destination)?; + Ok(()) +} + +#[cfg(unix)] +fn reap_archive_temp_entries( + destination: &Path, + entries: impl IntoIterator>, +) -> Result<(), String> { + for entry in entries { + reap_archive_temp_entry(destination, entry.map_err(|error| error.to_string())?)?; } - #[cfg(not(unix))] - let _ = &destination; Ok(()) } @@ -514,6 +566,7 @@ fn unlink_if_same_archive_temp( #[cfg(unix)] #[derive(Clone, Copy)] struct ArchiveTempPathOps { + opened_metadata: fn(&File) -> io::Result, metadata: fn(&Path) -> io::Result, remove: fn(&Path) -> io::Result<()>, } @@ -522,6 +575,7 @@ struct ArchiveTempPathOps { impl ArchiveTempPathOps { fn system() -> Self { Self { + opened_metadata: File::metadata, metadata: archive_temp_symlink_metadata, remove: archive_temp_remove_file, } @@ -547,7 +601,7 @@ fn unlink_if_same_archive_temp_with( operations: ArchiveTempPathOps, ) -> Result<(), String> { let (path, destination) = private_archive_pair(path, destination)?; - let opened = file.metadata().map_err(|error| error.to_string())?; + let opened = (operations.opened_metadata)(file).map_err(|error| error.to_string())?; let current = match (operations.metadata)(&path) { Ok(meta) => meta, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), @@ -1332,6 +1386,14 @@ fn verify_nested_spool( fn verify_nested_spool_reader( file: &mut R, plan: &NestedSectionPlan<'_>, +) -> Result { + verify_nested_spool_reader_with_seek(file, plan, Seek::seek) +} + +fn verify_nested_spool_reader_with_seek( + file: &mut R, + plan: &NestedSectionPlan<'_>, + seek: fn(&mut R, SeekFrom) -> io::Result, ) -> Result { validate_nested_file( file, @@ -1342,8 +1404,7 @@ fn verify_nested_spool_reader( levels: plan.levels, }, )?; - file.seek(SeekFrom::Start(0)) - .map_err(|error| error.to_string())?; + seek(file, SeekFrom::Start(0)).map_err(|error| error.to_string())?; let digest = hash_reader(file)?; Ok(SectionSummary { bytes: plan.layout.section_bytes, @@ -1765,6 +1826,15 @@ fn copy_nested_file_from( state: &mut SectionWriteState<'_>, request: NestedFileCopy<'_, '_, '_>, source: &mut R, +) -> Result<(), String> { + copy_nested_file_from_with_seek(state, request, source, Seek::seek) +} + +fn copy_nested_file_from_with_seek( + state: &mut SectionWriteState<'_>, + request: NestedFileCopy<'_, '_, '_>, + source: &mut R, + seek: fn(&mut R, SeekFrom) -> io::Result, ) -> Result<(), String> { validate_nested_file( source, @@ -1775,7 +1845,7 @@ fn copy_nested_file_from( levels: request.levels, }, )?; - seek_source_offset(source, request.offset).map_err(|error| error.to_string())?; + seek(source, SeekFrom::Start(request.offset)).map_err(|error| error.to_string())?; let actual = copy_region(state, source, request.bytes)?; if actual.as_slice() != request.digest { return Err(format!( @@ -1787,20 +1857,48 @@ fn copy_nested_file_from( } fn open_source_region(path: &Path, offset: u64, bytes: u64, label: &str) -> Result { - let mut source = File::open(path).map_err(|error| error.to_string())?; + open_source_region_with(path, offset, bytes, label, SourceRegionOps::system()) +} + +struct SourceRegionOps { + open: fn(&Path) -> io::Result, + metadata: fn(&File) -> io::Result, + seek: fn(&mut File, SeekFrom) -> io::Result, +} + +impl SourceRegionOps { + fn system() -> Self { + Self { + open: open_archive_source_file, + metadata: File::metadata, + seek: Seek::seek, + } + } +} + +fn open_archive_source_file(path: &Path) -> io::Result { + File::open(path) +} + +fn open_source_region_with( + path: &Path, + offset: u64, + bytes: u64, + label: &str, + operations: SourceRegionOps, +) -> Result { + let mut source = (operations.open)(path).map_err(|error| error.to_string())?; let end = offset.checked_add(bytes); - let source_len = source.metadata().map_err(|error| error.to_string())?.len(); + let source_len = (operations.metadata)(&source) + .map_err(|error| error.to_string())? + .len(); if end.is_none_or(|end| end > source_len) { return Err(format!("{label} source file is truncated")); } - seek_source_offset(&mut source, offset).map_err(|error| error.to_string())?; + (operations.seek)(&mut source, SeekFrom::Start(offset)).map_err(|error| error.to_string())?; Ok(source) } -fn seek_source_offset(source: &mut impl Seek, offset: u64) -> io::Result<()> { - source.seek(SeekFrom::Start(offset)).map(|_| ()) -} - fn copy_region( state: &mut SectionWriteState<'_>, source: &mut R, @@ -2000,16 +2098,23 @@ fn check_file_region( bytes: u64, rule: RegionRule, ) -> Result<(), String> { - source - .seek(SeekFrom::Start(offset)) - .map_err(|error| error.to_string())?; + check_file_region_with(source, offset, bytes, rule, Seek::seek, Read::read_exact) +} + +fn check_file_region_with( + source: &mut R, + offset: u64, + bytes: u64, + rule: RegionRule, + seek: fn(&mut R, SeekFrom) -> io::Result, + read_exact: fn(&mut R, &mut [u8]) -> io::Result<()>, +) -> Result<(), String> { + seek(source, SeekFrom::Start(offset)).map_err(|error| error.to_string())?; let mut remaining = bytes; let mut buffer = [0u8; 64 * 1024]; while remaining > 0 { let count = remaining.min(buffer.len() as u64) as usize; - source - .read_exact(&mut buffer[..count]) - .map_err(|error| error.to_string())?; + read_exact(source, &mut buffer[..count]).map_err(|error| error.to_string())?; validate_region_chunk(&buffer[..count], rule)?; remaining -= count as u64; } @@ -2226,6 +2331,8 @@ mod tests { inner: std::io::Cursor>, fail_seek_at: Option, seeks: usize, + fail_read_at: Option, + reads: usize, } impl FaultReadSeek { @@ -2234,12 +2341,18 @@ mod tests { inner: std::io::Cursor::new(bytes), fail_seek_at: None, seeks: 0, + fail_read_at: None, + reads: 0, } } } impl Read for FaultReadSeek { fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.reads += 1; + if self.fail_read_at == Some(self.reads) { + return Err(io::ErrorKind::Other.into()); + } self.inner.read(buffer) } } @@ -2440,6 +2553,14 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + #[test] + fn private_archive_parent_propagates_metadata_errors() { + let root = test_dir("private-parent-metadata-error"); + assert!(validate_private_archive_parent_with(&root, 0, denied_temp_metadata).is_err()); + fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] #[test] fn archive_parent_owner_policy_accepts_root_and_service_only() { @@ -2709,11 +2830,21 @@ mod tests { let root = test_dir("temp-unlink-io-errors"); let destination = root.join("archive.kar"); assert_temp_unlink_metadata_error(&destination); + assert_temp_unlink_opened_metadata_error(&destination); assert_temp_unlink_remove_error(&destination); + assert_locked_temp_remove_error(&destination); assert!(archive_temp_path(&destination, 0).exists()); fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + fn assert_locked_temp_remove_error(destination: &Path) { + let (path, file, _) = locked_archive_temp(destination); + assert!(remove_archive_temp_locked_with(&path, &file, denied_temp_remove).is_err()); + assert!(path.exists()); + drop(file); + } + #[cfg(unix)] fn locked_archive_temp(destination: &Path) -> (PathBuf, File, fs::Metadata) { let path = archive_temp_path(destination, 0); @@ -2738,6 +2869,7 @@ mod tests { &before, &file, ArchiveTempPathOps { + opened_metadata: File::metadata, metadata: denied_temp_metadata, remove: archive_temp_remove_file }, @@ -2747,6 +2879,21 @@ mod tests { drop(file); } + #[cfg(unix)] + fn assert_temp_unlink_opened_metadata_error(destination: &Path) { + let (path, file, before) = locked_archive_temp(destination); + let operations = ArchiveTempPathOps { + opened_metadata: denied_opened_metadata, + metadata: archive_temp_symlink_metadata, + remove: archive_temp_remove_file, + }; + assert!( + unlink_if_same_archive_temp_with(&path, destination, &before, &file, operations) + .is_err() + ); + drop(file); + } + #[cfg(unix)] fn assert_temp_unlink_remove_error(destination: &Path) { let (path, file, before) = locked_archive_temp(destination); @@ -2757,6 +2904,7 @@ mod tests { &before, &file, ArchiveTempPathOps { + opened_metadata: File::metadata, metadata: archive_temp_symlink_metadata, remove: denied_temp_remove }, @@ -2771,6 +2919,11 @@ mod tests { Err(io::ErrorKind::PermissionDenied.into()) } + #[cfg(unix)] + fn denied_opened_metadata(_: &File) -> io::Result { + Err(io::ErrorKind::PermissionDenied.into()) + } + #[cfg(unix)] fn denied_temp_remove(_: &Path) -> io::Result<()> { Err(io::ErrorKind::PermissionDenied.into()) @@ -3255,6 +3408,22 @@ mod tests { assert!(create_archive_temp(&missing).is_err()); } + #[cfg(unix)] + #[test] + fn stale_archive_reaper_reports_directory_and_entry_errors() { + let root = test_dir("stale-reaper-errors"); + let destination = root.join("archive.kar"); + assert!(reap_stale_archive_temps_with(&destination, denied_directory_read).is_err()); + let entries = std::iter::once(Err(io::ErrorKind::PermissionDenied.into())); + assert!(reap_archive_temp_entries(&destination, entries).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + fn denied_directory_read(_: &Path) -> io::Result { + Err(io::ErrorKind::PermissionDenied.into()) + } + #[test] fn source_region_and_hash_reader_fail_on_short_or_unreadable_inputs() { let root = test_dir("source-region-errors"); @@ -3267,6 +3436,53 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + #[test] + fn source_region_propagates_metadata_and_seek_errors() { + let root = test_dir("source-region-ops"); + let path = root.join("source.bin"); + fs::write(&path, [0u8; 4]).unwrap(); + assert!( + open_source_region_with( + &path, + 0, + 1, + "test", + SourceRegionOps { + metadata: denied_opened_metadata, + ..SourceRegionOps::system() + } + ) + .is_err() + ); + assert!( + open_source_region_with( + &path, + 0, + 1, + "test", + SourceRegionOps { + seek: reject_seek::, + ..SourceRegionOps::system() + } + ) + .is_err() + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn read_faults_propagate_through_hash_and_region_copy() { + let mut hashing = FaultReadSeek::new(vec![1]); + hashing.fail_read_at = Some(1); + assert!(hash_reader(&mut hashing).is_err()); + let mut source = FaultReadSeek::new(vec![1]); + source.fail_read_at = Some(1); + let mut output = FaultArchiveOutput::default(); + let mut state = SectionWriteState::new(&mut output); + assert!(copy_region(&mut state, &mut source, 1).is_err()); + } + #[test] fn oversized_section_padding_is_rejected() { let root = test_dir("padding-overflow"); @@ -3394,6 +3610,50 @@ mod tests { assert!(check_file_region(&mut source, 0, 0, RegionRule::ZeroPadding).is_err()); } + #[test] + fn file_backed_region_check_propagates_seek_and_read_errors() { + let root = test_dir("region-file-errors"); + let path = root.join("region.bin"); + fs::write(&path, [0u8; 4]).unwrap(); + assert_file_region_seek_error(&path); + assert_file_region_read_error(&path); + fs::remove_dir_all(root).unwrap(); + } + + fn assert_file_region_seek_error(path: &Path) { + let mut source = File::open(path).unwrap(); + assert!( + check_file_region_with( + &mut source, + 0, + 0, + RegionRule::ZeroPadding, + reject_seek::, + Read::read_exact + ) + .is_err() + ); + } + + fn assert_file_region_read_error(path: &Path) { + let mut source = File::open(path).unwrap(); + assert!( + check_file_region_with( + &mut source, + 0, + 1, + RegionRule::ZeroPadding, + Seek::seek, + reject_read:: + ) + .is_err() + ); + } + + fn reject_read(_: &mut R, _: &mut [u8]) -> io::Result<()> { + Err(io::ErrorKind::Other.into()) + } + #[test] fn nested_spool_and_copy_propagate_post_validation_seek_failures() { let input = reference_input(); @@ -3408,6 +3668,41 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[test] + fn file_backed_nested_readers_propagate_post_validation_seek_errors() { + let root = test_dir("nested-file-seek-errors"); + let input = reference_input(); + let tensors = reference_tensors(&input); + let plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + let spool = root.join("nested.spool"); + write_nested_section(&spool, &tensors[1]).unwrap(); + assert_file_spool_verify_seek_error(&spool, &plan); + assert_file_spool_copy_seek_error(&spool, &plan); + fs::remove_dir_all(root).unwrap(); + } + + fn assert_file_spool_verify_seek_error(path: &Path, plan: &NestedSectionPlan<'_>) { + let mut file = File::open(path).unwrap(); + assert!( + verify_nested_spool_reader_with_seek(&mut file, plan, reject_seek::).is_err() + ); + } + + fn assert_file_spool_copy_seek_error(path: &Path, plan: &NestedSectionPlan<'_>) { + let mut source = File::open(path).unwrap(); + let mut output = FaultArchiveOutput::default(); + let mut state = SectionWriteState::new(&mut output); + let request = nested_file_copy(path, plan, &[0; 32]); + assert!( + copy_nested_file_from_with_seek(&mut state, request, &mut source, reject_seek::) + .is_err() + ); + } + + fn reject_seek(_: &mut R, _: SeekFrom) -> io::Result { + Err(io::ErrorKind::Other.into()) + } + fn verify_nested_spool_seek_paths( bytes: &[u8], plan: &NestedSectionPlan<'_>, @@ -3624,14 +3919,16 @@ mod tests { let tensors = reference_tensors(&input); let mut plan = ArchivePlan::build(&source, &tensors).unwrap(); let root = test_dir("archive-plan-file-errors"); - for operation in [ - ArchiveOutputOperation::SetLength, - ArchiveOutputOperation::Length, - ArchiveOutputOperation::Seek, - ArchiveOutputOperation::Write, + for (operation, call) in [ + (ArchiveOutputOperation::SetLength, 1), + (ArchiveOutputOperation::Length, 1), + (ArchiveOutputOperation::Seek, 1), + (ArchiveOutputOperation::Seek, 2), + (ArchiveOutputOperation::Write, 1), + (ArchiveOutputOperation::Write, 2), ] { let mut output = File::create(root.join("archive.part")).unwrap(); - fail_archive_output_at(operation, 1); + fail_archive_output_at(operation, call); assert!(plan.write(&mut output, &source, &tensors, false).is_err()); } fs::remove_dir_all(root).unwrap(); @@ -3740,6 +4037,33 @@ mod tests { assert_eq!(output.archive_len().unwrap(), plan.layout.section_bytes); } + #[test] + fn file_backed_nested_spool_cleans_length_and_sync_failures() { + let root = test_dir("nested-spool-file-errors"); + let input = reference_input(); + let tensors = reference_tensors(&input); + let plan = NestedSectionPlan::new(&tensors[1]).unwrap(); + for (name, operation) in [ + ("length", ArchiveOutputOperation::Length), + ("sync", ArchiveOutputOperation::Sync), + ] { + assert_file_nested_spool_failure(&root, name, operation, &plan); + } + fs::remove_dir_all(root).unwrap(); + } + + fn assert_file_nested_spool_failure( + root: &Path, + name: &str, + operation: ArchiveOutputOperation, + plan: &NestedSectionPlan<'_>, + ) { + let path = root.join(format!("{name}.spool")); + fail_archive_output_at(operation, 1); + assert!(write_nested_spool(&path, plan).is_err()); + assert!(!path.exists()); + } + #[test] fn payload_writer_propagates_archive_length_metadata_error() { let input = reference_input(); @@ -4036,6 +4360,30 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + #[test] + fn archive_temp_name_parser_handles_non_utf8_and_invalid_destination() { + use std::os::unix::ffi::OsStrExt; + + let destination = Path::new("/"); + assert!(archive_temp_path(destination, 0).file_name().is_some()); + assert!(!is_archive_temp_name( + destination, + std::ffi::OsStr::new("other") + )); + assert!(!is_archive_temp_name( + destination, + std::ffi::OsStr::from_bytes(&[0xff]) + )); + } + + #[test] + fn archive_temp_removal_reports_a_missing_staging_file() { + let root = test_dir("remove-missing-temp"); + assert!(remove_archive_temp(&root.join("missing.part")).is_err()); + fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] #[test] fn failed_writer_cleanup_holds_lock_across_reaper_and_slot_reuse() { diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 4705628f..114ff3aa 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -437,11 +437,23 @@ fn prepare_shard_tensors( fn prepare_one_shard( request: ShardedShardRequest<'_>, state: &mut ShardedPrepareState, +) -> Result<(), String> { + prepare_one_shard_with_open(request, state, open_shard_file) +} + +fn open_shard_file(path: &Path) -> std::io::Result { + File::open(path) +} + +fn prepare_one_shard_with_open( + request: ShardedShardRequest<'_>, + state: &mut ShardedPrepareState, + open: fn(&Path) -> std::io::Result, ) -> Result<(), String> { let path = request.source_dir.join(&request.shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; check_shard_index(&index, request.shard, &mut state.architecture)?; - let mut source = File::open(&path).map_err(|error| error.to_string())?; + let mut source = open(&path).map_err(|error| error.to_string())?; prepare_shard_records(&request, &index, &mut source, state)?; verify_prepared_shard(&path, request.shard, &source) } @@ -596,9 +608,17 @@ fn verify_prepared_shard( shard: &derived_mixed::ShardIdentity, source: &File, ) -> Result<(), String> { - if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes - || hash_file(path)? != shard.gguf_sha256 - { + verify_shard_file_metadata(path, shard, source, File::metadata) +} + +fn verify_shard_file_metadata( + path: &Path, + shard: &derived_mixed::ShardIdentity, + source: &File, + metadata: fn(&File) -> std::io::Result, +) -> Result<(), String> { + let length = metadata(source).map_err(|error| error.to_string())?.len(); + if length != shard.gguf_bytes || hash_file(path)? != shard.gguf_sha256 { return Err(format!( "{}: GGUF shard changed during preparation", shard.name @@ -1020,7 +1040,7 @@ impl<'a> StreamPreparation<'a> { } fn prepare_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> { - self.prepare_shard_with_open(shard, |path| File::open(path)) + self.prepare_shard_with_open(shard, open_shard_file) } fn prepare_shard_with_open( @@ -1138,15 +1158,7 @@ impl<'a> StreamPreparation<'a> { path: &Path, source: &File, ) -> Result<(), String> { - if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes - || hash_file(path)? != shard.gguf_sha256 - { - return Err(format!( - "{}: GGUF shard changed during preparation", - shard.name - )); - } - Ok(()) + verify_shard_file_metadata(path, shard, source, File::metadata) } fn publish(self) -> Result { @@ -1408,6 +1420,7 @@ fn streamed_builder(request: &StreamPrepareRequest<'_>) -> String { } } +#[derive(Clone, Copy)] struct RawF32Spool<'a> { absolute: u64, source_kind: u32, @@ -1432,25 +1445,32 @@ fn spool_raw_f32_with_sync( .create_new(true) .open(request.path) .map_err(|error| error.to_string())?; - let result = (|| { - let mut writer = BufWriter::new(file); - let digests = write_raw_f32_chunks( - reader, - request.absolute, - request.source_kind, - request.source_bytes, - &mut writer, - )?; - writer.flush().map_err(|error| error.to_string())?; - sync(writer.get_ref()).map_err(|error| error.to_string())?; - Ok(digests) - })(); + let mut writer = BufWriter::new(file); + let result = write_raw_f32_spool(reader, request, &mut writer, sync); if result.is_err() { let _ = fs::remove_file(request.path); } result } +fn write_raw_f32_spool( + reader: &mut R, + request: RawF32Spool<'_>, + writer: &mut BufWriter, + sync: fn(&File) -> std::io::Result<()>, +) -> Result<([u8; 32], [u8; 32], u64), String> { + let digests = write_raw_f32_chunks( + reader, + request.absolute, + request.source_kind, + request.source_bytes, + writer, + )?; + writer.flush().map_err(|error| error.to_string())?; + sync(writer.get_ref()).map_err(|error| error.to_string())?; + Ok(digests) +} + fn write_raw_f32_chunks( reader: &mut R, absolute: u64, @@ -1753,9 +1773,18 @@ fn verify_single_source_unchanged( request: &SingleSourcePrepare<'_>, index: &gguf::TensorIndex, identity: &SingleSourceIdentity, +) -> Result<(), String> { + verify_single_source_with_metadata(request, index, identity, File::metadata) +} + +fn verify_single_source_with_metadata( + request: &SingleSourcePrepare<'_>, + index: &gguf::TensorIndex, + identity: &SingleSourceIdentity, + metadata: fn(&File) -> std::io::Result, ) -> Result<(), String> { let source = File::open(request.source_path).map_err(|error| error.to_string())?; - if source.metadata().map_err(|error| error.to_string())?.len() != index.summary.file_size + if metadata(&source).map_err(|error| error.to_string())?.len() != index.summary.file_size || hash_file(request.source_path)? != identity.original_digest { return Err("GGUF source changed during F32 preparation".into()); @@ -2473,9 +2502,17 @@ fn write_provenance_contents_with_sync( fn write_provenance_json( writer: &mut W, value: &serde_json::Value, +) -> Result<(), String> { + write_provenance_json_with_newline(writer, value, Write::write_all) +} + +fn write_provenance_json_with_newline( + writer: &mut W, + value: &serde_json::Value, + write_newline: fn(&mut W, &[u8]) -> std::io::Result<()>, ) -> Result<(), String> { serde_json::to_writer_pretty(&mut *writer, value).map_err(|error| error.to_string())?; - writer.write_all(b"\n").map_err(|error| error.to_string()) + write_newline(writer, b"\n").map_err(|error| error.to_string()) } fn hash_file(path: &Path) -> Result<[u8; 32], String> { @@ -2956,6 +2993,30 @@ mod tests { assert_changed_size_source_rejected(&request, &index, &identity); } + #[test] + fn single_source_preparation_and_recheck_report_missing_source() { + let fixture = overlay_fixture(); + let existing = fixture.directory.join("indexed-source.gguf"); + let bytes = two_tensor_f32_gguf(); + fs::write(&existing, &bytes).unwrap(); + let index = gguf::tensor_index(&existing).unwrap(); + let identity = single_source_identity_for(&existing, &index, &bytes); + let missing = fixture.directory.join("missing-source.gguf"); + let request = single_source_request(&missing); + let staging = StagingDir(PathBuf::new()); + assert!(prepare_single_source_tensors(&request, &index, &identity, &staging).is_err()); + assert!(verify_single_source_unchanged(&request, &index, &identity).is_err()); + } + + fn single_source_request(source_path: &Path) -> SingleSourcePrepare<'_> { + SingleSourcePrepare { + source_path, + destination: Path::new("unused.kar"), + levels: 2, + kind: PreviewKind::F32, + } + } + #[test] fn single_tensor_read_rejects_source_truncated_after_indexing() { let fixture = overlay_fixture(); @@ -2994,6 +3055,49 @@ mod tests { assert!(verify_prepared_shard(&path, &shard, &source).is_err()); } + #[test] + fn shard_verification_propagates_source_metadata_error() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("metadata-error.gguf"); + fs::write(&path, b"valid indexed bytes").unwrap(); + let source = File::open(&path).unwrap(); + let shard = derived_mixed::ShardIdentity { + name: "metadata-error.gguf".into(), + gguf_sha256: hash_file(&path).unwrap(), + gguf_bytes: fs::metadata(&path).unwrap().len(), + tensor_count: 1, + }; + assert!(verify_shard_file_metadata(&path, &shard, &source, reject_file_metadata).is_err()); + } + + #[test] + fn single_source_recheck_propagates_metadata_error() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("source-metadata-error.gguf"); + fs::write(&path, b"source").unwrap(); + let request = single_source_request(&path); + let identity = SingleSourceIdentity { + architecture: "fixture".into(), + source_name: "source.gguf".into(), + original_digest: [0; 32], + source_bytes: 6, + derived: None, + }; + assert!( + verify_single_source_with_metadata( + &request, + &empty_tensor_index(), + &identity, + reject_file_metadata + ) + .is_err() + ); + } + + fn reject_file_metadata(_: &File) -> std::io::Result { + Err(std::io::ErrorKind::PermissionDenied.into()) + } + #[test] fn shard_index_rejects_architecture_count_and_size_drift() { let fixture = overlay_fixture(); @@ -3215,6 +3319,14 @@ mod tests { assert_oversized_single_source_rejected(&fixture.directory); } + #[test] + fn single_source_index_reports_malformed_gguf() { + let path = preview_test_path("malformed-index", "gguf"); + fs::write(&path, b"not a GGUF").unwrap(); + assert!(load_single_source_index(&path).is_err()); + fs::remove_file(path).unwrap(); + } + #[test] fn single_source_index_rejects_tensor_count_above_limit() { let path = preview_test_path("too-many-tensors", "gguf"); @@ -3439,6 +3551,39 @@ mod tests { assert!(result.is_err()); } + #[cfg(unix)] + #[test] + fn file_backed_raw_spool_reports_write_and_flush_errors() { + assert_raw_file_write_error(); + assert_raw_file_flush_error(); + } + + #[cfg(unix)] + fn assert_raw_file_write_error() { + let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::with_capacity(0, file); + let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes()); + assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err()); + } + + #[cfg(unix)] + fn assert_raw_file_flush_error() { + let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::new(file); + let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes()); + let request = RawF32Spool { + absolute: 0, + source_kind: 0, + source_bytes: 4, + path: Path::new("unused.raw"), + }; + assert!(write_raw_f32_spool(&mut reader, request, &mut writer, File::sync_all).is_err()); + } + fn reject_spool_sync(_: &File) -> std::io::Result<()> { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) } @@ -3944,6 +4089,24 @@ mod tests { assert_post_index_open_error(&mut preparation, &shard); } + #[test] + fn legacy_shard_preparation_returns_source_open_error_after_indexing() { + let fixture = overlay_fixture(); + let identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + let shard = &identity.shards[0]; + let staging = StagingDir::create(&fixture.directory.join("legacy-open-error.kar")).unwrap(); + let request = ShardedShardRequest { + identity: &identity, + shard, + source_dir: &fixture.directory, + staging: &staging, + levels: 2, + }; + let mut state = ShardedPrepareState::new(identity.tensors.len()); + assert!(prepare_one_shard_with_open(request, &mut state, reject_source_open).is_err()); + } + fn assert_post_index_open_error( preparation: &mut StreamPreparation<'_>, shard: &derived_mixed::ShardIdentity, @@ -3957,6 +4120,10 @@ mod tests { ); } + fn reject_source_open(_: &Path) -> std::io::Result { + Err(std::io::ErrorKind::PermissionDenied.into()) + } + #[test] fn streamed_staging_refuses_existing_directory_and_root_destination() { let fixture = overlay_fixture(); @@ -4024,6 +4191,35 @@ mod tests { assert!(write_provenance_json(&mut LimitedProvenanceWriter(size), &value).is_err()); } + #[test] + fn file_backed_provenance_writer_reports_json_and_newline_errors() { + let value = serde_json::json!({"source":"fixture"}); + assert_file_provenance_newline_error(&value); + assert_file_provenance_json_error(&value); + } + + fn assert_file_provenance_newline_error(value: &serde_json::Value) { + let root = overlay_fixture(); + let path = root.directory.join("newline-error.json"); + let mut file = File::create(&path).unwrap(); + assert!( + write_provenance_json_with_newline(&mut file, value, reject_newline::).is_err() + ); + assert!(!fs::read(path).unwrap().ends_with(b"\n")); + } + + fn reject_newline(_: &mut W, _: &[u8]) -> std::io::Result<()> { + Err(std::io::ErrorKind::PermissionDenied.into()) + } + + #[cfg(unix)] + fn assert_file_provenance_json_error(value: &serde_json::Value) { + let Ok(mut file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + assert!(write_provenance_json(&mut file, value).is_err()); + } + fn reject_provenance_sync(_: &File) -> std::io::Result<()> { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) } -- 2.54.0 From afc6c62f8f8032d65e2345a3616ff635d5c73f8a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 04:03:52 +0200 Subject: [PATCH 45/58] test: cover remaining STRA-8 error monomorphs --- control-plane/src/kar_writer.rs | 34 +++++++-- control-plane/src/prepare_preview.rs | 110 +++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 5 deletions(-) diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 23337b82..7ab51d9d 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -438,8 +438,8 @@ fn reap_stale_archive_temps_with( let parent = destination .parent() .expect("canonical archive destination always has a parent"); - let entries = read_directory(parent).map_err(|error| error.to_string())?; - reap_archive_temp_entries(&destination, entries) + let mut entries = read_directory(parent).map_err(|error| error.to_string())?; + reap_archive_temp_entries(&destination, &mut entries) } #[cfg(not(unix))] @@ -454,7 +454,7 @@ fn reap_stale_archive_temps_with( #[cfg(unix)] fn reap_archive_temp_entries( destination: &Path, - entries: impl IntoIterator>, + entries: &mut dyn Iterator>, ) -> Result<(), String> { for entry in entries { reap_archive_temp_entry(destination, entry.map_err(|error| error.to_string())?)?; @@ -3414,8 +3414,8 @@ mod tests { let root = test_dir("stale-reaper-errors"); let destination = root.join("archive.kar"); assert!(reap_stale_archive_temps_with(&destination, denied_directory_read).is_err()); - let entries = std::iter::once(Err(io::ErrorKind::PermissionDenied.into())); - assert!(reap_archive_temp_entries(&destination, entries).is_err()); + let mut entries = std::iter::once(Err(io::ErrorKind::PermissionDenied.into())); + assert!(reap_archive_temp_entries(&destination, &mut entries).is_err()); fs::remove_dir_all(root).unwrap(); } @@ -3608,6 +3608,19 @@ mod tests { let mut source = FaultReadSeek::new(Vec::new()); source.fail_seek_at = Some(1); assert!(check_file_region(&mut source, 0, 0, RegionRule::ZeroPadding).is_err()); + source.fail_seek_at = None; + source.fail_read_at = Some(1); + assert!( + check_file_region_with( + &mut source, + 0, + 1, + RegionRule::ZeroPadding, + Seek::seek, + Read::read_exact + ) + .is_err() + ); } #[test] @@ -4228,6 +4241,17 @@ mod tests { verify_reap_fixture(make_reap_fixture()); } + #[cfg(unix)] + #[test] + fn stale_archive_reaper_returns_directory_entry_errors() { + let root = test_dir("reaper-entry-error"); + let destination = root.join("archive.kar"); + let mut entries = std::iter::once(Err(io::ErrorKind::PermissionDenied.into())); + assert!(reap_archive_temp_entries(&destination, &mut entries).is_err()); + assert!(!destination.exists()); + fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] #[test] fn reaper_preserves_replaced_paths_and_unpublished_hard_links() { diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 114ff3aa..506b0c4e 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -3558,6 +3558,51 @@ mod tests { assert_raw_file_flush_error(); } + #[test] + fn raw_spool_writer_preserves_file_and_cursor_source_bytes() { + let fixture = overlay_fixture(); + let bytes = 2.5f32.to_le_bytes(); + let source_path = fixture.directory.join("raw-spool-source.bin"); + fs::write(&source_path, bytes).unwrap(); + assert_file_raw_spool_matches(&source_path, &fixture.directory.join("file.raw"), &bytes); + assert_cursor_raw_spool_matches(&bytes, &fixture.directory.join("cursor.raw")); + } + + fn assert_file_raw_spool_matches(source: &Path, output: &Path, bytes: &[u8; 4]) { + let mut reader = File::open(source).unwrap(); + let request = raw_spool_request(output); + let result = spool_raw_f32(&mut reader, request).unwrap(); + assert_raw_spool_result(output, bytes, result); + } + + fn assert_cursor_raw_spool_matches(bytes: &[u8; 4], output: &Path) { + let mut reader = std::io::Cursor::new(bytes.to_vec()); + let result = spool_raw_f32(&mut reader, raw_spool_request(output)).unwrap(); + assert_raw_spool_result(output, bytes, result); + } + + fn raw_spool_request(path: &Path) -> RawF32Spool<'_> { + RawF32Spool { + absolute: 0, + source_kind: 0, + source_bytes: 4, + path, + } + } + + fn assert_raw_spool_result( + path: &Path, + source: &[u8; 4], + (source_digest, derived_digest, bytes): ([u8; 32], [u8; 32], u64), + ) { + assert_eq!(fs::read(path).unwrap(), source); + let expected_digest: [u8; 32] = Sha256::digest(source).into(); + assert_eq!(source_digest, expected_digest); + assert_eq!(derived_digest, expected_digest); + assert_eq!(bytes, 4); + fs::remove_file(path).unwrap(); + } + #[cfg(unix)] fn assert_raw_file_write_error() { let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { @@ -3566,6 +3611,20 @@ mod tests { let mut writer = BufWriter::with_capacity(0, file); let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes()); assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err()); + assert_file_reader_full_device_write_error(); + } + + #[cfg(unix)] + fn assert_file_reader_full_device_write_error() { + let fixture = overlay_fixture(); + let source_path = fixture.directory.join("full-device-source.bin"); + fs::write(&source_path, 2.5f32.to_le_bytes()).unwrap(); + let mut reader = File::open(source_path).unwrap(); + let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::with_capacity(0, file); + assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err()); } #[cfg(unix)] @@ -4107,6 +4166,57 @@ mod tests { assert!(prepare_one_shard_with_open(request, &mut state, reject_source_open).is_err()); } + #[test] + fn legacy_shard_preparation_reports_malformed_index() { + let fixture = overlay_fixture(); + let identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + let shard = &identity.shards[0]; + let staging = StagingDir::create(&fixture.directory.join("malformed-legacy.kar")).unwrap(); + fs::write(fixture.directory.join(&shard.name), b"malformed GGUF").unwrap(); + let request = malformed_shard_request(&fixture, &identity, shard, &staging); + let mut state = ShardedPrepareState::new(identity.tensors.len()); + let error = prepare_one_shard_with_open(request, &mut state, open_shard_file).unwrap_err(); + assert!(!error.is_empty()); + } + + #[test] + fn streamed_shard_preparation_reports_malformed_index() { + let fixture = overlay_fixture(); + let identity = + derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap(); + let parts = stream_parts::plan_shards(&identity, &fixture.directory).unwrap(); + let shard = shard_identity(&identity.shards[0]); + let archive = fixture.directory.join("malformed-index.kar"); + let request = shard_prepare_request(&fixture.manifest, &fixture.directory, &archive); + let mut preparation = StreamPreparation::new( + request, + identity, + parts, + StagingDir::create(&archive).unwrap(), + ); + fs::write(fixture.directory.join(&shard.name), b"malformed GGUF").unwrap(); + let error = preparation + .prepare_shard_with_open(&shard, open_shard_file) + .unwrap_err(); + assert!(!error.is_empty()); + } + + fn malformed_shard_request<'a>( + fixture: &'a OverlayFixture, + identity: &'a derived_mixed::ShardedIdentity, + shard: &'a derived_mixed::ShardIdentity, + staging: &'a StagingDir, + ) -> ShardedShardRequest<'a> { + ShardedShardRequest { + identity, + shard, + source_dir: &fixture.directory, + staging, + levels: 2, + } + } + fn assert_post_index_open_error( preparation: &mut StreamPreparation<'_>, shard: &derived_mixed::ShardIdentity, -- 2.54.0 From ed7f9fc473d2fed313e8f9dea3ab67f686b2f4dc Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 04:15:17 +0200 Subject: [PATCH 46/58] test(kar): cover raw spool I/O failures --- control-plane/src/prepare_preview.rs | 69 ++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 506b0c4e..ed31481e 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -3508,6 +3508,16 @@ mod tests { assert_raw_spool_preserves_existing(&mut source, &fixture.directory.join("owned.raw")); } + #[test] + fn cursor_spool_creation_conflict_preserves_existing_output() { + let fixture = overlay_fixture(); + let path = fixture.directory.join("cursor-owned.raw"); + fs::write(&path, b"existing bytes").unwrap(); + let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes().to_vec()); + assert!(spool_raw_f32(&mut reader, raw_spool_request(&path)).is_err()); + assert_eq!(fs::read(path).unwrap(), b"existing bytes"); + } + fn assert_unsupported_raw_spool_removes_partial(source: &mut File, path: &Path) { let request = RawF32Spool { absolute: 0, @@ -3556,6 +3566,8 @@ mod tests { fn file_backed_raw_spool_reports_write_and_flush_errors() { assert_raw_file_write_error(); assert_raw_file_flush_error(); + assert_cursor_vec_full_device_write_error(); + assert_file_and_cursor_vec_flush_errors(); } #[test] @@ -3614,6 +3626,16 @@ mod tests { assert_file_reader_full_device_write_error(); } + #[cfg(unix)] + fn assert_cursor_vec_full_device_write_error() { + let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::with_capacity(0, file); + let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes().to_vec()); + assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err()); + } + #[cfg(unix)] fn assert_file_reader_full_device_write_error() { let fixture = overlay_fixture(); @@ -3643,6 +3665,27 @@ mod tests { assert!(write_raw_f32_spool(&mut reader, request, &mut writer, File::sync_all).is_err()); } + #[cfg(unix)] + fn assert_file_and_cursor_vec_flush_errors() { + let fixture = overlay_fixture(); + let source_path = fixture.directory.join("flush-source.bin"); + fs::write(&source_path, 2.5f32.to_le_bytes()).unwrap(); + let mut file_reader = File::open(source_path).unwrap(); + assert_raw_spool_flush_error(&mut file_reader); + let mut cursor_reader = std::io::Cursor::new(2.5f32.to_le_bytes().to_vec()); + assert_raw_spool_flush_error(&mut cursor_reader); + } + + #[cfg(unix)] + fn assert_raw_spool_flush_error(reader: &mut R) { + let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::new(file); + let request = raw_spool_request(Path::new("unused.raw")); + assert!(write_raw_f32_spool(reader, request, &mut writer, File::sync_all).is_err()); + } + fn reject_spool_sync(_: &File) -> std::io::Result<()> { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) } @@ -3668,6 +3711,32 @@ mod tests { assert!(!path.exists()); } + #[test] + fn raw_spool_sync_failure_propagates_for_borrowed_and_owned_cursors() { + let fixture = overlay_fixture(); + let bytes = 2.5f32.to_le_bytes(); + let mut borrowed = std::io::Cursor::new(bytes.as_slice()); + assert_cursor_spool_sync_error(&mut borrowed, &fixture.directory.join("borrowed.raw")); + let mut owned = std::io::Cursor::new(bytes.to_vec()); + assert_cursor_spool_sync_error(&mut owned, &fixture.directory.join("owned.raw")); + } + + fn assert_cursor_spool_sync_error(reader: &mut R, path: &Path) { + let file = File::create(path).unwrap(); + let mut writer = BufWriter::new(file); + assert!( + write_raw_f32_spool( + reader, + raw_spool_request(path), + &mut writer, + reject_spool_sync + ) + .is_err() + ); + assert!(path.exists()); + fs::remove_file(path).unwrap(); + } + #[test] fn streamed_preparation_detects_identity_tensor_count_changed_before_run() { let fixture = overlay_fixture(); -- 2.54.0 From 7f4e40d103b71d1c7622ff5f2f2890080b0292f7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 04:25:57 +0200 Subject: [PATCH 47/58] test(kar): cover borrowed spool I/O closures --- control-plane/src/prepare_preview.rs | 33 +++++++++++++++++++++------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index ed31481e..5f9528fc 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -3634,6 +3634,18 @@ mod tests { let mut writer = BufWriter::with_capacity(0, file); let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes().to_vec()); assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err()); + assert_borrowed_cursor_full_device_write_error(); + } + + #[cfg(unix)] + fn assert_borrowed_cursor_full_device_write_error() { + let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else { + return; + }; + let mut writer = BufWriter::with_capacity(0, file); + let bytes = 2.5f32.to_le_bytes(); + let mut reader = std::io::Cursor::new(bytes.as_slice()); + assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err()); } #[cfg(unix)] @@ -3674,6 +3686,9 @@ mod tests { assert_raw_spool_flush_error(&mut file_reader); let mut cursor_reader = std::io::Cursor::new(2.5f32.to_le_bytes().to_vec()); assert_raw_spool_flush_error(&mut cursor_reader); + let bytes = 2.5f32.to_le_bytes(); + let mut borrowed_cursor = std::io::Cursor::new(bytes.as_slice()); + assert_raw_spool_flush_error(&mut borrowed_cursor); } #[cfg(unix)] @@ -3724,14 +3739,16 @@ mod tests { fn assert_cursor_spool_sync_error(reader: &mut R, path: &Path) { let file = File::create(path).unwrap(); let mut writer = BufWriter::new(file); - assert!( - write_raw_f32_spool( - reader, - raw_spool_request(path), - &mut writer, - reject_spool_sync - ) - .is_err() + let error = write_raw_f32_spool( + reader, + raw_spool_request(path), + &mut writer, + reject_spool_sync, + ) + .unwrap_err(); + assert_eq!( + error, + std::io::Error::from(std::io::ErrorKind::PermissionDenied).to_string() ); assert!(path.exists()); fs::remove_file(path).unwrap(); -- 2.54.0 From 3c9c64d4b4493d3db7ecaad7ec42f0e770d84c17 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 04:33:56 +0200 Subject: [PATCH 48/58] test(kar): cover array cursor sync failure --- control-plane/src/prepare_preview.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 5f9528fc..8eb604a8 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -3730,6 +3730,8 @@ mod tests { fn raw_spool_sync_failure_propagates_for_borrowed_and_owned_cursors() { let fixture = overlay_fixture(); let bytes = 2.5f32.to_le_bytes(); + let mut array_cursor = std::io::Cursor::new(bytes); + assert_cursor_spool_sync_error(&mut array_cursor, &fixture.directory.join("array.raw")); let mut borrowed = std::io::Cursor::new(bytes.as_slice()); assert_cursor_spool_sync_error(&mut borrowed, &fixture.directory.join("borrowed.raw")); let mut owned = std::io::Cursor::new(bytes.to_vec()); -- 2.54.0 From c5727d20809d0d4e922a270aa6e8302e6eba8612 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 05:32:49 +0200 Subject: [PATCH 49/58] refactor verified overlay resolution --- control-plane/src/kar_overlay.rs | 390 ++++++++++++++++++--------- control-plane/src/kar_writer.rs | 3 +- control-plane/src/prepare_preview.rs | 12 +- control-plane/src/stream_parts.rs | 7 +- 4 files changed, 270 insertions(+), 142 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index a9395b4c..609c041f 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -355,172 +355,260 @@ pub struct Summary { pub provenance_path: PathBuf, } -/// Verify both complete archives and bind every replacement to the same -/// virtual-F32 source record before a loader selects an archive by tensor name. -pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result { - let base_archive = kar_writer::canonical_archive_destination(base_archive)?; - let overlay_archive = kar_writer::canonical_archive_destination(overlay_archive)?; - let sidecar = |path: &Path| -> Result { - let name = path.file_name().ok_or("KAR archive has no file name")?; - Ok(path.with_file_name(format!("{}.provenance.json", name.to_string_lossy()))) - }; - let base: BaseProvenance = serde_json::from_reader( - File::open(sidecar(&base_archive)?).map_err(|error| error.to_string())?, - ) - .map_err(|error| error.to_string())?; - let overlay: OverlayProvenance = serde_json::from_reader( - File::open(sidecar(&overlay_archive)?).map_err(|error| error.to_string())?, - ) - .map_err(|error| error.to_string())?; - if !base.supported_partition_policy() - || overlay.schema != "strata-next/kar-overlay-provenance-v1" - || overlay.base_archive_sha256 != base.archive_sha256 - || overlay.levels < 2 - || overlay.levels > 8 - || overlay.records.is_empty() - || hex::encode(hash_file(&base_archive)?) != base.archive_sha256 - || hex::encode(hash_file(&overlay_archive)?) != overlay.overlay_archive_sha256 - { - return Err("base or overlay archive differs from its provenance".into()); +struct ExpectedSource { + offset: u64, + bytes: u64, + digest: String, + dimensions: Option>, +} + +struct VerifiedOverlayArchives { + base: BaseProvenance, + overlay: OverlayProvenance, + base_sources: Vec, + overlay_sources: Vec, +} + +fn sidecar_path(path: &Path) -> Result { + let name = path.file_name().ok_or("KAR archive has no file name")?; + Ok(path.with_file_name(format!("{}.provenance.json", name.to_string_lossy()))) +} + +fn read_archive_provenance(path: &Path) -> Result { + serde_json::from_reader(File::open(sidecar_path(path)?).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string()) +} + +fn validate_archive_provenance( + base_path: &Path, + overlay_path: &Path, + base: &BaseProvenance, + overlay: &OverlayProvenance, +) -> Result<(), String> { + let valid = base.supported_partition_policy() + && overlay.schema == "strata-next/kar-overlay-provenance-v1" + && overlay.base_archive_sha256 == base.archive_sha256 + && (2..=8).contains(&overlay.levels) + && !overlay.records.is_empty() + && hex::encode(hash_file(base_path)?) == base.archive_sha256 + && hex::encode(hash_file(overlay_path)?) == overlay.overlay_archive_sha256; + if valid { + Ok(()) + } else { + Err("base or overlay archive differs from its provenance".into()) } - let (base_summary, base_sources) = kar::verify_with_sources(&base_archive)?; - let (overlay_summary, overlay_sources) = kar::verify_with_sources(&overlay_archive)?; - if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)? - || overlay_summary.source_digest != base_summary.source_digest - || base_summary.source_bytes != base.derived_f32_bytes - || overlay_summary.source_bytes != base_summary.source_bytes - || overlay_sources.len() != overlay.records.len() - { +} + +fn verified_archive_sources( + base_path: &Path, + overlay_path: &Path, + base: &BaseProvenance, + overlay: &OverlayProvenance, +) -> Result<(Vec, Vec), String> { + let (base_summary, base_sources) = kar::verify_with_sources(base_path)?; + let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_path)?; + let source_digest = parse_digest(&base.derived_f32_sha256)?; + let valid = base_summary.source_digest == source_digest + && overlay_summary.source_digest == base_summary.source_digest + && base_summary.source_bytes == base.derived_f32_bytes + && overlay_summary.source_bytes == base_summary.source_bytes + && overlay_sources.len() == overlay.records.len(); + if !valid { return Err("KAR directory differs from virtual-F32 provenance".into()); } - let mut recorded_base = HashMap::new(); + Ok((base_sources, overlay_sources)) +} + +fn load_verified_overlay_archives( + base_path: &Path, + overlay_path: &Path, +) -> Result { + let base_path = kar_writer::canonical_archive_destination(base_path)?; + let overlay_path = kar_writer::canonical_archive_destination(overlay_path)?; + let base: BaseProvenance = read_archive_provenance(&base_path)?; + let overlay: OverlayProvenance = read_archive_provenance(&overlay_path)?; + validate_archive_provenance(&base_path, &overlay_path, &base, &overlay)?; + let (base_sources, overlay_sources) = + verified_archive_sources(&base_path, &overlay_path, &base, &overlay)?; + Ok(VerifiedOverlayArchives { + base, + overlay, + base_sources, + overlay_sources, + }) +} + +fn unique_base_records(base: &BaseProvenance) -> Result, String> { + let mut recorded = HashMap::new(); for record in &base.tensors { - if recorded_base.insert(record.name.as_str(), record).is_some() { + if recorded.insert(record.name.as_str(), record).is_some() { return Err("duplicate base provenance tensor".into()); } } - struct ExpectedSource<'a> { - offset: u64, - bytes: u64, - digest: &'a str, - dimensions: Option<&'a [u64]>, + Ok(recorded) +} + +fn validate_partition_parent( + parent: &PartitionedTensor, + original: &BaseTensor, +) -> Result<(), String> { + let elements = parent + .parent_dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)); + if parent.parts.len() < 2 + || parent.parent_dimensions.is_empty() + || elements.and_then(|n| n.checked_mul(4)) != Some(original.derived_bytes) + { + return Err("invalid partitioned tensor provenance".into()); } + Ok(()) +} + +struct PartitionProgress { + source: ExpectedSource, + next_offset: u64, + last_dimension: u64, +} + +fn partition_progress( + parent: &PartitionedTensor, + part: &PartitionPart, + offset: u64, + last_dimension: u64, +) -> Result { + let dimensions_match = part.dimensions.len() == parent.parent_dimensions.len() + && part.dimensions[..part.dimensions.len() - 1] + == parent.parent_dimensions[..parent.parent_dimensions.len() - 1]; + let bytes = part + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)); + if !dimensions_match + || bytes.and_then(|n| n.checked_mul(4)) != Some(part.derived_bytes) + || part.derived_offset != offset + { + return Err(format!("{}: invalid partition geometry", part.name)); + } + Ok(PartitionProgress { + source: ExpectedSource { + offset: part.derived_offset, + bytes: part.derived_bytes, + digest: part.f32_sha256.clone(), + dimensions: Some(part.dimensions.clone()), + }, + next_offset: offset + .checked_add(part.derived_bytes) + .ok_or("partitioned tensor offset overflow")?, + last_dimension: last_dimension + .checked_add(*part.dimensions.last().unwrap()) + .ok_or("partitioned tensor shape overflow")?, + }) +} + +fn insert_partition_parts( + parent: &PartitionedTensor, + original: &BaseTensor, + expected: &mut HashMap, +) -> Result<(), String> { + let mut offset = original.derived_offset; + let mut last_dimension = 0u64; + for part in &parent.parts { + let progress = partition_progress(parent, part, offset, last_dimension)?; + if expected + .insert(part.name.clone(), progress.source) + .is_some() + { + return Err("duplicate partitioned tensor part".into()); + } + offset = progress.next_offset; + last_dimension = progress.last_dimension; + } + let parent_end = original + .derived_offset + .checked_add(original.derived_bytes) + .ok_or("partitioned parent offset overflow")?; + if offset != parent_end || last_dimension != *parent.parent_dimensions.last().unwrap() { + return Err("partitioned parts do not cover their parent".into()); + } + Ok(()) +} + +fn expected_base_sources(base: &BaseProvenance) -> Result, String> { + let recorded = unique_base_records(base)?; let mut expected = HashMap::new(); let mut partitioned = HashSet::new(); for parent in &base.partitioned_tensors { - let original = recorded_base + let original = recorded .get(parent.parent_name.as_str()) .ok_or("partitioned parent absent from base provenance")?; - if !partitioned.insert(parent.parent_name.as_str()) - || parent.parts.len() < 2 - || parent.parent_dimensions.is_empty() - || parent - .parent_dimensions - .iter() - .try_fold(1u64, |n, dim| n.checked_mul(*dim)) - .and_then(|n| n.checked_mul(4)) - != Some(original.derived_bytes) - { + if !partitioned.insert(parent.parent_name.as_str()) { return Err("invalid partitioned tensor provenance".into()); } - let mut offset = original.derived_offset; - let mut last_dimension = 0u64; - for part in &parent.parts { - if part.dimensions.len() != parent.parent_dimensions.len() - || part.dimensions[..part.dimensions.len() - 1] - != parent.parent_dimensions[..parent.parent_dimensions.len() - 1] - || part - .dimensions - .iter() - .try_fold(1u64, |n, dim| n.checked_mul(*dim)) - .and_then(|n| n.checked_mul(4)) - != Some(part.derived_bytes) - || part.derived_offset != offset - { - return Err(format!("{}: invalid partition geometry", part.name)); - } - offset = offset - .checked_add(part.derived_bytes) - .ok_or("partitioned tensor offset overflow")?; - last_dimension = last_dimension - .checked_add(*part.dimensions.last().unwrap()) - .ok_or("partitioned tensor shape overflow")?; - if expected - .insert( - part.name.as_str(), - ExpectedSource { - offset: part.derived_offset, - bytes: part.derived_bytes, - digest: &part.f32_sha256, - dimensions: Some(&part.dimensions), - }, - ) - .is_some() - { - return Err("duplicate partitioned tensor part".into()); - } - } - if offset - != original - .derived_offset - .checked_add(original.derived_bytes) - .ok_or("partitioned parent offset overflow")? - || last_dimension != *parent.parent_dimensions.last().unwrap() - { - return Err("partitioned parts do not cover their parent".into()); - } + validate_partition_parent(parent, original)?; + insert_partition_parts(parent, original, &mut expected)?; } for record in &base.tensors { if partitioned.contains(record.name.as_str()) { continue; } - if expected - .insert( - record.name.as_str(), - ExpectedSource { - offset: record.derived_offset, - bytes: record.derived_bytes, - digest: &record.f32_sha256, - dimensions: None, - }, - ) - .is_some() - { + let source = ExpectedSource { + offset: record.derived_offset, + bytes: record.derived_bytes, + digest: record.f32_sha256.clone(), + dimensions: None, + }; + if expected.insert(record.name.clone(), source).is_some() { return Err("base provenance record collides with a partition".into()); } } - if expected.len() != base_sources.len() { + Ok(expected) +} + +fn verify_base_source_mappings( + expected: &HashMap, + sources: &[kar::TensorSource], +) -> Result<(), String> { + if expected.len() != sources.len() { return Err("base KAR record count differs from partitioned provenance".into()); } - for source in &base_sources { + for source in sources { let record = expected - .get(source.name.as_str()) + .get(&source.name) .ok_or("base KAR tensor absent from provenance")?; - if source.digest != parse_digest(record.digest)? + let dimensions_match = record + .dimensions + .as_ref() + .is_none_or(|dims| source.dimensions == *dims); + let elements = source + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)); + if source.digest != parse_digest(&record.digest)? || source.offset != record.offset || source.dtype != 0 - || record - .dimensions - .is_some_and(|dims| source.dimensions != dims) - || source - .dimensions - .iter() - .try_fold(1u64, |n, dim| n.checked_mul(*dim)) - .and_then(|n| n.checked_mul(4)) - != Some(record.bytes) + || !dimensions_match + || elements.and_then(|n| n.checked_mul(4)) != Some(record.bytes) { return Err(format!("{}: base source mapping differs", source.name)); } } + Ok(()) +} + +fn verified_replacements( + overlay: &OverlayProvenance, + sources: &[kar::TensorSource], +) -> Result, String> { let mut replacements = HashMap::new(); - for (index, source) in overlay_sources.iter().enumerate() { + for (index, source) in sources.iter().enumerate() { let record = overlay .records .iter() .find(|record| record.name == source.name) .ok_or("overlay KAR tensor absent from provenance")?; // `verify_with_sources` rejects duplicate archive names before this loop. - replacements.insert(source.name.as_str(), index); + replacements.insert(source.name.clone(), index); // Strict sidecar JSON parsing rejects non-finite and out-of-range f64 values. if record.derived_offset != source.offset || record.f32_sha256 != hex::encode(source.digest) @@ -531,12 +619,19 @@ pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result, +) -> Result, String> { + let mut records = Vec::with_capacity(base.len()); + for (index, source) in base.iter().enumerate() { + let replacement = replacements.get(&source.name).copied(); if let Some(overlay_index) = replacement { - let selected = &overlay_sources[overlay_index]; + let selected = &overlay[overlay_index]; if selected.digest != source.digest || selected.offset != source.offset || selected.dimensions != source.dimensions @@ -560,10 +655,25 @@ pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result Result { + let archives = load_verified_overlay_archives(base_archive, overlay_archive)?; + let expected = expected_base_sources(&archives.base)?; + verify_base_source_mappings(&expected, &archives.base_sources)?; + let replacements = verified_replacements(&archives.overlay, &archives.overlay_sources)?; + let records = resolved_records( + &archives.base_sources, + &archives.overlay_sources, + &replacements, + )?; Ok(Resolution { schema: "strata-next/verified-kar-overlay-selection-v1", - base_archive_sha256: base.archive_sha256, - overlay_archive_sha256: overlay.overlay_archive_sha256, + base_archive_sha256: archives.base.archive_sha256, + overlay_archive_sha256: archives.overlay.overlay_archive_sha256, replacement_count: replacements.len(), records, }) @@ -1345,7 +1455,19 @@ mod tests { fn strict_json_rejects_non_finite_overlay_error_values() { for number in ["NaN", "Infinity", "-Infinity", "1e999", "-1e999"] { let json = format!( - r#"{{"schema":"strata-next/kar-overlay-provenance-v1","base_archive_sha256":"base","overlay_archive_sha256":"overlay","levels":2,"records":[{{"name":"weight","derived_offset":0,"f32_sha256":"digest","section_bytes":0,"relative_l2":{number}}}]}}"# + concat!( + r#"{{"schema":"strata-next/kar-overlay-provenance-v1","base_archive_sha256":"#, + r#""base","overlay_archive_sha256":"#, + r#""overlay","levels":2,"records":[{{"name":"weight","derived_offset":0,"f32_sha256":"#, + r#""digest","section_bytes":0,"relative_l2":"#, + "{}", + r#"}}]}}"# + ), + number + ); + assert!( + serde_json::from_str::(&json.replace(number, "0.0")).is_ok(), + "{json}" ); assert!( serde_json::from_str::(&json).is_err(), diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 7ab51d9d..e9e4b780 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -76,7 +76,8 @@ enum ArchiveOutputOperation { #[cfg(test)] thread_local! { - static ARCHIVE_OUTPUT_FAILURE: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static ARCHIVE_OUTPUT_FAILURE: std::cell::Cell> = + const { std::cell::Cell::new(None) }; } #[cfg(test)] diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 8eb604a8..34c8c3b5 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -5647,10 +5647,7 @@ mod tests { fs::create_dir(&root).unwrap(); let base = root.join("base.kar"); let overlay = root.join("overlay.kar"); - let payload = [1.0f32, 2.0, 3.0, 4.0] - .into_iter() - .flat_map(f32::to_le_bytes) - .collect::>(); + let payload = minimal_identity_payload(); let tensor_digest = Sha256::digest(&payload).into(); let base_identity = identity_source(case.base_digest, case.base_bytes, case.base_dtype); let overlay_identity = identity_source(case.overlay_digest, case.overlay_bytes, 0); @@ -5676,6 +5673,13 @@ mod tests { } } + fn minimal_identity_payload() -> Vec { + [1.0f32, 2.0, 3.0, 4.0] + .into_iter() + .flat_map(f32::to_le_bytes) + .collect() + } + fn identity_source( digest: [u8; 32], bytes: u64, diff --git a/control-plane/src/stream_parts.rs b/control-plane/src/stream_parts.rs index 61cf12ca..cb3e48ea 100644 --- a/control-plane/src/stream_parts.rs +++ b/control-plane/src/stream_parts.rs @@ -674,9 +674,10 @@ mod tests { max_part_elements: 32, ple_part_elements: Some(32), }; - assert!( - matches!(plan_shards_with_limits(&identity, directory, limits), Err(error) if error.contains("requires per_layer_token_embd.weight")) - ); + assert!(matches!( + plan_shards_with_limits(&identity, directory, limits), + Err(error) if error.contains("requires per_layer_token_embd.weight") + )); } fn assert_duplicate_names_are_rejected(directory: &Path) { -- 2.54.0 From 845eb571ec1b9eb9e5618460e1b7949e9bf94eaf Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 06:11:44 +0200 Subject: [PATCH 50/58] Remove unconsumed comments from STRA-8 diff --- control-plane/src/kar_overlay.rs | 2 -- control-plane/src/kar_writer.rs | 1 - control-plane/src/prepare_preview.rs | 36 +++++++++++++++++++++------- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index 609c041f..8223592a 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -607,9 +607,7 @@ fn verified_replacements( .iter() .find(|record| record.name == source.name) .ok_or("overlay KAR tensor absent from provenance")?; - // `verify_with_sources` rejects duplicate archive names before this loop. replacements.insert(source.name.clone(), index); - // Strict sidecar JSON parsing rejects non-finite and out-of-range f64 values. if record.derived_offset != source.offset || record.f32_sha256 != hex::encode(source.digest) || record.section_bytes != source.section_bytes diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index e9e4b780..06329803 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -302,7 +302,6 @@ fn validate_private_archive_parent_with( ) -> Result<(), String> { for directory in parent.ancestors().collect::>().into_iter().rev() { let metadata = metadata(directory).map_err(|error| error.to_string())?; - // The caller passes a canonicalized parent, so every ancestor is a directory. if !archive_parent_owner_allowed(metadata.uid(), uid) { return Err("KAR parent is not owned by the service or root".into()); } diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 34c8c3b5..407a26bd 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -1537,7 +1537,6 @@ fn validate_single_source_levels(levels: u8) -> Result<(), String> { fn load_single_source_index(path: &Path) -> Result { let index = gguf::tensor_index(path).map_err(|error| error.to_string())?; - // `tensor_index` rejects zero-tensor GGUFs before returning an index. if index.summary.file_size > MAX_SOURCE_BYTES || index.tensors.len() > MAX_TENSORS { return Err("F32 preview exceeds its source or tensor-count limit".into()); } @@ -3172,7 +3171,16 @@ mod tests { tensors: vec![sharded_identity_for(tensor, &raw, &[1.25])], }; let pipe = fixture.directory.join("nonseekable-sharded.pipe"); - assert!(read_sharded_weights(&identity, &index, tensor, &mut open_fifo(&pipe), 0).is_err()); + assert!( + read_sharded_weights( + &identity, + &index, + tensor, + &mut open_private_fixture_fifo(&pipe), + 0 + ) + .is_err() + ); fs::remove_file(pipe).unwrap(); } @@ -3206,25 +3214,35 @@ mod tests { prepared: Vec::new(), }; let pipe = fixture.directory.join("nonseekable-single.pipe"); - assert!(prepare_single_tensor(request, &mut open_fifo(&pipe), &mut progress).is_err()); + assert!( + prepare_single_tensor( + request, + &mut open_private_fixture_fifo(&pipe), + &mut progress + ) + .is_err() + ); fs::remove_file(pipe).unwrap(); } #[cfg(target_os = "linux")] - fn open_fifo(path: &Path) -> File { + fn open_private_fixture_fifo(private_fifo_path: &Path) -> File { use std::os::unix::ffi::OsStrExt; - let name = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); - // SAFETY: `name` is NUL-terminated and points to this test's private FIFO path. - assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); - let writer_path = path.to_path_buf(); + let private_fifo_name = + std::ffi::CString::new(private_fifo_path.as_os_str().as_bytes()).unwrap(); + assert_eq!( + unsafe { libc::mkfifo(private_fifo_name.as_ptr(), 0o600) }, + 0 + ); + let writer_path = private_fifo_path.to_path_buf(); let writer = std::thread::spawn(move || { fs::OpenOptions::new() .write(true) .open(writer_path) .unwrap() }); - let reader = File::open(path).unwrap(); + let reader = File::open(private_fifo_path).unwrap(); drop(writer.join().unwrap()); reader } -- 2.54.0 From 161d779b7cb09b413cefc20729f967b053f9d5d0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 06:33:59 +0200 Subject: [PATCH 51/58] Complete STRA-8 comment carrier audit --- control-plane/src/kar_overlay.rs | 2 +- control-plane/src/kar_writer.rs | 4 +++- control-plane/src/prepare_preview.rs | 6 +----- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index 8223592a..984b3b0f 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -1442,7 +1442,7 @@ fn overlay_summary( } #[cfg(test)] -#[allow(clippy::items_after_test_module)] // comparison helpers remain grouped after this focused test module +#[allow(clippy::items_after_test_module)] mod tests { use super::*; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 06329803..d4e94b33 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -21,6 +21,8 @@ use crate::kar; #[cfg(test)] static ARCHIVE_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); const ARCHIVE_TEMP_SLOTS: u8 = 8; +#[cfg(unix)] +const POSIX_STICKY_BIT: u32 = 0o1000; #[cfg(test)] thread_local! { @@ -306,7 +308,7 @@ fn validate_private_archive_parent_with( return Err("KAR parent is not owned by the service or root".into()); } let mode = metadata.mode(); - let sticky = mode & 0o1000 != 0; // POSIX S_ISVTX is mode bit 01000. + let sticky = mode & POSIX_STICKY_BIT != 0; if mode & 0o022 != 0 && !sticky { return Err("KAR parent allows untrusted path replacement".into()); } diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 407a26bd..3420db01 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -964,10 +964,6 @@ fn require_streamed_space( if archive_tensor_count == 0 || archive_tensor_count > 100_000 { return Err("streamed sharded tensor count exceeds KAR-2 limits".into()); } - // Every nested part stores at least `levels` four-byte plane words per - // 32 values; a RAW fallback stores four bytes per value. The smaller of - // these is a safe lower bound before section files are created. Passing - // this gate does not guarantee enough space for scales and metadata. let minimum_payload_bytes = archive_parts .iter() .flat_map(|parts| parts.iter()) @@ -3804,7 +3800,7 @@ mod tests { } #[test] - fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { + fn minimum_payload_uses_plane_bytes_or_raw_fallback() { assert_eq!( minimum_part_payload_bytes(707_775_598_080, 2).unwrap(), 44_235_974_880 -- 2.54.0 From 1d8e022cb46ab17728b3f78d343e1480fc432148 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 07:14:43 +0200 Subject: [PATCH 52/58] fix tokenizer GGUF metadata validation and limits --- crates/tokenizer/src/lib.rs | 521 ++++++++++++++++++++++-------------- 1 file changed, 322 insertions(+), 199 deletions(-) diff --git a/crates/tokenizer/src/lib.rs b/crates/tokenizer/src/lib.rs index 89abe67b..2eff44ab 100644 --- a/crates/tokenizer/src/lib.rs +++ b/crates/tokenizer/src/lib.rs @@ -346,72 +346,126 @@ const MAX_RELEVANT_TOKENIZER_FIELDS: usize = 128; /// that separately before using these tokenizer assets. pub fn read_gguf_tokenizer_metadata(path: &Path) -> GgufResult { let mut cursor = GgufCursor::open(path)?; - if cursor.take(4)? != b"GGUF" { - return Err(gguf_error("not a GGUF file")); - } - if cursor.u32()? != 3 { - return Err(gguf_error("only GGUF v3 is supported")); - } - cursor.skip(8)?; // tensor count; tensor inspection belongs to the model loader. - let count = cursor.u64()?; - if count > MAX_GGUF_METADATA_ENTRIES { - return Err(gguf_error("unreasonable GGUF metadata entry count")); - } - let minimum_bytes = count - .checked_mul(13) - .ok_or_else(|| gguf_error("GGUF metadata entry count overflow"))?; - if minimum_bytes > cursor.remaining()? { - return Err(gguf_error("GGUF metadata count exceeds bounded header")); + cursor.validate_file()?; + let count = cursor.metadata_entry_count()?; + TokenizerFields::read(&mut cursor, count)?.finish() +} + +#[derive(Default)] +struct TokenizerFields { + model: Option, + pre: Option, + tokens: Option>, + merges: Option>, + token_types: Option>, + special_ids: BTreeMap, + chat_template: Option, + seen_fields: HashSet, +} + +impl TokenizerFields { + fn read(cursor: &mut GgufCursor, count: u64) -> GgufResult { + let mut fields = Self::default(); + for _ in 0..count { + fields.read_entry(cursor)?; + } + Ok(fields) } - let mut model = None; - let mut pre = None; - let mut tokens = None; - let mut merges = None; - let mut token_types = None; - let mut special_ids = BTreeMap::new(); - let mut chat_template = None; - let mut seen_fields = HashSet::new(); - for _ in 0..count { + fn read_entry(&mut self, cursor: &mut GgufCursor) -> GgufResult<()> { let key = cursor.string()?; let kind = cursor.u32()?; - let relevant = matches!( - key.as_str(), - "tokenizer.ggml.model" - | "tokenizer.ggml.pre" - | "tokenizer.ggml.tokens" - | "tokenizer.ggml.merges" - | "tokenizer.ggml.token_type" - | "tokenizer.chat_template" - ) || (key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id")); - if relevant { - if seen_fields.len() >= MAX_RELEVANT_TOKENIZER_FIELDS { - return Err(gguf_error("too many tokenizer metadata fields")); - } - if !seen_fields.insert(key.clone()) { - return Err(gguf_error("duplicate tokenizer metadata field")); - } + self.ensure_unique(&key)?; + self.read_value(key, kind, cursor) + } + + fn ensure_unique(&mut self, key: &str) -> GgufResult<()> { + if !is_relevant_tokenizer_field(key) { + return Ok(()); } + if self.seen_fields.len() >= MAX_RELEVANT_TOKENIZER_FIELDS { + return Err(gguf_error("too many tokenizer metadata fields")); + } + if !self.seen_fields.insert(key.to_owned()) { + return Err(gguf_error("duplicate tokenizer metadata field")); + } + Ok(()) + } + + fn read_value(&mut self, key: String, kind: u32, cursor: &mut GgufCursor) -> GgufResult<()> { match key.as_str() { - "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), - "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), - "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), - "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), - "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), - _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { - special_ids.insert(key, cursor.integer(kind)?); + "tokenizer.ggml.model" if kind == 8 => self.model = Some(cursor.string()?), + "tokenizer.ggml.pre" => self.pre = Some(read_pre_value(cursor, kind)?), + "tokenizer.ggml.tokens" => self.tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" => self.merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" => self.token_types = Some(cursor.integer_array(kind)?), + "tokenizer.chat_template" if kind == 8 => self.chat_template = Some(cursor.string()?), + _ if is_special_token_id(&key) => { + self.special_ids.insert(key, cursor.integer(kind)?); } _ => cursor.skip_value(kind)?, } + Ok(()) } - let model = model.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?; - let tokens = tokens.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?; - let merges = merges.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?; - let chat_template = - chat_template.ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?; - if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { + fn finish(self) -> GgufResult { + let model = self.model.ok_or_else(missing_model)?; + let tokens = self.tokens.ok_or_else(missing_tokens)?; + let merges = self.merges.ok_or_else(missing_merges)?; + let chat_template = self.chat_template.ok_or_else(missing_chat_template)?; + validate_tokenizer_fields( + &model, + self.pre.as_deref(), + &tokens, + self.token_types.as_deref(), + &chat_template, + )?; + let vocab = validate_vocabulary(&tokens)?; + validate_merges(&merges, &vocab)?; + validate_special_ids(&self.special_ids, tokens.len())?; + Ok(GgufTokenizerMetadata { + model, + pre: self.pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types: self.token_types, + special_ids: self.special_ids, + chat_template, + }) + } +} + +fn is_relevant_tokenizer_field(key: &str) -> bool { + matches!( + key, + "tokenizer.ggml.model" + | "tokenizer.ggml.pre" + | "tokenizer.ggml.tokens" + | "tokenizer.ggml.merges" + | "tokenizer.ggml.token_type" + | "tokenizer.chat_template" + ) || is_special_token_id(key) +} + +fn is_special_token_id(key: &str) -> bool { + key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") +} + +fn read_pre_value(cursor: &mut GgufCursor, kind: u32) -> GgufResult { + if kind != 8 { + return Err(gguf_error("tokenizer.ggml.pre must be a string")); + } + cursor.string() +} + +fn validate_tokenizer_fields( + model: &str, + pre: Option<&str>, + tokens: &[String], + token_types: Option<&[u32]>, + chat_template: &str, +) -> GgufResult<()> { + if model != "gpt2" || pre.is_some_and(|value| value != "qwen35") { return Err(gguf_error( "only the qwen35 byte-level BPE tokenizer is supported", )); @@ -421,49 +475,66 @@ pub fn read_gguf_tokenizer_metadata(path: &Path) -> GgufResult GgufResult> { let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); if vocab.len() != tokens.len() { return Err(gguf_error( "GGUF tokenizer has duplicate vocabulary entries", )); } + Ok(vocab) +} + +fn validate_merges(merges: &[String], vocab: &HashSet<&str>) -> GgufResult<()> { let mut seen_merges = HashSet::new(); - for merge in &merges { + for merge in merges { let Some((left, right)) = merge.split_once(' ') else { return Err(gguf_error("GGUF BPE merge is not a pair")); }; - if left.is_empty() - || right.is_empty() - || right.contains(' ') - || !vocab.contains(left) - || !vocab.contains(right) - || !seen_merges.insert(merge) - { + if !valid_merge(left, right, vocab) || !seen_merges.insert(merge) { return Err(gguf_error("GGUF BPE merge is invalid or duplicated")); } } - for &id in special_ids.values() { - if id as usize >= tokens.len() { - return Err(gguf_error("special token ID exceeds vocabulary")); - } + Ok(()) +} + +fn valid_merge(left: &str, right: &str, vocab: &HashSet<&str>) -> bool { + !left.is_empty() + && !right.is_empty() + && !right.contains(' ') + && vocab.contains(left) + && vocab.contains(right) +} + +fn validate_special_ids(ids: &BTreeMap, token_count: usize) -> GgufResult<()> { + if ids.values().any(|id| *id as usize >= token_count) { + return Err(gguf_error("special token ID exceeds vocabulary")); } - Ok(GgufTokenizerMetadata { - model, - pre: pre.unwrap_or_else(|| "qwen35".to_owned()), - tokens, - merges, - token_types, - special_ids, - chat_template, - }) + Ok(()) +} + +fn missing_model() -> GgufTokenizerError { + gguf_error("GGUF is missing tokenizer.ggml.model") +} + +fn missing_tokens() -> GgufTokenizerError { + gguf_error("GGUF is missing tokenizer.ggml.tokens") +} + +fn missing_merges() -> GgufTokenizerError { + gguf_error("GGUF is missing tokenizer.ggml.merges") +} + +fn missing_chat_template() -> GgufTokenizerError { + gguf_error("GGUF is missing tokenizer.chat_template") } fn gguf_error(message: impl Into) -> GgufTokenizerError { @@ -486,6 +557,35 @@ impl GgufCursor { Ok(Self { file, size }) } + fn validate_file(&mut self) -> GgufResult<()> { + if self.take(4)? != b"GGUF" { + return Err(gguf_error("not a GGUF file")); + } + if self.u32()? != 3 { + return Err(gguf_error("only GGUF v3 is supported")); + } + self.skip(8) + } + + fn metadata_entry_count(&mut self) -> GgufResult { + let count = self.u64()?; + if count > MAX_GGUF_METADATA_ENTRIES { + return Err(gguf_error("unreasonable GGUF metadata entry count")); + } + self.validate_entry_envelope(count)?; + Ok(count) + } + + fn validate_entry_envelope(&mut self, count: u64) -> GgufResult<()> { + let minimum_bytes = count + .checked_mul(13) + .ok_or_else(|| gguf_error("GGUF metadata entry count overflow"))?; + if minimum_bytes > self.remaining()? { + return Err(gguf_error("GGUF metadata count exceeds bounded header")); + } + Ok(()) + } + fn position(&mut self) -> GgufResult { self.file .stream_position() @@ -638,43 +738,58 @@ impl GgufCursor { let size = self.u64()?; self.skip(size) } - 9 => { - let element = self.u32()?; - let count = self.u64()?; - match element { - 8 => { - if count > MAX_GGUF_METADATA_ENTRIES { - return Err(gguf_error("unreasonable GGUF string array count")); - } - let minimum_bytes = count - .checked_mul(8) - .ok_or_else(|| gguf_error("GGUF string array size overflow"))?; - if minimum_bytes > self.remaining()? { - return Err(gguf_error("GGUF string array exceeds remaining header")); - } - for _ in 0..count { - let size = self.u64()?; - if size > MAX_GGUF_HEADER_BYTES { - return Err(gguf_error("GGUF string array element is too large")); - } - self.skip(size)?; - } - Ok(()) - } - 9 => Err(gguf_error("nested GGUF arrays are unsupported")), - _ => { - let width = value_width(element)?; - let bytes = count - .checked_mul(width) - .ok_or_else(|| gguf_error("GGUF array size overflow"))?; - self.skip(bytes) - } - } - } + 9 => self.skip_array_value(), 10..=12 => self.skip(8), _ => Err(gguf_error(format!("unknown GGUF metadata type {kind}"))), } } + + fn skip_array_value(&mut self) -> GgufResult<()> { + let element = self.u32()?; + let count = self.u64()?; + match element { + 8 => self.skip_string_array(count), + 9 => Err(gguf_error("nested GGUF arrays are unsupported")), + _ => self.skip_typed_array(element, count), + } + } + + fn skip_string_array(&mut self, count: u64) -> GgufResult<()> { + if count > MAX_GGUF_METADATA_ENTRIES { + return Err(gguf_error("unreasonable GGUF string array count")); + } + self.validate_string_array_size(count)?; + for _ in 0..count { + self.skip_string_array_item()?; + } + Ok(()) + } + + fn validate_string_array_size(&mut self, count: u64) -> GgufResult<()> { + let bytes = count + .checked_mul(8) + .ok_or_else(|| gguf_error("GGUF string array size overflow"))?; + if bytes > self.remaining()? { + return Err(gguf_error("GGUF string array exceeds remaining header")); + } + Ok(()) + } + + fn skip_string_array_item(&mut self) -> GgufResult<()> { + let size = self.u64()?; + if size > MAX_GGUF_HEADER_BYTES { + return Err(gguf_error("GGUF string array element is too large")); + } + self.skip(size) + } + + fn skip_typed_array(&mut self, element: u32, count: u64) -> GgufResult<()> { + let width = value_width(element)?; + let bytes = count + .checked_mul(width) + .ok_or_else(|| gguf_error("GGUF array size overflow"))?; + self.skip(bytes) + } } fn value_width(kind: u32) -> GgufResult { @@ -921,7 +1036,7 @@ mod gguf_metadata_tests { fn base() -> Vec { let mut bytes = b"GGUF".to_vec(); bytes.extend_from_slice(&3u32.to_le_bytes()); - bytes.extend_from_slice(&0u64.to_le_bytes()); // no tensors: metadata reader only. + bytes.extend_from_slice(&0u64.to_le_bytes()); bytes.extend_from_slice(&7u64.to_le_bytes()); string_field(&mut bytes, "tokenizer.ggml.model", "gpt2"); string_field(&mut bytes, "tokenizer.ggml.pre", "qwen35"); @@ -952,6 +1067,34 @@ mod gguf_metadata_tests { fs::remove_file(path).unwrap(); } + fn assert_metadata_rejected(bytes: &[u8]) { + with_bytes(bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + } + + fn token_array_count_offset(bytes: &[u8]) -> usize { + let marker = b"tokenizer.ggml.tokens"; + let start = bytes + .windows(marker.len()) + .position(|window| window == marker) + .unwrap(); + start + 8 + marker.len() + 4 + 4 + } + + fn replace_pre_with_integer(bytes: &mut Vec) { + let marker = b"tokenizer.ggml.pre"; + let start = bytes + .windows(marker.len()) + .position(|window| window == marker) + .unwrap(); + let kind = start + marker.len(); + let value = kind + 4; + let end = value + 8 + b"qwen35".len(); + bytes[kind..value].copy_from_slice(&4u32.to_le_bytes()); + bytes.splice(value..end, 1u32.to_le_bytes()); + } + #[test] fn reads_qwen35_tokenizer_metadata_with_control_plane_parity() { with_bytes(&base(), |path| { @@ -967,108 +1110,73 @@ mod gguf_metadata_tests { } #[test] - fn rejects_wrong_magic_version_truncation_and_excessive_metadata_count() { + fn rejects_wrong_magic() { let mut bytes = base(); bytes[0] = b'X'; - with_bytes(&bytes, |path| { - assert!( - read_gguf_tokenizer_metadata(path) - .unwrap_err() - .to_string() - .contains("GGUF") - ); - }); + assert_metadata_rejected(&bytes); + } + #[test] + fn rejects_unsupported_version() { let mut bytes = base(); bytes[4..8].copy_from_slice(&2u32.to_le_bytes()); - with_bytes(&bytes, |path| { - assert!( - read_gguf_tokenizer_metadata(path) - .unwrap_err() - .to_string() - .contains("v3") - ); - }); + assert_metadata_rejected(&bytes); + } + #[test] + fn rejects_truncated_metadata() { let bytes = base(); - with_bytes(&bytes[..bytes.len() - 2], |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()); - }); + assert_metadata_rejected(&bytes[..bytes.len() - 2]); + } + #[test] + fn rejects_excessive_metadata_count() { let mut bytes = b"GGUF".to_vec(); bytes.extend_from_slice(&3u32.to_le_bytes()); bytes.extend_from_slice(&0u64.to_le_bytes()); bytes.extend_from_slice(&u64::MAX.to_le_bytes()); - with_bytes(&bytes, |path| { - assert!( - read_gguf_tokenizer_metadata(path) - .unwrap_err() - .to_string() - .contains("entry count") - ); - }); + assert_metadata_rejected(&bytes); } #[test] - fn rejects_oversized_string_and_truncated_or_excessive_arrays_before_allocation() { + fn rejects_oversized_metadata_string() { let mut bytes = b"GGUF".to_vec(); bytes.extend_from_slice(&3u32.to_le_bytes()); bytes.extend_from_slice(&0u64.to_le_bytes()); bytes.extend_from_slice(&1u64.to_le_bytes()); bytes.extend_from_slice(&(MAX_GGUF_STRING_BYTES + 1).to_le_bytes()); - bytes.extend_from_slice(&[0; 5]); // Keep the minimum metadata entry envelope intact. - with_bytes(&bytes, |path| { - assert!( - read_gguf_tokenizer_metadata(path) - .unwrap_err() - .to_string() - .contains("too large") - ); - }); - - let mut bytes = base(); - bytes.extend_from_slice(&[0; 0]); - // Replace the token array's count with a value above the explicit cap. - let marker = b"tokenizer.ggml.tokens"; - let at = bytes - .windows(marker.len()) - .position(|w| w == marker) - .unwrap(); - let count_at = at + 8 + marker.len() + 4 + 4; - bytes[count_at..count_at + 8] - .copy_from_slice(&(MAX_TOKENIZER_ARRAY_ITEMS + 1).to_le_bytes()); - with_bytes(&bytes, |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()); - }); - - let mut bytes = base(); - let at = bytes - .windows(marker.len()) - .position(|w| w == marker) - .unwrap(); - let count_at = at + 8 + marker.len() + 4 + 4; - bytes[count_at..count_at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); - with_bytes(&bytes, |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()); - }); + bytes.extend_from_slice(&[0; 5]); + assert_metadata_rejected(&bytes); } #[test] - fn rejects_duplicate_tokenizer_metadata_and_duplicate_vocabulary_tokens() { + fn rejects_excessive_token_array_count() { + let mut bytes = base(); + let count_at = token_array_count_offset(&bytes); + bytes[count_at..count_at + 8] + .copy_from_slice(&(MAX_TOKENIZER_ARRAY_ITEMS + 1).to_le_bytes()); + assert_metadata_rejected(&bytes); + } + + #[test] + fn rejects_token_array_count_overflow() { + let mut bytes = base(); + let count_at = token_array_count_offset(&bytes); + bytes[count_at..count_at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_metadata_rejected(&bytes); + } + + #[test] + fn rejects_duplicate_tokenizer_metadata() { let mut bytes = base(); string_field(&mut bytes, "tokenizer.ggml.model", "gpt2"); bytes[16..24].copy_from_slice(&8u64.to_le_bytes()); - with_bytes(&bytes, |path| { - assert!( - read_gguf_tokenizer_metadata(path) - .unwrap_err() - .to_string() - .contains("duplicate tokenizer metadata") - ); - }); + assert_metadata_rejected(&bytes); + } + #[test] + fn rejects_duplicate_vocabulary_tokens() { let mut bytes = base(); - // Rewrite the third token "ab" to "a", preserving all offsets. let marker = b"tokenizer.ggml.tokens"; let at = bytes .windows(marker.len()) @@ -1085,7 +1193,7 @@ mod gguf_metadata_tests { } #[test] - fn rejects_invalid_tokenizer_types_ids_merges_and_unknown_metadata_types() { + fn rejects_special_token_id_outside_vocabulary() { let mut bytes = base(); let marker = b"tokenizer.ggml.eos_token_id"; let at = bytes @@ -1094,10 +1202,11 @@ mod gguf_metadata_tests { .unwrap(); let value_at = at + 8 + marker.len() + 4; bytes[value_at..value_at + 4].copy_from_slice(&99u32.to_le_bytes()); - with_bytes(&bytes, |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()) - }); + assert_metadata_rejected(&bytes); + } + #[test] + fn rejects_invalid_merge() { let mut bytes = base(); let marker = b"tokenizer.ggml.merges"; let at = bytes @@ -1106,10 +1215,11 @@ mod gguf_metadata_tests { .unwrap(); let value_at = at + 8 + marker.len() + 4 + 4 + 8 + 8; bytes[value_at..value_at + 3].copy_from_slice(b"x y"); - with_bytes(&bytes, |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()) - }); + assert_metadata_rejected(&bytes); + } + #[test] + fn rejects_mismatched_token_types_length() { let mut bytes = base(); let marker = b"tokenizer.ggml.token_type"; let at = bytes @@ -1119,18 +1229,31 @@ mod gguf_metadata_tests { let count_at = at + 8 + marker.len() + 4 + 4; bytes[count_at..count_at + 8].copy_from_slice(&3u64.to_le_bytes()); bytes.drain(count_at + 8 + 4 * 3..count_at + 8 + 4 * 4); - with_bytes(&bytes, |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()) - }); + assert_metadata_rejected(&bytes); + } + #[test] + fn rejects_unknown_metadata_type() { let mut bytes = base(); bytes.extend_from_slice(&("x".len() as u64).to_le_bytes()); bytes.extend_from_slice(b"x"); bytes.extend_from_slice(&99u32.to_le_bytes()); bytes.extend_from_slice(&8u64.to_le_bytes()); bytes[16..24].copy_from_slice(&8u64.to_le_bytes()); + assert_metadata_rejected(&bytes); + } + + #[test] + fn rejects_present_non_string_pre_tokenizer() { + let mut bytes = base(); + replace_pre_with_integer(&mut bytes); with_bytes(&bytes, |path| { - assert!(read_gguf_tokenizer_metadata(path).is_err()) + let error = read_gguf_tokenizer_metadata(path).unwrap_err(); + assert!( + error + .to_string() + .contains("tokenizer.ggml.pre must be a string") + ); }); } -- 2.54.0 From adb52d3ec80e454931c14abf8d0a89a3e9c953f2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 07:34:18 +0200 Subject: [PATCH 53/58] inline tokenizer metadata missing-field errors --- crates/tokenizer/src/lib.rs | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/crates/tokenizer/src/lib.rs b/crates/tokenizer/src/lib.rs index 2eff44ab..d0bf60fd 100644 --- a/crates/tokenizer/src/lib.rs +++ b/crates/tokenizer/src/lib.rs @@ -409,10 +409,18 @@ impl TokenizerFields { } fn finish(self) -> GgufResult { - let model = self.model.ok_or_else(missing_model)?; - let tokens = self.tokens.ok_or_else(missing_tokens)?; - let merges = self.merges.ok_or_else(missing_merges)?; - let chat_template = self.chat_template.ok_or_else(missing_chat_template)?; + let model = self + .model + .ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?; + let tokens = self + .tokens + .ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?; + let merges = self + .merges + .ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?; + let chat_template = self + .chat_template + .ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?; validate_tokenizer_fields( &model, self.pre.as_deref(), @@ -521,22 +529,6 @@ fn validate_special_ids(ids: &BTreeMap, token_count: usize) -> Gguf Ok(()) } -fn missing_model() -> GgufTokenizerError { - gguf_error("GGUF is missing tokenizer.ggml.model") -} - -fn missing_tokens() -> GgufTokenizerError { - gguf_error("GGUF is missing tokenizer.ggml.tokens") -} - -fn missing_merges() -> GgufTokenizerError { - gguf_error("GGUF is missing tokenizer.ggml.merges") -} - -fn missing_chat_template() -> GgufTokenizerError { - gguf_error("GGUF is missing tokenizer.chat_template") -} - fn gguf_error(message: impl Into) -> GgufTokenizerError { GgufTokenizerError(message.into()) } -- 2.54.0 From 881c6b991df696334d2d78fb1b119ac44ac64c76 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 07:44:46 +0200 Subject: [PATCH 54/58] refactor tokenizer finish within LOC limit --- crates/tokenizer/src/lib.rs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/crates/tokenizer/src/lib.rs b/crates/tokenizer/src/lib.rs index d0bf60fd..a8bad37b 100644 --- a/crates/tokenizer/src/lib.rs +++ b/crates/tokenizer/src/lib.rs @@ -409,18 +409,13 @@ impl TokenizerFields { } fn finish(self) -> GgufResult { - let model = self - .model - .ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?; - let tokens = self - .tokens - .ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?; - let merges = self - .merges - .ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?; - let chat_template = self - .chat_template - .ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?; + let (model, tokens, merges, chat_template) = + (self.model, self.tokens, self.merges, self.chat_template); + let model = model.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?; + let tokens = tokens.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?; + let merges = merges.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?; + let chat_template = + chat_template.ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?; validate_tokenizer_fields( &model, self.pre.as_deref(), -- 2.54.0 From ac070fe2fa8bf0db9aa4f5fe627736c465e6e3e1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 09:01:06 +0200 Subject: [PATCH 55/58] fix(ci): verify pinned rustup before executing installer --- .github/workflows/linux.yml | 28 +++------------ scripts/install-pinned-rustup.sh | 61 ++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 23 deletions(-) create mode 100755 scripts/install-pinned-rustup.sh diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index cfd1fa54..1cc2bacc 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -34,10 +34,7 @@ jobs: run: apt-get update && apt-get install -y ca-certificates curl cmake ninja-build g++ python3-numpy - name: Install pinned Rust run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Local checks run: scripts/check-local.sh @@ -56,10 +53,7 @@ jobs: run: apt-get update && apt-get install -y ca-certificates curl python3 - name: Install pinned Rust nightly with LLVM coverage tools run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install nightly-2026-10-05 --profile minimal --component llvm-tools-preview + scripts/install-pinned-rustup.sh rustup toolchain install nightly-2026-10-05 --profile minimal --component llvm-tools-preview - name: Test coverage parser and workflow contract run: python3 scripts/test-changed-scope-coverage.py - name: Run exact changed-production coverage gate @@ -121,11 +115,7 @@ jobs: --image-tag "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - name: Install pinned Rust and musl target run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - name: Assemble actual combined executable and runtime image run: | # Keep resource evidence even if the hosted runner terminates this job. @@ -197,11 +187,7 @@ jobs: run: apt-get update && apt-get install -y ca-certificates curl docker.io musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - name: Build static CLI run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next - name: Verify ELF and checksum @@ -383,11 +369,7 @@ jobs: run: apt-get update && apt-get install -y ca-certificates curl gh musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - name: Rebuild release CLI assets on the tag commit run: | cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next diff --git a/scripts/install-pinned-rustup.sh b/scripts/install-pinned-rustup.sh new file mode 100755 index 00000000..484997e6 --- /dev/null +++ b/scripts/install-pinned-rustup.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Pin the installer independently of rust-toolchain.toml, which pins rustc/cargo. +readonly RUSTUP_VERSION="1.29.0" +readonly RUSTUP_TARGET="x86_64-unknown-linux-gnu" +readonly RUSTUP_INIT_SHA256="4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10" +readonly RUSTUP_INIT_URL="https://static.rust-lang.org/rustup/archive/${RUSTUP_VERSION}/${RUSTUP_TARGET}/rustup-init" + +# Give each Actions job an isolated installation so a host's rustup cannot +# silently override the version pinned here. +if [[ -n "${RUNNER_TEMP:-}" && -n "${GITHUB_RUN_ID:-}" ]]; then + rustup_home="${RUNNER_TEMP}/strata-rustup-${GITHUB_RUN_ID}-${GITHUB_JOB:-job}" + export CARGO_HOME="${rustup_home}/cargo" + export RUSTUP_HOME="${rustup_home}/rustup" + mkdir -p "$CARGO_HOME" + if [[ -n "${GITHUB_ENV:-}" ]]; then + printf 'CARGO_HOME=%s\nRUSTUP_HOME=%s\n' "$CARGO_HOME" "$RUSTUP_HOME" >> "$GITHUB_ENV" + fi +fi + +tmp_dir="$(mktemp -d)" +trap 'rm -rf -- "$tmp_dir"' EXIT + +python3 - "$RUSTUP_INIT_URL" "$tmp_dir/rustup-init" <<'PY' +import shutil +import sys +import urllib.request + +request = urllib.request.Request( + sys.argv[1], headers={"User-Agent": "strata-next-pinned-rustup-bootstrap/1"} +) +with urllib.request.urlopen(request, timeout=120) as response: + with open(sys.argv[2], "wb") as output: + shutil.copyfileobj(response, output) +PY + +printf '%s %s\n' "$RUSTUP_INIT_SHA256" "$tmp_dir/rustup-init" | sha256sum --check --status || { + echo "rustup-init ${RUSTUP_VERSION} checksum mismatch" >&2 + exit 1 +} + +chmod 0755 "$tmp_dir/rustup-init" +"$tmp_dir/rustup-init" -y --no-modify-path \ + --default-host "$RUSTUP_TARGET" --default-toolchain none --profile minimal + +export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" +if [[ -n "${GITHUB_PATH:-}" ]]; then + printf '%s\n' "${CARGO_HOME:-$HOME/.cargo}/bin" >> "$GITHUB_PATH" +fi +rustup set auto-self-update disable + +actual_version="$(rustup --version | awk 'NR == 1 { print $2 }')" +if [[ "$actual_version" != "$RUSTUP_VERSION" ]]; then + echo "expected rustup ${RUSTUP_VERSION}, got ${actual_version:-unknown}" >&2 + exit 1 +fi + +if (( $# > 0 )); then + "$@" +fi -- 2.54.0 From 0b33cdeb778defa1e5e0d97271554a26ec212ab2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 09:07:47 +0200 Subject: [PATCH 56/58] test(ci): preserve coverage gate with pinned bootstrap snapshots --- scripts/test-changed-scope-coverage.py | 31 +++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/scripts/test-changed-scope-coverage.py b/scripts/test-changed-scope-coverage.py index 76f03821..d7fef7e8 100644 --- a/scripts/test-changed-scope-coverage.py +++ b/scripts/test-changed-scope-coverage.py @@ -10,7 +10,9 @@ import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -EXISTING_JOBS_SHA256 = "26cf64e51e207b9f81cef306e4ec31f3ed817334699e0b0fe7c7a031cb848a25" +# Reviewed snapshots from frozen infrastructure commit ac070fe2fa8bf0db9aa4f5fe627736c465e6e3e1. +EXISTING_JOBS_SHA256 = "4072554cb17e5afc49aba44a1ecbb5b71fa2d0bbf417512a432e3d519f16496b" +COVERAGE_JOB_SHA256 = "131cd1dc20e77f509137bf5db596466405899d6ed06c702869c46d72b79f38ea" PUSH_PULL_SHA256 = "cefb2858cd9b21076e171fa764dbf2df1472b911cc0743caa6fac7d09a216c89" SPEC = importlib.util.spec_from_file_location("changed_scope", ROOT / "scripts/check-changed-scope-coverage.py") COVERAGE = importlib.util.module_from_spec(SPEC) @@ -145,6 +147,9 @@ pub fn with_test_only_block() { current = (ROOT / ".github/workflows/linux.yml").read_text() original = subprocess.run(["git", "show", "HEAD:.github/workflows/linux.yml"], cwd=ROOT, capture_output=True, text=True, check=True).stdout + self._assert_workflow_contract(current, original) + + def _assert_workflow_contract(self, current: str, original: str) -> None: job_names = ("verify", "keyless-cuda", "hosted-cuda-package", "linux-static-cli", "linux-cli-container", "release-cli") self.assertEqual(_digest("".join(_job_block(current, name) for name in job_names)), @@ -156,6 +161,7 @@ pub fn with_test_only_block() { self.assertIn("changed_scope_coverage:\n description:", current) self.assertIn("type: boolean\n default: false", current) job = _job_block(current, "changed-scope-coverage") + self.assertEqual(_digest(job), COVERAGE_JOB_SHA256) self.assertIn("needs: verify", job) self.assertIn("runs-on: ubuntu-latest", job) self.assertNotIn("self-hosted", job) @@ -166,6 +172,29 @@ pub fn with_test_only_block() { self.assertNotIn("actions/upload-artifact", job) self.assertNotIn("download-artifact", job) + def test_workflow_rejects_restored_unchecked_installer_in_every_bootstrap_job(self) -> None: + current = (ROOT / ".github/workflows/linux.yml").read_text() + self._assert_workflow_contract(current, current) + unchecked_bootstrap = ( + " curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs " + "| sh -s -- -y --profile minimal --default-toolchain none\n" + ' echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"\n' + ' export PATH="$HOME/.cargo/bin:$PATH"\n' + " " + ) + for name in ("verify", "changed-scope-coverage", "hosted-cuda-package", + "linux-static-cli", "release-cli"): + with self.subTest(job=name): + block = _job_block(current, name) + self.assertEqual(block.count(" scripts/install-pinned-rustup.sh "), 1) + restored = block.replace(" scripts/install-pinned-rustup.sh ", + unchecked_bootstrap, 1) + mutated = current.replace(block, restored, 1) + # Matching HEAD cannot rescue a committed insecure bootstrap: the fixed + # reviewed snapshots must refuse it independently of that comparison. + with self.assertRaises(AssertionError): + self._assert_workflow_contract(mutated, mutated) + def _digest(value: str) -> str: import hashlib -- 2.54.0 From ba60abfa659da4d418e20e1d5363e468845607e2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 10:21:39 +0200 Subject: [PATCH 57/58] ci: pin Linux checkout action to verified v4 commit --- .github/workflows/linux.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 1cc2bacc..6fc53461 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -27,7 +27,7 @@ jobs: verify: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # The configured Gitea ubuntu-latest label runs a root node:24-bookworm job container; # sudo is not installed there, so install packages directly. - name: Install build tools @@ -46,7 +46,7 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: fetch-depth: 0 - name: Install parser runtime @@ -64,7 +64,7 @@ jobs: needs: verify runs-on: [self-hosted, linux, x64, strata-gpu] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - name: Query-routing, streaming and snapshot GPU tests run: scripts/check-keyless-gpu.sh - name: Bounded KAR expert component GPU tests @@ -84,7 +84,7 @@ jobs: CARGO_BUILD_JOBS: '2' CUDA_ARCHITECTURES: '120' steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - name: Install Docker and package tools (no drivers) run: | echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" @@ -182,7 +182,7 @@ jobs: needs: verify runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - name: Install musl toolchain run: apt-get update && apt-get install -y ca-certificates curl docker.io musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target @@ -346,7 +346,7 @@ jobs: needs: verify runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - name: Install the Docker CLI run: command -v docker >/dev/null 2>&1 || { apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io >/dev/null; } - name: Build actual CLI-only scratch image @@ -364,7 +364,7 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - name: Install release build tools run: apt-get update && apt-get install -y ca-certificates curl gh musl-tools cmake binutils python3-numpy - name: Install pinned Rust and target -- 2.54.0 From d099a3b3dad8301c7af8314370406860cfc12626 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 10:32:33 +0200 Subject: [PATCH 58/58] test(ci): enforce immutable checkout references in every Linux job --- scripts/test-changed-scope-coverage.py | 40 ++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/scripts/test-changed-scope-coverage.py b/scripts/test-changed-scope-coverage.py index d7fef7e8..36534963 100644 --- a/scripts/test-changed-scope-coverage.py +++ b/scripts/test-changed-scope-coverage.py @@ -10,9 +10,9 @@ import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -# Reviewed snapshots from frozen infrastructure commit ac070fe2fa8bf0db9aa4f5fe627736c465e6e3e1. -EXISTING_JOBS_SHA256 = "4072554cb17e5afc49aba44a1ecbb5b71fa2d0bbf417512a432e3d519f16496b" -COVERAGE_JOB_SHA256 = "131cd1dc20e77f509137bf5db596466405899d6ed06c702869c46d72b79f38ea" +# Reviewed snapshots from frozen infrastructure commit ba60abfa659da4d418e20e1d5363e468845607e2. +EXISTING_JOBS_SHA256 = "c61b2c03df92cb4027e6d1f666b9ff6f370e9a783ae44662674864db006b7b7f" +COVERAGE_JOB_SHA256 = "22081e16838b5b3d403db38d22753792bcf4d507ae363f7ae9e2c2a0e14f03c5" PUSH_PULL_SHA256 = "cefb2858cd9b21076e171fa764dbf2df1472b911cc0743caa6fac7d09a216c89" SPEC = importlib.util.spec_from_file_location("changed_scope", ROOT / "scripts/check-changed-scope-coverage.py") COVERAGE = importlib.util.module_from_spec(SPEC) @@ -150,6 +150,7 @@ pub fn with_test_only_block() { self._assert_workflow_contract(current, original) def _assert_workflow_contract(self, current: str, original: str) -> None: + self._assert_checkout_contract(current) job_names = ("verify", "keyless-cuda", "hosted-cuda-package", "linux-static-cli", "linux-cli-container", "release-cli") self.assertEqual(_digest("".join(_job_block(current, name) for name in job_names)), @@ -172,6 +173,39 @@ pub fn with_test_only_block() { self.assertNotIn("actions/upload-artifact", job) self.assertNotIn("download-artifact", job) + def _assert_checkout_contract(self, current: str) -> None: + expected = " - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262\n" + names = ("verify", "changed-scope-coverage", "keyless-cuda", "hosted-cuda-package", + "linux-static-cli", "linux-cli-container", "release-cli") + # This explicit allowlist is independent of both the subject and snapshot hashes. + self.assertEqual(current.count("actions/checkout@"), len(names)) + for name in names: + block = _job_block(current, name) + self.assertEqual(block.count("actions/checkout@"), 1, name) + self.assertEqual(block.count(expected), 1, name) + + def test_workflow_requires_seven_immutable_checkout_references(self) -> None: + current = (ROOT / ".github/workflows/linux.yml").read_text() + self._assert_checkout_contract(current) + + def test_workflow_rejects_mutable_checkout_references_in_every_job(self) -> None: + """[SEC][UC-104-CI01] Refuse mutable checkout tags/branches independently of hashes.""" + current = (ROOT / ".github/workflows/linux.yml").read_text() + self._assert_checkout_contract(current) + pinned = "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" + for name in ("verify", "changed-scope-coverage", "keyless-cuda", "hosted-cuda-package", + "linux-static-cli", "linux-cli-container", "release-cli"): + for mutable in ("v4", "v4.2.2", "main"): + with self.subTest(job=name, ref=mutable): + block = _job_block(current, name) + self.assertEqual(block.count(pinned), 1) + mutated = current.replace(block, block.replace(pinned, + f"actions/checkout@{mutable}", 1), 1) + # Exercise the semantic judge directly: no digest or HEAD mismatch + # is needed to reject any of the seven restored mutable callers. + with self.assertRaises(AssertionError): + self._assert_checkout_contract(mutated) + def test_workflow_rejects_restored_unchecked_installer_in_every_bootstrap_job(self) -> None: current = (ROOT / ".github/workflows/linux.yml").read_text() self._assert_workflow_contract(current, current) -- 2.54.0