Files
leleka/crates/backend-api/src/load_mode.rs
T

145 lines
5.0 KiB
Rust

//! Explicit model-load selection. Validation here admits configuration only;
//! the backend must verify artifacts and qualification before returning ready.
use crate::{ContractError, LoadedModel, ModelDescriptor, RuntimeConfig};
pub const LOAD_CONFIG_VERSION: u16 = 1;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum InferenceMode {
Native,
/// Resolves a trusted local profile; this ID is never a filesystem path.
ExperimentalKarPle {
profile_id: String,
},
/// Separate expert path, never substituted for the PLE customization.
ExperimentalKarExperts(KarExpertLoad),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KarExpertLoad {
pub bundle_directory: String,
pub archive_file: String,
pub binding_file: String,
pub provenance_file: String,
pub levels: u8,
pub cache_mib: u32,
pub prefill_mode: KarPrefillMode,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KarPrefillMode {
DecodeOnly,
AllRoutedBatched,
}
impl RuntimeConfig {
/// The sole legacy adapter refuses ambiguous experimental permission.
pub fn legacy_native(
gpu_memory_limit_bytes: Option<u64>,
allow_experimental: bool,
) -> Result<Self, ContractError> {
if allow_experimental {
return Err(ContractError::InvalidField("legacy_experimental_mode"));
}
let config = Self {
load_config_version: LOAD_CONFIG_VERSION,
inference_mode: InferenceMode::Native,
gpu_memory_limit_bytes,
allow_experimental: false,
};
config.validate()?;
Ok(config)
}
/// Does not open artifacts, enable an operator, allocate CUDA or attest
/// model quality. Unsupported/unqualified paths must still fail at load.
pub fn validate(&self) -> Result<(), ContractError> {
if self.load_config_version != LOAD_CONFIG_VERSION {
return Err(ContractError::InvalidField("load_config_version"));
}
if self.gpu_memory_limit_bytes == Some(0) {
return Err(ContractError::InvalidField("gpu_memory_limit_bytes"));
}
if self.inference_mode != InferenceMode::Native && !self.allow_experimental {
return Err(ContractError::InvalidField("experimental_permission"));
}
match &self.inference_mode {
InferenceMode::Native => Ok(()),
InferenceMode::ExperimentalKarPle { profile_id } => {
validate_name(profile_id, "profile_id")
}
InferenceMode::ExperimentalKarExperts(experts) => experts.validate(),
}
}
}
impl KarExpertLoad {
fn validate(&self) -> Result<(), ContractError> {
if self.bundle_directory.is_empty()
|| self.bundle_directory.len() > 4096
|| self.bundle_directory.chars().any(char::is_control)
{
return Err(ContractError::InvalidField("bundle_directory"));
}
for (value, field) in [
(&self.archive_file, "archive_file"),
(&self.binding_file, "binding_file"),
(&self.provenance_file, "provenance_file"),
] {
validate_name(value, field)?;
}
if !(1..=8).contains(&self.levels) {
return Err(ContractError::InvalidField("levels"));
}
if self.cache_mib == 0 {
return Err(ContractError::InvalidField("cache_mib"));
}
Ok(())
}
}
impl LoadedModel {
/// A backend must validate its completed result against the exact request.
/// This cannot replace its physical digest/qualification checks or registry.
pub fn validate_for_load(
&self,
requested: &ModelDescriptor,
config: &RuntimeConfig,
) -> Result<(), ContractError> {
config.validate()?;
requested.validate()?;
self.descriptor.validate()?;
if &self.descriptor != requested {
return Err(ContractError::InvalidField("loaded_model_identity"));
}
if self.handle.is_empty() || self.handle.chars().any(char::is_control) {
return Err(ContractError::InvalidField("loaded_handle"));
}
if self.load_config_version != config.load_config_version
|| self.effective_mode != config.inference_mode
{
return Err(ContractError::InvalidField("loaded_inference_mode"));
}
let Some(hex) = self.mode_identity_digest.strip_prefix("sha256:") else {
return Err(ContractError::InvalidField("mode_identity_digest"));
};
if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(ContractError::InvalidField("mode_identity_digest"));
}
Ok(())
}
}
fn validate_name(value: &str, field: &'static str) -> Result<(), ContractError> {
if value.is_empty()
|| value.len() > 128
|| matches!(value, "." | "..")
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
{
return Err(ContractError::InvalidField(field));
}
Ok(())
}