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

330 lines
10 KiB
Rust

//! Fail-closed acquisition and preparation paths. The full-size stream is
//! experimental until real-model quality and Linux GPU loading are verified.
use std::{
fs, io,
path::{Component, Path},
};
use crate::{gguf, kar, model, prepare_preview, stream_parts};
pub enum PreviewOutcome {
Created(prepare_preview::PreviewSummary),
Reused(kar::Summary),
}
fn require_levels(levels: u8, message: &str) -> Result<(), crate::BoxError> {
if !(1..=8).contains(&levels) {
return Err(message.into());
}
Ok(())
}
fn require_regular_archive(metadata: &fs::Metadata) -> Result<(), crate::BoxError> {
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err("existing KAR path must be a regular file".into());
}
Ok(())
}
fn require_preview_source_limit(manifest: &model::Manifest) -> Result<(), crate::BoxError> {
let source_bytes = manifest
.files
.iter()
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
.ok_or("sharded source byte count overflow")?;
if source_bytes > 64 * 1024 * 1024 {
return Err(
"sharded preview accepts at most 64 MiB of GGUF input; full-model preparation is not implemented".into(),
);
}
Ok(())
}
fn reuse_sharded_preview(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
) -> Result<PreviewOutcome, crate::BoxError> {
let summary = prepare_preview::verify_sharded(manifest, source_dir, archive)?;
if summary.max_planes != levels {
return Err(format!(
"existing KAR has {} levels, requested {levels}; choose another output path",
summary.max_planes
)
.into());
}
Ok(PreviewOutcome::Reused(summary))
}
fn create_sharded_preview(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
) -> Result<PreviewOutcome, crate::BoxError> {
let created = prepare_preview::prepare_sharded(manifest, source_dir, archive, levels)?;
prepare_preview::verify_sharded(manifest, source_dir, archive)?;
Ok(PreviewOutcome::Created(created))
}
async fn fetch_and_verify(
manifest: &model::Manifest,
source_dir: &Path,
) -> Result<(), crate::BoxError> {
model::fetch(manifest, source_dir).await?;
model::verify(manifest, source_dir).await?;
Ok(())
}
pub async fn ensure_sharded_preview(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
) -> Result<PreviewOutcome, crate::BoxError> {
require_levels(levels, "sharded preview requires 1..=8 KAR levels")?;
require_preview_source_limit(manifest)?;
fetch_and_verify(manifest, source_dir).await?;
match fs::symlink_metadata(archive) {
Ok(metadata) => {
require_regular_archive(&metadata)?;
reuse_sharded_preview(manifest, source_dir, archive, levels)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
create_sharded_preview(manifest, source_dir, archive, levels)
}
Err(error) => Err(error.into()),
}
}
pub async fn ensure_sharded_streamed(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
) -> Result<PreviewOutcome, crate::BoxError> {
ensure_sharded_streamed_with_policy(manifest, source_dir, archive, levels, None).await
}
pub async fn ensure_sharded_streamed_ple(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: u64,
) -> Result<PreviewOutcome, crate::BoxError> {
ensure_sharded_streamed_with_policy(
manifest,
source_dir,
archive,
levels,
Some(ple_part_elements),
)
.await
}
fn verify_streamed(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<kar::Summary, String> {
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)
}
}
fn prepare_streamed(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<prepare_preview::PreviewSummary, String> {
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)
}
}
fn require_streamed_request(
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<(), crate::BoxError> {
require_levels(
levels,
"streamed sharded preparation requires 1..=8 KAR levels",
)?;
if let Some(limit) = ple_part_elements {
stream_parts::validate_ple_limit(limit)?;
}
Ok(())
}
fn create_streamed(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<PreviewOutcome, crate::BoxError> {
let created = prepare_streamed(manifest, source_dir, archive, levels, ple_part_elements)?;
verify_streamed(manifest, source_dir, archive, levels, ple_part_elements)?;
Ok(PreviewOutcome::Created(created))
}
async fn ensure_sharded_streamed_with_policy(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<PreviewOutcome, crate::BoxError> {
require_streamed_request(levels, ple_part_elements)?;
preflight_existing_shards(manifest, source_dir, archive, levels)?;
fetch_and_verify(manifest, source_dir).await?;
match fs::symlink_metadata(archive) {
Ok(metadata) => {
require_regular_archive(&metadata)?;
let summary =
verify_streamed(manifest, source_dir, archive, levels, ple_part_elements)?;
Ok(PreviewOutcome::Reused(summary))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
create_streamed(manifest, source_dir, archive, levels, ple_part_elements)
}
Err(error) => Err(error.into()),
}
}
fn archive_exists(archive: &Path) -> Result<bool, crate::BoxError> {
match fs::symlink_metadata(archive) {
Ok(_) => Ok(true),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
fn require_plain_shard_name(name: &Path) -> Result<(), crate::BoxError> {
if name.components().count() != 1
|| !matches!(name.components().next(), Some(Component::Normal(_)))
{
return Err("invalid model shard name".into());
}
Ok(())
}
/// Adds the minimum payload of every tensor of the shard to `minimum`.
fn add_tensor_minimums(
tensors: Vec<gguf::TensorInfo>,
levels: u8,
mut minimum: u64,
) -> Result<u64, crate::BoxError> {
for tensor in tensors {
let derived_bytes = tensor
.dimensions
.iter()
.try_fold(4u64, |bytes, dim| bytes.checked_mul(*dim))
.ok_or("GGUF tensor F32 byte count overflow")?;
minimum = minimum
.checked_add(prepare_preview::minimum_part_payload_bytes(
derived_bytes,
levels,
)?)
.ok_or("KAR minimum payload size overflow")?;
}
Ok(minimum)
}
/// The running minimum after this shard, or `None` when the shard is absent
/// or incomplete and the check cannot be decided yet.
fn add_shard_minimum(
source_dir: &Path,
shard: &model::ModelFile,
levels: u8,
minimum: u64,
) -> Result<Option<u64>, crate::BoxError> {
let name = Path::new(&shard.name);
require_plain_shard_name(name)?;
let path = source_dir.join(name);
let metadata = match fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err(format!("model shard is not a regular file: {}", path.display()).into());
}
if metadata.len() != shard.size {
return Ok(None); // Fetch will reject or resume this shard.
}
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.summary.file_size != shard.size {
return Err("GGUF shard size differs from manifest".into());
}
add_tensor_minimums(index.tensors, levels, minimum).map(Some)
}
/// Reject an impossible new archive before hashing already-present large
/// shards. GGUF metadata is only a rejection hint; fetch/verify still pins
/// every source byte before preparation when the volume has enough space.
fn preflight_existing_shards(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
) -> Result<(), crate::BoxError> {
if archive_exists(archive)? {
return Ok(()); // Reusing an archive needs no new payload space.
}
let mut minimum = 0u64;
for shard in &manifest.files {
match add_shard_minimum(source_dir, shard, levels, minimum)? {
Some(next) => minimum = next,
None => return Ok(()),
}
}
let parent = archive
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
model::require_space(parent, minimum)
.map_err(|error| format!("KAR minimum payload does not fit: {error}").into())
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
#[tokio::test]
async fn full_model_is_rejected_before_creating_a_download_directory() {
let manifest = model::Manifest::from_spec("qwen-iq3-s").await.unwrap();
let source_dir = std::env::temp_dir().join(format!(
"strata-oversized-preview-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
assert!(!source_dir.exists());
let error =
ensure_sharded_preview(&manifest, &source_dir, &source_dir.join("model.kar"), 2)
.await
.err()
.unwrap()
.to_string();
assert!(error.contains("at most 64 MiB"));
assert!(!source_dir.exists());
}
}