Files
leleka/control-plane/src/native_model.rs
T

325 lines
10 KiB
Rust

//! Config-driven immutable GGUF acquisition, exact preparation and offline reuse.
use crate::{
asset_bundle::{self, AssetBundle},
model, native_pack,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
fs::{self, File, OpenOptions},
io::Read,
path::{Path, PathBuf},
};
type Result<T> = std::result::Result<T, crate::BoxError>;
const FILES: &[&str] = &[
"dense.bin",
"index.txt",
"native_experts.txt",
"conversions.json",
"source.json",
"tokenizer/vocab.json",
"tokenizer/merges.txt",
"tokenizer/token_type.json",
"tokenizer/tokenizer.json",
"tokenizer/chat_template.jinja",
];
/// Files only the opt-in `iq_pack.py` modes write (`--compat-bf16`, `--base`, `--experts-bin`). A receipt lists the
/// ones present; the default pack has none.
const OPTIONAL_FILES: &[&str] = &[
"compat-bf16.json",
"extra.bin",
"experts.bin",
"experts.bin.src.json",
];
#[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>,
}
/// The manifest itself must survive publication and cannot live in a generated tree.
fn check_manifests_outside(all: &[AssetBundle], directories: &[PathBuf]) -> Result<()> {
for asset in all {
let manifest = resolved(&asset.manifest)?;
if directories
.iter()
.any(|directory| manifest.starts_with(directory))
{
return Err("asset manifests must be outside generated directories".into());
}
}
Ok(())
}
/// No directory contains another, after every filesystem alias has been resolved.
fn check_no_overlap(directories: &[PathBuf]) -> Result<()> {
for (i, directory) in directories.iter().enumerate() {
if directories[..i]
.iter()
.any(|other| directory.starts_with(other) || other.starts_with(directory))
{
return Err("native model directories overlap through filesystem aliases".into());
}
}
Ok(())
}
impl NativeModel {
pub fn validate(&self, assets: &[AssetBundle]) -> Result<()> {
let mut all = vec![
AssetBundle {
manifest: self.manifest.clone(),
directory: self.source_dir.clone(),
},
AssetBundle {
manifest: self.manifest.clone(),
directory: self.output.clone(),
},
];
all.extend(assets.iter().map(|a| AssetBundle {
manifest: a.manifest.clone(),
directory: a.directory.clone(),
}));
asset_bundle::validate(&all)?;
let directories = all
.iter()
.map(|a| resolved(&a.directory))
.collect::<Result<Vec<_>>>()?;
check_no_overlap(&directories)?;
check_manifests_outside(&all, &directories)
}
pub async fn ensure(&self) -> Result<PathBuf> {
let manifest = model::Manifest::load(&self.manifest).await?;
// Source acquisition uses the existing private resumable stage and lock.
asset_bundle::provision(&[AssetBundle {
manifest: self.manifest.clone(),
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 _lock = self.lock_output()?;
self.prepare_or_verify(&manifest).await?;
Ok(primary)
}
/// An existing pack is verified against its receipt; a missing one is prepared first.
async fn prepare_or_verify(&self, manifest: &model::Manifest) -> Result<()> {
match fs::symlink_metadata(&self.output) {
Ok(_) => verify_receipt(manifest, &self.output)?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
native_pack::prepare(manifest, &self.source_dir, &self.output).await?;
verify_receipt(manifest, &self.output)?;
}
Err(e) => return Err(e.into()),
}
Ok(())
}
/// Take the exclusive lock beside the output; the pack is prepared or verified while it is held.
fn lock_output(&self) -> Result<File> {
let parent = self.output.parent().ok_or("pack directory has no parent")?;
fs::create_dir_all(parent)?;
let mut name = std::ffi::OsString::from(".");
name.push(self.output.file_name().ok_or("pack filename missing")?);
name.push(".native-model-lock");
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let lock = options.open(parent.join(name))?;
if !lock.metadata()?.is_file() {
return Err("native model lock must be a regular file".into());
}
lock.try_lock()
.map_err(|_| "native model preparation is busy; retry when it finishes")?;
Ok(lock)
}
}
// Resolve existing ancestors too: a new path beneath a symlink can otherwise
// appear lexically disjoint while writing inside another immutable version.
fn resolved(path: &Path) -> Result<PathBuf> {
match fs::symlink_metadata(path) {
Ok(_) => Ok(fs::canonicalize(path)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
let parent = path.parent().ok_or("path has no existing ancestor")?;
Ok(resolved(parent)?.join(path.file_name().ok_or("path component missing")?))
}
Err(e) => Err(e.into()),
}
}
#[derive(Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct Entry {
size: u64,
sha256: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Receipt {
schema: u32,
converter: u32,
sources: BTreeMap<String, Entry>,
files: BTreeMap<String, Entry>,
}
fn sources(manifest: &model::Manifest) -> BTreeMap<String, Entry> {
manifest
.files
.iter()
.map(|f| {
(
f.name.clone(),
Entry {
size: f.size,
sha256: f.sha256.to_ascii_lowercase(),
},
)
})
.collect()
}
fn digest(path: &Path) -> Result<Entry> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err("pack entries must be regular files".into());
}
let mut file = File::open(path)?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 65536];
let mut size = 0;
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
hash.update(&buffer[..n]);
size += n as u64;
}
Ok(Entry {
size,
sha256: hex::encode(hash.finalize()),
})
}
const PACK_TOP: &[&str] = &[
"dense.bin",
"index.txt",
"native_experts.txt",
"conversions.json",
"source.json",
"receipt.json",
"tokenizer",
];
const TOKENIZER_FILES: &[&str] = &[
"vocab.json",
"merges.txt",
"token_type.json",
"tokenizer.json",
"chat_template.jinja",
];
fn exact_tree(output: &Path, optional: &[&str]) -> Result<()> {
let mut top = PACK_TOP.to_vec();
top.extend_from_slice(optional);
exact_dir(output, top)?;
exact_dir(&output.join("tokenizer"), TOKENIZER_FILES.to_vec())
}
/// `dir` is a real directory holding exactly the `expected` names.
fn exact_dir(dir: &Path, expected: Vec<&str>) -> Result<()> {
let md = fs::symlink_metadata(dir)?;
if !md.is_dir() || md.file_type().is_symlink() {
return Err("pack must contain real directories".into());
}
let mut actual = fs::read_dir(dir)?
.map(|r| r.map(|e| e.file_name()))
.collect::<std::io::Result<Vec<_>>>()?;
actual.sort();
let mut expected = expected
.into_iter()
.map(std::ffi::OsString::from)
.collect::<Vec<_>>();
expected.sort();
if actual != expected {
return Err("pack file set differs from receipt schema".into());
}
Ok(())
}
pub fn write_receipt(manifest: &model::Manifest, output: &Path) -> Result<()> {
let files = FILES
.iter()
.chain(OPTIONAL_FILES.iter().filter(|n| output.join(n).exists()))
.map(|name| Ok((name.to_string(), digest(&output.join(name))?)))
.collect::<Result<BTreeMap<_, _>>>()?;
let receipt = Receipt {
schema: 1,
converter: 1,
sources: sources(manifest),
files,
};
use std::io::Write;
let mut file = File::create(output.join("receipt.json"))?;
file.write_all(&serde_json::to_vec_pretty(&receipt)?)?;
file.sync_all()?;
Ok(())
}
pub fn verify_receipt(manifest: &model::Manifest, output: &Path) -> Result<()> {
let r = read_receipt(output)?;
let optional = OPTIONAL_FILES
.iter()
.copied()
.filter(|n| r.files.contains_key(*n))
.collect::<Vec<_>>();
check_receipt_pins(manifest, &r, optional.len())?;
exact_tree(output, &optional)?;
for name in FILES.iter().chain(optional.iter()) {
if r.files.get(*name) != Some(&digest(&output.join(name))?) {
return Err("native pack checksum mismatch; use a new versioned output".into());
}
}
Ok(())
}
fn read_receipt(output: &Path) -> Result<Receipt> {
let path = output.join("receipt.json");
let md = fs::symlink_metadata(&path)?;
if !md.is_file() || md.file_type().is_symlink() || md.len() > 1_048_576 {
return Err("invalid pack receipt file".into());
}
Ok(serde_json::from_slice(&fs::read(path)?)?)
}
/// The receipt names this manifest's sources, this converter and exactly the files of the schema.
fn check_receipt_pins(manifest: &model::Manifest, r: &Receipt, optional: usize) -> Result<()> {
if r.schema != 1
|| r.converter != 1
|| r.sources != sources(manifest)
|| r.files.len() != FILES.len() + optional
|| !FILES.iter().all(|n| r.files.contains_key(*n))
{
return Err("native pack receipt does not match pinned sources/converter".into());
}
Ok(())
}