diff --git a/Cargo.lock b/Cargo.lock index f8d3729d..071adc05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1007,6 +1007,13 @@ dependencies = [ name = "leleka-backend-api" version = "0.1.0" +[[package]] +name = "leleka-model-format" +version = "0.1.0" +dependencies = [ + "sha2", +] + [[package]] name = "leleka-tokenizer" version = "0.1.0" @@ -2005,6 +2012,7 @@ dependencies = [ "http-body", "http-body-util", "jsonschema", + "leleka-model-format", "leleka-tokenizer", "libc", "regex", diff --git a/Cargo.toml b/Cargo.toml index 5a15d9d5..582be906 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/tokenizer", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/tokenizer", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index f293001b..4a5fd3f3 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -14,6 +14,7 @@ axum = "0.8" futures-core = "0.3" hex = "0.4" leleka-tokenizer = { path = "../crates/tokenizer" } +leleka-model-format = { path = "../crates/model-format" } http-body = "1" jsonschema = { version = "0.58.4", default-features = false } libc = "0.2" diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 97965c3c..fc902384 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -10,7 +10,7 @@ pub mod embedded_engine; mod embedded_spec; pub mod engine_probe; pub mod ggml_bridge; -pub mod gguf; +pub use leleka_model_format::gguf; pub mod gguf_f32_stream; mod history_store; mod immutable_directory; diff --git a/crates/backend-api/src/lib.rs b/crates/backend-api/src/lib.rs index 64f3e85a..73672bee 100644 --- a/crates/backend-api/src/lib.rs +++ b/crates/backend-api/src/lib.rs @@ -8,7 +8,9 @@ use std::sync::Mutex; use std::sync::mpsc::{self, Receiver, RecvError, SendError, Sender}; /// Version understood by this crate and advertised in [`BackendIdentity`]. -pub const BACKEND_API_VERSION: u16 = 1; +// Version 2 replaces independent capability axes with explicit model tuples. +// Version 1 identities must be refused rather than reinterpreted as version 2. +pub const BACKEND_API_VERSION: u16 = 2; #[derive(Clone, Debug, Eq, PartialEq)] pub struct BackendIdentity { @@ -42,7 +44,11 @@ impl ModelDescriptor { ("architecture", self.architecture.as_str()), ("weight_format", self.weight_format.as_str()), ] { - if value.trim().is_empty() { + if value.is_empty() + || value + .chars() + .any(|ch| ch.is_whitespace() || ch.is_control()) + { return Err(ContractError::InvalidField(field)); } } @@ -56,27 +62,38 @@ impl ModelDescriptor { } } +/// One explicitly supported family, architecture and weight format combination. +/// +/// Advertising two tuples does not advertise any combination of their fields. +/// An artifact digest is supplied by the descriptor and verified during loading. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SupportedModelTuple { + pub family: String, + pub architecture: String, + pub weight_format: String, +} + #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct BackendCapabilities { - pub supported_families: Vec, - pub supported_architectures: Vec, - pub supported_weight_formats: Vec, + /// Exact supported combinations. An empty list advertises no model support. + pub supported_models: Vec, pub max_concurrent_generations: usize, pub supports_cancellation: bool, pub supports_tool_call_streaming: bool, } impl BackendCapabilities { + /// Refuse malformed descriptors and combinations not explicitly advertised. + /// + /// This checks declared compatibility only; it does not verify artifact bytes + /// or admit memory, concurrency, hardware, or an experimental runtime mode. pub fn supports(&self, model: &ModelDescriptor) -> bool { - self.supported_families.iter().any(|v| v == &model.family) - && self - .supported_architectures - .iter() - .any(|v| v == &model.architecture) - && self - .supported_weight_formats - .iter() - .any(|v| v == &model.weight_format) + model.validate().is_ok() + && self.supported_models.iter().any(|supported| { + supported.family == model.family + && supported.architecture == model.architecture + && supported.weight_format == model.weight_format + }) } } @@ -179,8 +196,8 @@ impl fmt::Display for ContractError { impl std::error::Error for ContractError {} -/// Implemented by runtime backends. A backend must not claim a model family or -/// format until it can load and serve it with the declared semantics. +/// Implemented by runtime backends. A backend must not advertise a model tuple +/// until it can load and serve that combination with the declared semantics. pub trait Backend: Send { fn identity(&self) -> BackendIdentity; fn capabilities(&self) -> BackendCapabilities; @@ -321,10 +338,10 @@ mod tests { fn model() -> ModelDescriptor { ModelDescriptor { - family: "qwen3_moe".into(), - architecture: "qwen3_moe_v1".into(), + family: "fixture_alpha".into(), + architecture: "fixture_arch_a".into(), artifact_digest: format!("sha256:{}", "a".repeat(64)), - weight_format: "gguf:iq3_s".into(), + weight_format: "fixture:format_a".into(), } } @@ -339,20 +356,148 @@ mod tests { ); } - #[test] - fn capabilities_match_family_architecture_and_format_together() { - let capabilities = BackendCapabilities { - supported_families: vec!["qwen3_moe".into()], - supported_architectures: vec!["qwen3_moe_v1".into()], - supported_weight_formats: vec!["gguf:iq3_s".into()], + fn capabilities() -> BackendCapabilities { + BackendCapabilities { + supported_models: vec![ + SupportedModelTuple { + family: "fixture_alpha".into(), + architecture: "fixture_arch_a".into(), + weight_format: "fixture:format_a".into(), + }, + SupportedModelTuple { + family: "fixture_beta".into(), + architecture: "fixture_arch_b".into(), + weight_format: "fixture:format_b".into(), + }, + ], max_concurrent_generations: 2, supports_cancellation: true, supports_tool_call_streaming: true, + } + } + + #[test] + fn capabilities_admit_only_explicit_tuples_not_their_cartesian_product() { + let capabilities = capabilities(); + let mut admitted = 0; + for family in ["fixture_alpha", "fixture_beta"] { + for architecture in ["fixture_arch_a", "fixture_arch_b"] { + for weight_format in ["fixture:format_a", "fixture:format_b"] { + let descriptor = ModelDescriptor { + family: family.into(), + architecture: architecture.into(), + weight_format: weight_format.into(), + ..model() + }; + let expected = matches!( + (family, architecture, weight_format), + ("fixture_alpha", "fixture_arch_a", "fixture:format_a") + | ("fixture_beta", "fixture_arch_b", "fixture:format_b") + ); + let actual = capabilities.supports(&descriptor); + assert_eq!(actual, expected, "{descriptor:?}"); + admitted += usize::from(actual); + } + } + } + assert_eq!(admitted, 2); + for unknown in [ + ModelDescriptor { + family: "fixture_unknown".into(), + ..model() + }, + ModelDescriptor { + architecture: "fixture_arch_unknown".into(), + ..model() + }, + ModelDescriptor { + weight_format: "fixture:unknown".into(), + ..model() + }, + ] { + assert!(!capabilities.supports(&unknown)); + } + } + + #[test] + fn empty_capabilities_advertise_no_models() { + assert!(!BackendCapabilities::default().supports(&model())); + let empty = BackendCapabilities { + supported_models: Vec::new(), + ..capabilities() }; - assert!(capabilities.supports(&model())); - let mut unsupported = model(); - unsupported.weight_format = "gguf:unknown".into(); - assert!(!capabilities.supports(&unsupported)); + assert!(!empty.supports(&model())); + } + + #[test] + fn invalid_digests_are_refused_even_for_an_explicit_tuple() { + for digest in [ + String::new(), + "sha256:abc".into(), + format!("sha256:{}", "a".repeat(63)), + format!("sha256:{}", "a".repeat(65)), + format!("sha256:{}", "z".repeat(64)), + format!("SHA256:{}", "a".repeat(64)), + format!("sha256:{} ", "a".repeat(64)), + ] { + let descriptor = ModelDescriptor { + artifact_digest: digest, + ..model() + }; + assert_eq!( + descriptor.validate(), + Err(ContractError::InvalidField("artifact_digest")) + ); + assert!(!capabilities().supports(&descriptor)); + } + } + + #[test] + fn malformed_fields_cannot_be_admitted_even_if_a_backend_lists_them() { + for invalid in [ + "", + " ", + "fixture alpha", + " fixture", + "fixture ", + "fixture\n", + "fixture\0", + ] { + for field in ["family", "architecture", "weight_format"] { + let mut descriptor = model(); + let mut capabilities = capabilities(); + let supported = &mut capabilities.supported_models[0]; + match field { + "family" => { + descriptor.family = invalid.into(); + supported.family = invalid.into(); + } + "architecture" => { + descriptor.architecture = invalid.into(); + supported.architecture = invalid.into(); + } + "weight_format" => { + descriptor.weight_format = invalid.into(); + supported.weight_format = invalid.into(); + } + _ => unreachable!(), + } + assert_eq!( + descriptor.validate(), + Err(ContractError::InvalidField(field)) + ); + assert!(!capabilities.supports(&descriptor), "{field}: {invalid:?}"); + } + } + } + + #[test] + fn supported_tuple_does_not_pin_or_verify_artifact_bytes() { + let descriptor = ModelDescriptor { + artifact_digest: format!("sha256:{}", "b".repeat(64)), + ..model() + }; + assert!(capabilities().supports(&descriptor)); } #[test] @@ -363,11 +508,14 @@ mod tests { api_version: BACKEND_API_VERSION, }; assert!(current.supports_current_api()); - let older = BackendIdentity { - api_version: 0, - ..current - }; - assert!(!older.supports_current_api()); + assert_eq!(BACKEND_API_VERSION, 2); + for api_version in [0, 1, 3, u16::MAX] { + let incompatible = BackendIdentity { + api_version, + ..current.clone() + }; + assert!(!incompatible.supports_current_api()); + } } #[test] diff --git a/crates/model-format/Cargo.toml b/crates/model-format/Cargo.toml new file mode 100644 index 00000000..4ae52fb7 --- /dev/null +++ b/crates/model-format/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "leleka-model-format" +version = "0.1.0" +description = "Bounded native GGUF metadata and tensor indexing for Leleka" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +sha2 = "0.11" + +[lints] +workspace = true diff --git a/crates/model-format/README.md b/crates/model-format/README.md new file mode 100644 index 00000000..8dc5e721 --- /dev/null +++ b/crates/model-format/README.md @@ -0,0 +1,76 @@ +# Leleka model format foundation + +`leleka-model-format` exposes the existing bounded GGUF v3 parser as an +independent Rust crate. It depends directly on `sha2` and the standard library; +it has no build script, C/FFI shim, GGML, Strata process/source link, CUDA or +Python dependency. The existing control plane reexports its `gguf` module, so +preparation, inspection, tokenizer extraction and tensor-export consumers keep +their public paths. + +The original parser geometry and its three tests were moved unchanged from `control-plane/src/gguf.rs`. +Tensor block geometry and the legacy Flash-Next metadata guard retain their +upstream references; see [the provenance record](../../docs/upstream.md). +Those helpers inspect metadata and byte layout, not tensor values or inference. +Recognizing a quantization block size is not support for decoding or serving it. + +## Contract and limits + +- `inspect` validates GGUF v3 header structure and reports metadata/layout. +- `tensor_index` additionally requires known block geometry, checked dimensions, + alignment, bounded nonoverlapping tensor spans and consistent file bounds. +- `tensor_sha256` hashes one indexed tensor through a fixed 1 MiB buffer. +- `tokenizer_metadata` extracts the existing Qwen35 tokenizer fields after + header inspection; the separate tokenizer crate implements tokenization. +- `check_flash_next_profile` is the existing specialized metadata admission + check. It does not validate a complete model, tokenizer or numerical output. + +All preexisting bounds/rejections remain unchanged. Path-based functions reopen +the source; callers must keep the verified file stable between inspection and +reading. File length checks do not detect same-size replacement or mutation. +`VerifiedGgufFile::open` is a separate owned-file API: it accepts a +`sha256:<64 hex digits>` artifact digest, opens one regular file, hashes the full +file with a buffer of at most 64 KiB, and parses the strict tensor index through +that same handle. The private file/index pair is retained; `index()` offers only +an immutable borrow. `stream_tensor` validates a requested tensor number and +byte range before delivering at most 64 KiB per callback, and `tensor_sha256` +hashes the indexed payload through that stream. Neither tensor operation reopens +the pathname or allocates the full tensor. A consumer may explicitly collect +chunks or return an I/O error to abort. Empty ranges at the tensor end are valid. + +Renaming or replacing the original pathname after opening does not redirect this +handle to a different file. The preliminary path metadata check rejects ordinary +nonregular paths; the opened-file metadata check determines whether the accepted +handle is regular. This does not make pathname lookup atomic against a malicious +concurrent substitution during opening. The caller must supply a stable regular +source for opening and prevent **in-place writes for the entire verification, +indexing and read lifetime**. Keeping a file descriptor does not make its bytes +immutable: even same-size writes to the same file remain visible and are not +caught by file length checks. The stored artifact digest records verification at +open, not a later content attestation. Size changes are refused before/after +streaming, and short reads propagate errors; callbacks already delivered before +an I/O failure cannot be retracted. + +The existing path APIs and tensor geometry remain unchanged. Descriptor, tensor +and tokenizer semantics, memory admission, GPU allocation, readiness and +real-model parity remain separate work. +The current `strata-control` still has its legacy GGML/build dependencies; +extracting this crate does not remove them from that package or its runtime. + +## Standalone checks + +```sh +cargo test --locked -p leleka-model-format +cargo clippy --locked -p leleka-model-format --all-targets -- -D warnings +cargo tree --locked -p leleka-model-format +``` + +These are container/parser checks with sanitized synthetic bytes. They do not +establish inference, model quality, GPU operation or performance. + +Owned-file tests use generated synthetic GGUF bytes: full-digest and tensor-byte +oracles, multi-chunk and partial streaming, malformed digest, nonregular source, +tamper, truncate, unsupported version/type and overlapping geometry rejection, +range/overflow checks before callbacks, callback abort/recovery, Unix pathname +replacement retaining the original file, and an explicit same-size in-place +mutation counterexample. These tests do not qualify an immutable artifact store +or a complete model loader. diff --git a/control-plane/src/gguf.rs b/crates/model-format/src/gguf.rs similarity index 64% rename from control-plane/src/gguf.rs rename to crates/model-format/src/gguf.rs index ec052e4b..ac8c727c 100644 --- a/control-plane/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -52,6 +52,164 @@ pub struct TokenizerMetadata { pub chat_template: String, } +/// An owned GGUF file whose complete bytes matched the declared digest at open. +/// +/// The private file and index stay paired across pathname replacements. This is +/// not an immutable snapshot: callers must prevent in-place writes for the whole +/// verification, indexing and reading lifetime. Size checks cannot prove that. +#[derive(Debug)] +pub struct VerifiedGgufFile { + file: File, + index: TensorIndex, + artifact_sha256: [u8; 32], +} + +const STREAM_BUFFER_BYTES: usize = 64 * 1024; + +impl VerifiedGgufFile { + /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. + /// The opened file's contents must remain stable until this handle is dropped. + pub fn open(path: &Path, expected_digest: &str) -> Result { + let expected = parse_artifact_digest(expected_digest)?; + // Refuse an ordinary nonregular path before opening it (notably FIFOs). + // The opened-file check below is authoritative for the accepted source. + if !std::fs::metadata(path)?.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let mut file = File::open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let size = metadata.len(); + let mut digest = Sha256::new(); + stream_file_span(&mut file, 0, size, |chunk| { + digest.update(chunk); + Ok(()) + })?; + let actual: [u8; 32] = digest.finalize().into(); + if actual != expected { + return Err("GGUF artifact SHA256 mismatch".into()); + } + if file.metadata()?.len() != size { + return Err("GGUF source size changed during verification".into()); + } + let index = read_index_file(&mut file, size, true)?; + if file.metadata()?.len() != size { + return Err("GGUF source size changed during indexing".into()); + } + Ok(Self { + file, + index, + artifact_sha256: actual, + }) + } + + pub fn index(&self) -> &TensorIndex { + &self.index + } + + /// Digest verified when opening, not a promise of later source immutability. + pub fn artifact_sha256(&self) -> [u8; 32] { + self.artifact_sha256 + } + + /// Stream an exact byte range within an indexed tensor through a buffer of + /// at most 64 KiB. The consumer may return an I/O error to abort the stream. + /// No pathname is reopened; all range checks precede the first callback. + pub fn stream_tensor( + &mut self, + tensor_number: usize, + offset: u64, + bytes: u64, + consume: impl FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<()> { + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 + || offset + .checked_add(bytes) + .is_none_or(|end| end > tensor.bytes) + { + return Err("GGUF tensor byte range is out of bounds".into()); + } + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(offset)) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(bytes) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + self.check_size()?; + stream_file_span(&mut self.file, absolute, bytes, consume)?; + self.check_size() + } + + /// Hash the complete indexed tensor without allocating its full payload. + pub fn tensor_sha256(&mut self, tensor_number: usize) -> Result<[u8; 32]> { + let bytes = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")? + .bytes; + let mut digest = Sha256::new(); + self.stream_tensor(tensor_number, 0, bytes, |chunk| { + digest.update(chunk); + Ok(()) + })?; + Ok(digest.finalize().into()) + } + + fn check_size(&self) -> Result<()> { + if self.file.metadata()?.len() != self.index.summary.file_size { + return Err("GGUF source size changed after verification".into()); + } + Ok(()) + } +} + +fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> { + let hex = value + .strip_prefix("sha256:") + .ok_or("invalid GGUF artifact digest")?; + if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err("invalid GGUF artifact digest".into()); + } + let mut digest = [0u8; 32]; + for (index, byte) in digest.iter_mut().enumerate() { + *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)?; + } + Ok(digest) +} + +fn stream_file_span( + file: &mut File, + absolute: u64, + bytes: u64, + mut consume: impl FnMut(&[u8]) -> std::io::Result<()>, +) -> Result<()> { + file.seek(SeekFrom::Start(absolute))?; + let mut buffer = vec![0u8; bytes.min(STREAM_BUFFER_BYTES as u64) as usize]; + let mut remaining = bytes; + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..count])?; + consume(&buffer[..count])?; + remaining -= count as u64; + } + Ok(()) +} + /// Metadata admission for the specialised engine, before expensive preparation. /// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. pub fn check_flash_next_profile(path: &Path) -> Result<()> { @@ -240,8 +398,13 @@ pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> } fn read_index(path: &Path, strict: bool) -> Result { - let file = File::open(path)?; + let mut file = File::open(path)?; let size = file.metadata()?.len(); + read_index_file(&mut file, size, strict) +} + +fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result { + file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor { file, size }; if cursor.take(4)? != b"GGUF" { return Err("not a GGUF file".into()); @@ -431,12 +594,12 @@ pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { }) } -struct Cursor { - file: File, +struct Cursor { + file: R, size: u64, } -impl Cursor { +impl Cursor { fn position(&mut self) -> Result { Ok(self.file.stream_position()?) } @@ -784,4 +947,274 @@ mod tests { assert!(tensor_index(&path).is_err()); std::fs::remove_file(path).unwrap(); } + + struct OwnedFixture { + directory: std::path::PathBuf, + path: std::path::PathBuf, + bytes: Vec, + small: Vec, + large: Vec, + kind_at: usize, + offset_at: usize, + } + + impl OwnedFixture { + fn new() -> Self { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let directory = std::env::temp_dir().join(format!( + "leleka-owned-gguf-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&directory).unwrap(); + let path = directory.join("fixture.gguf"); + let small = (0..16).collect::>(); + let large = (0..STREAM_BUFFER_BYTES * 3 + 11) + .map(|at| (at % 251) as u8) + .collect::>(); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend(2u64.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "fixture.small"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(4u64.to_le_bytes()); + bytes.extend(0u32.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "fixture.large"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend((large.len() as u64).to_le_bytes()); + let kind_at = bytes.len(); + bytes.extend(24u32.to_le_bytes()); + let offset_at = bytes.len(); + bytes.extend(32u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(&small); + bytes.extend([0u8; 16]); + bytes.extend(&large); + std::fs::write(&path, &bytes).unwrap(); + Self { + directory, + path, + bytes, + small, + large, + kind_at, + offset_at, + } + } + + fn digest(&self) -> String { + let hex = Sha256::digest(&self.bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + format!("sha256:{hex}") + } + } + + impl Drop for OwnedFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.directory); + } + } + + #[test] + fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + assert_eq!(source.index().tensors.len(), 2); + assert_eq!(source.index().tensors[1].bytes, fixture.large.len() as u64); + for (number, expected) in [(0, &fixture.small), (1, &fixture.large)] { + assert_eq!( + source.tensor_sha256(number).unwrap(), + <[u8; 32]>::from(Sha256::digest(expected)) + ); + } + let mut seen = 0; + let mut callbacks = 0; + source + .stream_tensor(1, 0, fixture.large.len() as u64, |chunk| { + assert!(!chunk.is_empty() && chunk.len() <= STREAM_BUFFER_BYTES); + assert_eq!(chunk, &fixture.large[seen..seen + chunk.len()]); + seen += chunk.len(); + callbacks += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(seen, fixture.large.len()); + assert_eq!(callbacks, 4); + let mut partial = Vec::new(); + source + .stream_tensor(1, 7, 13, |chunk| { + partial.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(partial, fixture.large[7..20]); + } + + #[test] + fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() { + let fixture = OwnedFixture::new(); + for digest in [ + "", + "abc", + "sha256:abc", + &format!("sha256:{}", "g".repeat(64)), + &format!("SHA256:{}", "a".repeat(64)), + ] { + assert!( + VerifiedGgufFile::open(&fixture.path, digest) + .unwrap_err() + .to_string() + .contains("invalid GGUF artifact digest") + ); + } + assert!( + VerifiedGgufFile::open(&fixture.directory, &fixture.digest()) + .unwrap_err() + .to_string() + .contains("regular file") + ); + let mut tampered = fixture.bytes.clone(); + *tampered.last_mut().unwrap() ^= 1; + std::fs::write(&fixture.path, tampered).unwrap(); + assert!( + VerifiedGgufFile::open(&fixture.path, &fixture.digest()) + .unwrap_err() + .to_string() + .contains("SHA256 mismatch") + ); + } + + #[test] + fn owned_handle_rejects_truncated_unsupported_and_bad_geometry_even_with_matching_digest() { + let mut fixture = OwnedFixture::new(); + let original = fixture.bytes.clone(); + for fault in 0..4 { + fixture.bytes = original.clone(); + match fault { + 0 => { + fixture.bytes.pop(); + } + 1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4] + .copy_from_slice(&u32::MAX.to_le_bytes()), + 2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8] + .copy_from_slice(&0u64.to_le_bytes()), + 3 => fixture.bytes[4..8].copy_from_slice(&2u32.to_le_bytes()), + _ => unreachable!(), + } + std::fs::write(&fixture.path, &fixture.bytes).unwrap(); + assert!( + VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(), + "fault {fault}" + ); + } + } + + #[test] + fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + for (number, offset, bytes) in [ + (2, 0, 1), + (0, 0, 17), + (0, 17, 0), + (0, u64::MAX, 1), + (0, 1, u64::MAX), + ] { + let mut called = false; + assert!( + source + .stream_tensor(number, offset, bytes, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } + source + .stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer")) + .unwrap(); + assert!( + source + .stream_tensor(1, 0, 10, |_| Err(std::io::Error::other( + "synthetic consumer failure" + ))) + .unwrap_err() + .to_string() + .contains("synthetic consumer failure") + ); + assert_eq!( + source.tensor_sha256(0).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.small)) + ); + } + + #[cfg(unix)] + #[test] + fn pathname_replacement_keeps_original_verified_file_and_index() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + std::fs::rename(&fixture.path, fixture.directory.join("original.gguf")).unwrap(); + std::fs::write(&fixture.path, b"replacement is not a GGUF file").unwrap(); + assert!(tensor_index(&fixture.path).is_err()); + assert_eq!( + source.tensor_sha256(1).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.large)) + ); + let mut small = Vec::new(); + source + .stream_tensor(0, 0, 16, |chunk| { + small.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(small, fixture.small); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + } + + #[test] + fn opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + let mut mutated = fixture.bytes.clone(); + *mutated.last_mut().unwrap() ^= 1; + std::fs::write(&fixture.path, &mutated).unwrap(); + // Explicit counterexample: retaining the descriptor does not freeze bytes. + assert_ne!( + source.tensor_sha256(1).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.large)) + ); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + std::fs::OpenOptions::new() + .write(true) + .open(&fixture.path) + .unwrap() + .set_len(0) + .unwrap(); + let mut called = false; + assert!( + source + .stream_tensor(0, 0, 16, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } } diff --git a/crates/model-format/src/lib.rs b/crates/model-format/src/lib.rs new file mode 100644 index 00000000..b954b632 --- /dev/null +++ b/crates/model-format/src/lib.rs @@ -0,0 +1,9 @@ +//! Backend-independent model-container inspection and indexing. +//! +//! This foundation exposes bounded GGUF metadata and byte geometry. It does +//! not implement dequantization, complete model loading, device allocation or inference. +//! The owned GGUF reader binds digest verification and indexing to one open file; +//! callers must keep that file's contents stable throughout its lifetime. +//! Its only direct dependency is the Rust SHA-256 implementation in `sha2`. + +pub mod gguf; diff --git a/docs/backend-capability-admission.md b/docs/backend-capability-admission.md new file mode 100644 index 00000000..d4755e1f --- /dev/null +++ b/docs/backend-capability-admission.md @@ -0,0 +1,11 @@ +# Backend capability admission + +The `leleka-backend-api` contract at API version 2 describes supported models as explicit `SupportedModelTuple` entries in `BackendCapabilities.supported_models`. Each entry binds family, architecture and weight format together. Entries do not imply combinations assembled from different entries, and the default empty list supports no models. + +`supports` first validates the descriptor: identifiers must be nonempty and contain no whitespace or control characters, and the artifact digest must use the existing `sha256:` prefix with exactly 64 hexadecimal characters. It then requires one exact declared tuple. Matching is case-sensitive for tuple identifiers, with no wildcard, alias or family inference. + +The public capability layout replaces the version 1 independent lists. `BACKEND_API_VERSION` advances from 1 to 2, and `BackendIdentity::supports_current_api` rejects version 1 identities. A backend must migrate its declarations to explicit combinations; generating their Cartesian product would recreate the old admission bug. This is a Rust scaffold contract, not a stable dynamic plugin ABI or serialized protocol. The crate package version remains controlled separately by repository release policy; no backend consumer or production model declaration currently uses this scaffold. + +Compatibility declaration is only one load prerequisite. `supports` does not read or hash model bytes, validate tensors or a tokenizer, check hardware, reserve memory/concurrency, qualify experimental modes, or publish readiness. Backend implementations must perform those checks before loading succeeds. A declared tuple is a backend assertion, not proof that a real model works. + +Tests use two synthetic declared tuples and independently enumerate all eight combinations: only the two explicit entries are admitted. They also cover unknown formats, empty capabilities, malformed identifiers even when explicitly advertised, invalid digests, and refusal of obsolete/future API versions. No real family support, inference quality, numerical result or performance claim is introduced. diff --git a/scripts/check-local.sh b/scripts/check-local.sh index a28be2fc..9d6f5675 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -17,6 +17,10 @@ python3 "${repo_root}/scripts/test-runtime-image.py" python3 "${repo_root}/scripts/test-gitea-release.py" python3 "${repo_root}/scripts/test-keyless-routing.py" +cargo fmt --manifest-path "${repo_root}/crates/model-format/Cargo.toml" --check +cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets -- -D warnings +cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format +cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-backend-api cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked