Native runtime profile admission before pack preparation (#26)

* feat: validate declared native runtime geometry before preparation

* fix: preserve independent draft geometry for pruned targets
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 05:37:57 +02:00
committed by GitHub
parent 22de91c08f
commit a269656d22
8 changed files with 302 additions and 5 deletions
+2
View File
@@ -245,6 +245,8 @@ jobs:
run: python3 scripts/smoke-native-bootstrap.py control-plane/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
- name: Native runtime profile metadata admission
run: python3 scripts/smoke-runtime-profile.py control-plane/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
- name: Native installer with actual isolated systemd user service
+163
View File
@@ -52,6 +52,63 @@ pub struct TokenizerMetadata {
pub chat_template: String,
}
/// 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<()> {
let summary = inspect(path)?;
if summary.architecture.as_deref() != Some("qwen4exp") {
return Err("runtime_profile requires general.architecture=qwen4exp".into());
}
let required = [
("qwen4exp.block_count", Some(48)),
("qwen4exp.embedding_length", Some(2560)),
("qwen4exp.attention.head_count", Some(24)),
("qwen4exp.attention.head_count_kv", Some(2)),
("qwen4exp.expert_count", None),
("qwen4exp.expert_used_count", None),
];
let mut cursor = Cursor {
file: File::open(path)?,
size: summary.file_size,
};
cursor.skip(24)?;
let mut values = BTreeMap::new();
for _ in 0..summary.metadata {
let key = cursor.string()?;
let kind = cursor.u32()?;
if required.iter().any(|(name, _)| *name == key) {
if !matches!(kind, 0..=5 | 10 | 11) {
return Err(format!("runtime_profile: {key} must be an integer").into());
}
let value = cursor.integer(kind).map_err(|_| {
format!("runtime_profile: {key} must be a nonnegative 32-bit integer")
})?;
values.insert(key, value);
} else {
cursor.skip_value(kind)?;
}
}
for (key, expected) in required {
let value = *values
.get(key)
.ok_or_else(|| format!("runtime_profile: missing {key}"))?;
if value == 0 || value > i32::MAX as u32 {
return Err(format!("runtime_profile: {key} must be in 1..2147483647").into());
}
if let Some(expected) = expected
&& value != expected
{
return Err(format!("runtime_profile: {key}={value}, expected {expected}").into());
}
}
if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] {
return Err(
"runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into(),
);
}
Ok(())
}
/// Read only tokenizer fields after the complete GGUF header has passed inspection.
pub fn tokenizer_metadata(path: &Path) -> Result<TokenizerMetadata> {
inspect(path)?;
@@ -547,6 +604,112 @@ mod tests {
out.extend_from_slice(value.as_bytes());
}
#[test]
fn admits_flash_metadata_and_rejects_incompatible_profiles() {
let path = std::env::temp_dir().join(format!("strata-gguf-profile-{}", std::process::id()));
let fields = [
("qwen4exp.block_count", 48u32),
("qwen4exp.embedding_length", 2560),
("qwen4exp.attention.head_count", 24),
("qwen4exp.attention.head_count_kv", 2),
("qwen4exp.expert_count", 512),
("qwen4exp.expert_used_count", 10),
];
let write = |entries: Vec<(&str, u32, Vec<u8>)>| {
let mut data = b"GGUF".to_vec();
data.extend(3u32.to_le_bytes());
data.extend(0u64.to_le_bytes());
data.extend((entries.len() as u64 + 1).to_le_bytes());
string(&mut data, "general.architecture");
data.extend(8u32.to_le_bytes());
string(&mut data, "qwen4exp");
for (key, kind, bytes) in entries {
string(&mut data, key);
data.extend(kind.to_le_bytes());
data.extend(bytes);
}
data.resize(data.len().div_ceil(32) * 32, 0);
std::fs::write(&path, data).unwrap();
};
let good = || {
fields
.iter()
.map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec()))
.collect::<Vec<_>>()
};
write(good());
check_flash_next_profile(&path).unwrap();
for index in 0..fields.len() {
let mut entries = good();
entries.remove(index);
write(entries);
assert!(
check_flash_next_profile(&path)
.unwrap_err()
.to_string()
.contains(fields[index].0)
);
let mut entries = good();
entries[index].2 = 0u32.to_le_bytes().to_vec();
write(entries);
assert!(check_flash_next_profile(&path).is_err());
}
for index in 0..4 {
let mut entries = good();
entries[index].2 = (fields[index].1 + 1).to_le_bytes().to_vec();
write(entries);
assert!(
check_flash_next_profile(&path)
.unwrap_err()
.to_string()
.contains("expected")
);
}
for (kind, bytes) in [
(7, vec![1]),
(6, 48f32.to_le_bytes().to_vec()),
(5, (-1i32).to_le_bytes().to_vec()),
(10, (1u64 << 32).to_le_bytes().to_vec()),
] {
let mut entries = good();
entries[0] = (fields[0].0, kind, bytes);
write(entries);
assert!(
check_flash_next_profile(&path)
.unwrap_err()
.to_string()
.contains(fields[0].0)
);
}
let mut entries = good();
entries[4].2 = 256u32.to_le_bytes().to_vec();
write(entries);
check_flash_next_profile(&path).unwrap();
let mut entries = good();
entries[5].2 = 513u32.to_le_bytes().to_vec();
write(entries);
assert!(
check_flash_next_profile(&path)
.unwrap_err()
.to_string()
.contains("exceeds")
);
for kind in [0, 1, 2, 3, 4, 5, 10, 11] {
let mut entries = good();
let bytes = 48u64.to_le_bytes();
let n = match kind {
0 | 1 => 1,
2 | 3 => 2,
4 | 5 => 4,
_ => 8,
};
entries[0] = (fields[0].0, kind, bytes[..n].to_vec());
write(entries);
check_flash_next_profile(&path).unwrap();
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn inspects_header_and_rejects_truncated_payload() {
let mut gguf = b"GGUF".to_vec();
+12 -1
View File
@@ -27,12 +27,19 @@ const FILES: &[&str] = &[
"tokenizer/chat_template.jinja",
];
#[derive(Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum RuntimeProfile {
Qwen4expFlashNext,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeModel {
pub manifest: PathBuf,
pub source_dir: PathBuf,
pub output: PathBuf,
pub runtime_profile: Option<RuntimeProfile>,
}
impl NativeModel {
@@ -85,6 +92,10 @@ impl NativeModel {
directory: self.source_dir.clone(),
}])
.await?;
let primary = native_pack::primary_shard(&manifest, &self.source_dir)?;
if let Some(RuntimeProfile::Qwen4expFlashNext) = self.runtime_profile {
crate::gguf::check_flash_next_profile(&primary)?;
}
let parent = self.output.parent().ok_or("pack directory has no parent")?;
fs::create_dir_all(parent)?;
let mut name = std::ffi::OsString::from(".");
@@ -111,7 +122,7 @@ impl NativeModel {
}
Err(e) => return Err(e.into()),
}
native_pack::primary_shard(&manifest, &self.source_dir)
Ok(primary)
}
}
+2
View File
@@ -49,6 +49,8 @@ pub fn check(path: Option<&Path>) -> Result<serde_json::Value, &'static str> {
"engine": engine,
"tokenizer_validated": config.tokenizer_dir.is_some() && !tokenizer_pending,
"native_model_configured":config.native_model.is_some(),
"native_runtime_profile":config.native_model.as_ref().and_then(|native| native.runtime_profile),
"native_runtime_profile_checked":false,
"mtp_pack": if config.mtp_pack.is_some() { "pinned_structural_check_pending" } else { "unconfigured" },
"native_model_verified":false,
"inference_configured": config.worker.is_some() && config.tokenizer_dir.is_some() && !tokenizer_pending,
+19
View File
@@ -568,6 +568,25 @@ auxiliary pack with a separate pinned `assets` bundle and pass its explicit path
keep its directory disjoint from managed sources/output. The baseline can run
without optional MTP. Full-model and clean-node GPU qualification remain open.
For the current specialised engine, add
`"runtime_profile": "qwen4exp-flash-next"` inside `native_model`. After source
SHA verification and shard discovery, `provision`/`serve` check the first GGUF
shard **before pack preparation or output mutation**, including offline reuse.
The profile requires `qwen4exp` metadata with 48 blocks, hidden width 2560,
24 attention heads and 2 KV heads. Expert counts must be positive 32-bit signed
values and selected experts cannot exceed total experts; pruned counts remain
allowed with or without MTP. The engine uses an independent canonical draft
geometry for MTP, so its 512 experts need not match a pruned target. Missing, mistyped or incompatible fields identify the failing key.
Unknown profile names fail config validation; `check-config` reports the selected
`native_runtime_profile` and `native_runtime_profile_checked: false` without
reading model files or downloading anything.
Omitting the profile preserves generic exact preparation. The profile checks
metadata compatibility only: tensor layout/values, checkpoint pairing, memory
fit and actual GPU/model/MTP qualification remain separate checks. It does not
change generated bytes or enable compression. Rejected versioned sources remain
available for diagnosis, and existing prepared versions remain unchanged.
For the current Qwen3.8 Flash Next **Q2 MTP runtime layout**, set `mtp_pack` to
exactly one directory listed in `assets`:
+6 -2
View File
@@ -12,6 +12,7 @@ import re
import shutil
import socket
import subprocess
import struct
import sys
import tempfile
import threading
@@ -49,7 +50,10 @@ def main():
(source / 'dense.txt').write_text(good_index)
# Invalid pinned pack is deliberately tiny: verify no base-model fetch.
(source / 'experts.bin').write_bytes(b'invalid')
fixture.write_gguf(source / 'model.gguf', fixture.fixtures())
fixture.write_gguf(source / 'model.gguf', fixture.fixtures(), extra_fields=[
('qwen4exp.' + k, 4, struct.pack('<I', v)) for k, v in {
'block_count': 48, 'embedding_length': 2560, 'attention.head_count': 24,
'attention.head_count_kv': 2, 'expert_count': 256, 'expert_used_count': 10}.items()])
requests = []
class Source(http.server.BaseHTTPRequestHandler):
@@ -94,7 +98,7 @@ while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac; done
mtp = root / 'mtp-v1'
config = {'bind': f'127.0.0.1:{port}', 'mtp_pack': str(mtp),
'assets': [{'manifest': str(mtp_manifest), 'directory': str(mtp)}],
'native_model': {'manifest': str(model_manifest), 'source_dir': str(root / 'base'), 'output': str(root / 'pack')},
'native_model': {'manifest': str(model_manifest), 'source_dir': str(root / 'base'), 'output': str(root / 'pack'), 'runtime_profile': 'qwen4exp-flash-next'},
'engine': {'executable': str(worker), 'args': [str(marker)], 'startup_timeout_s': 5, 'max_restarts': 0}}
path = root / 'config.json'
env = {'PATH': os.defpath}
+2 -2
View File
@@ -21,8 +21,8 @@ def string(s):
return struct.pack('<Q', len(b)) + b
def write_gguf(path, tensors, split=None, architecture='qwen4exp', tokenizer=True):
fields = []
def write_gguf(path, tensors, split=None, architecture='qwen4exp', tokenizer=True, extra_fields=()):
fields = list(extra_fields)
if architecture:
fields.append(('general.architecture', 8, string(architecture)))
if split is not None:
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Actual verified-GGUF provisioning; metadata admission only, synthetic CPU tensors."""
import hashlib
import http.server
import importlib.util
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import threading
def main():
binary = str(Path(sys.argv[1]).resolve())
spec = importlib.util.spec_from_file_location('pack_fixture', Path(__file__).with_name('smoke-native-pack.py'))
fixture = importlib.util.module_from_spec(spec); spec.loader.exec_module(fixture)
expected = {'block_count': 48, 'embedding_length': 2560, 'attention.head_count': 24,
'attention.head_count_kv': 2, 'expert_count': 512, 'expert_used_count': 10}
with tempfile.TemporaryDirectory(prefix='strata-runtime-profile-') as tmp:
root = Path(tmp).resolve(); source = root / 'http'; source.mkdir()
requests = []
class Source(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(source), **kwargs)
def log_message(self, *_): pass
def do_GET(self):
requests.append(self.path); super().do_GET()
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Source)
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
marker = root / 'started'
worker = root / 'worker.sh'
worker.write_text(f'#!/bin/sh\ntouch "{marker}"\nexit 1\n'); worker.chmod(0o700)
manifest = root / 'manifest.json'; config_path = root / 'config.json'
config = {'native_model': {'manifest': str(manifest), 'source_dir': str(root/'base'),
'output': str(root/'pack'), 'runtime_profile': 'qwen4exp-flash-next'},
'engine': {'executable': str(worker), 'max_restarts': 0}}
def publish(values, kind=4):
fields = [('qwen4exp.'+key, kind, struct.pack('<I', val)) for key,val in values.items()]
fixture.write_gguf(source/'model.gguf', fixture.fixtures(), extra_fields=fields)
data = (source/'model.gguf').read_bytes()
manifest.write_text(json.dumps({'schema_version': 1, 'files': [{'name': 'model.gguf',
'url': f'http://127.0.0.1:{server.server_port}/model.gguf',
'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}]}))
def run(cmd='provision', ok=True):
config_path.write_text(json.dumps(config))
r = subprocess.run([binary, cmd, '--config', str(config_path)], capture_output=True, timeout=30, env={'PATH': os.defpath})
assert (r.returncode == 0) == ok, (r.stdout, r.stderr)
return r
try:
publish(expected)
check = json.loads(run('check-config').stdout)
assert check['native_runtime_profile'] == 'qwen4exp-flash-next' and not check['native_runtime_profile_checked']
assert not requests and not (root/'base').exists()
config['native_model']['runtime_profile'] = 'unsupported'; run('check-config', ok=False)
assert not requests
config['native_model']['runtime_profile'] = 'qwen4exp-flash-next'
run(); assert requests == ['/model.gguf'] and not marker.exists()
receipt = (root/'pack/receipt.json').read_bytes()
original = {p.relative_to(root/'pack'):p.read_bytes() for p in (root/'pack').rglob('*') if p.is_file()}
# A validation-only profile must leave every generated byte unchanged.
config['native_model'].pop('runtime_profile'); config['native_model']['output'] = str(root/'baseline')
run(); assert requests == ['/model.gguf']
assert original == {p.relative_to(root/'baseline'):p.read_bytes() for p in (root/'baseline').rglob('*') if p.is_file()}
config['native_model']['runtime_profile'] = 'qwen4exp-flash-next'
for i, values in enumerate([{**expected, 'embedding_length': 1280},
{k:v for k,v in expected.items() if k!='block_count'},
{**expected, 'expert_used_count': 513}]):
publish(values)
config['native_model']['source_dir'] = str(root/f'bad-base-{i}')
config['native_model']['output'] = str(root/f'bad-pack-{i}')
r = run('serve', ok=False)
assert b'runtime_profile' in r.stderr
assert not (root/f'bad-pack-{i}').exists() and not (root/f'.bad-pack-{i}.native-model-lock').exists()
assert (root/'pack/receipt.json').read_bytes() == receipt and not marker.exists()
# Existing output created by the generic converter must be rechecked too.
config['native_model'].pop('runtime_profile')
run(); prior = (root/'bad-pack-2/receipt.json').read_bytes()
config['native_model']['runtime_profile'] = 'qwen4exp-flash-next'
assert b'exceeds' in run('serve', ok=False).stderr
assert (root/'bad-pack-2/receipt.json').read_bytes() == prior and not marker.exists()
# Pruned expert count is permitted without MTP, matching the engine guard.
publish({**expected, 'expert_count':256})
config['native_model']['source_dir'] = str(root/'pruned-base')
config['native_model']['output'] = str(root/'pruned-pack')
run(); n = len(requests)
server.shutdown(); server.server_close(); thread.join()
run(); assert len(requests) == n and not marker.exists()
finally:
if thread.is_alive(): server.shutdown(); server.server_close(); thread.join()
print('runtime profile passed: read-only unknown-profile rejection; verified HTTP source metadata faults before output/worker; previous version preserved; exact generated-file equality tolerance0; pruned/offline acceptance. Synthetic tensor geometry/values, no GPU or model quality qualification.')
if __name__ == '__main__': main()