feat(engine): extract Rust GGUF foundation and enforce model capability tuples

This commit is contained in:
Pavlo Ratushnyi
2026-10-07 20:33:15 +02:00
parent f015052247
commit c6a3fc7e42
11 changed files with 274 additions and 37 deletions
Generated
+8
View File
@@ -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",
+2 -2
View File
@@ -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"
+1
View File
@@ -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"
+1 -1
View File
@@ -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;
+182 -34
View File
@@ -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<String>,
pub supported_architectures: Vec<String>,
pub supported_weight_formats: Vec<String>,
/// Exact supported combinations. An empty list advertises no model support.
pub supported_models: Vec<SupportedModelTuple>,
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]
+13
View File
@@ -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
+45
View File
@@ -0,0 +1,45 @@
# 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 parser and its 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.
This crate does not yet provide an owned, immutable, digest-bound model-loader
handle. Full-artifact verification, descriptor/tensor/tokenizer binding, 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.
+7
View File
@@ -0,0 +1,7 @@
//! Backend-independent model-container inspection and indexing.
//!
//! This foundation exposes bounded GGUF metadata and byte geometry. It does
//! not implement dequantization, model loading, device allocation or inference.
//! Its only direct dependency is the Rust SHA-256 implementation in `sha2`.
pub mod gguf;
+11
View File
@@ -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.
+4
View File
@@ -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