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

563 lines
18 KiB
Rust

//! Versioned, runtime-independent contract between Leleka and inference backends.
//!
//! This crate deliberately contains no CUDA, model loader, Strata, or Python
//! dependency. It defines the boundary those implementations must satisfy.
use std::fmt;
use std::sync::Mutex;
use std::sync::mpsc::{self, Receiver, RecvError, SendError, Sender};
/// Version understood by this crate and advertised in [`BackendIdentity`].
// 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 {
pub name: String,
pub implementation_version: String,
pub api_version: u16,
}
impl BackendIdentity {
pub fn supports_current_api(&self) -> bool {
self.api_version == BACKEND_API_VERSION
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ModelDescriptor {
/// Stable family identifier, for example `qwen3_moe` or `mixtral`.
pub family: String,
/// Architecture revision understood by the backend.
pub architecture: String,
/// Exact model artifact digest, formatted as `sha256:<hex>`.
pub artifact_digest: String,
/// Weight format and quantization, for example `gguf:iq3_s`.
pub weight_format: String,
}
impl ModelDescriptor {
pub fn validate(&self) -> Result<(), ContractError> {
for (field, value) in [
("family", self.family.as_str()),
("architecture", self.architecture.as_str()),
("weight_format", self.weight_format.as_str()),
] {
if value.is_empty()
|| value
.chars()
.any(|ch| ch.is_whitespace() || ch.is_control())
{
return Err(ContractError::InvalidField(field));
}
}
let Some(hex) = self.artifact_digest.strip_prefix("sha256:") else {
return Err(ContractError::InvalidField("artifact_digest"));
};
if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(ContractError::InvalidField("artifact_digest"));
}
Ok(())
}
}
/// 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 {
/// 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 {
model.validate().is_ok()
&& self.supported_models.iter().any(|supported| {
supported.family == model.family
&& supported.architecture == model.architecture
&& supported.weight_format == model.weight_format
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeConfig {
/// Requested GPU memory ceiling in bytes. `None` leaves policy to the host.
pub gpu_memory_limit_bytes: Option<u64>,
/// Whether the caller explicitly permits an experimental/lossy path.
pub allow_experimental: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoadedModel {
pub handle: String,
pub descriptor: ModelDescriptor,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GenerationRequest {
pub request_id: String,
pub prompt: String,
pub max_output_tokens: u32,
pub temperature_milli: u32,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Usage {
pub input_tokens: u64,
pub output_tokens: u64,
pub reused_input_tokens: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FinishReason {
Stop,
Length,
ToolCalls,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ErrorCode {
InvalidRequest,
UnsupportedModel,
ResourceExhausted,
BackendUnavailable,
Internal,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GenerationEvent {
TextDelta {
text: String,
},
ToolCallDelta {
index: u32,
id: Option<String>,
name: Option<String>,
arguments_delta: String,
},
Usage(Usage),
Terminal(GenerationTerminal),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GenerationTerminal {
Completed {
reason: FinishReason,
usage: Usage,
},
Failed {
code: ErrorCode,
message: String,
retryable: bool,
},
Cancelled,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ContractError {
InvalidField(&'static str),
UnsupportedApiVersion(u16),
GenerationAlreadyTerminal,
GenerationClosed,
}
impl fmt::Display for ContractError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidField(field) => write!(f, "invalid {field}"),
Self::UnsupportedApiVersion(version) => {
write!(f, "backend API version {version} is unsupported")
}
Self::GenerationAlreadyTerminal => {
f.write_str("generation already has a terminal event")
}
Self::GenerationClosed => f.write_str("generation event stream is closed"),
}
}
}
impl std::error::Error for ContractError {}
/// 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;
fn load(
&mut self,
model: ModelDescriptor,
config: RuntimeConfig,
) -> Result<LoadedModel, BackendError>;
fn start_generation(
&mut self,
model: &LoadedModel,
request: GenerationRequest,
) -> Result<GenerationStream, BackendError>;
fn cancel(&mut self, request_id: &str) -> Result<(), BackendError>;
fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BackendError {
pub code: ErrorCode,
pub message: String,
pub retryable: bool,
}
impl fmt::Display for BackendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {}", self.code, self.message)
}
}
impl std::error::Error for BackendError {}
/// Producer side of a generation stream. It serializes sends and allows only
/// one terminal event; deltas after completion are rejected.
pub struct GenerationSink {
sender: Sender<GenerationEvent>,
terminal_sent: Mutex<bool>,
}
impl GenerationSink {
pub fn channel() -> (Self, GenerationStream) {
let (sender, receiver) = mpsc::channel();
(
Self {
sender,
terminal_sent: Mutex::new(false),
},
GenerationStream {
receiver,
terminal_seen: false,
},
)
}
pub fn emit(&self, event: GenerationEvent) -> Result<(), ContractError> {
let is_terminal = matches!(event, GenerationEvent::Terminal(_));
let mut terminal_sent = self.terminal_sent.lock().expect("generation lock poisoned");
if *terminal_sent {
return Err(ContractError::GenerationAlreadyTerminal);
}
self.sender
.send(event)
.map_err(|SendError(_)| ContractError::GenerationClosed)?;
if is_terminal {
*terminal_sent = true;
}
Ok(())
}
pub fn complete(&self, reason: FinishReason, usage: Usage) -> Result<(), ContractError> {
self.emit(GenerationEvent::Terminal(GenerationTerminal::Completed {
reason,
usage,
}))
}
pub fn fail(
&self,
code: ErrorCode,
message: impl Into<String>,
retryable: bool,
) -> Result<(), ContractError> {
self.emit(GenerationEvent::Terminal(GenerationTerminal::Failed {
code,
message: message.into(),
retryable,
}))
}
pub fn cancel(&self) -> Result<(), ContractError> {
self.emit(GenerationEvent::Terminal(GenerationTerminal::Cancelled))
}
}
/// Consumer side. End-of-channel without a terminal event is a protocol error.
pub struct GenerationStream {
receiver: Receiver<GenerationEvent>,
terminal_seen: bool,
}
impl GenerationStream {
pub fn recv(&mut self) -> Result<Option<GenerationEvent>, StreamError> {
if self.terminal_seen {
return Ok(None);
}
match self.receiver.recv() {
Ok(event) => {
if matches!(event, GenerationEvent::Terminal(_)) {
self.terminal_seen = true;
}
Ok(Some(event))
}
Err(RecvError) => Err(StreamError::MissingTerminal),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StreamError {
MissingTerminal,
}
impl fmt::Display for StreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingTerminal => {
f.write_str("generation stream closed without a terminal event")
}
}
}
}
impl std::error::Error for StreamError {}
#[cfg(test)]
mod tests {
use super::*;
fn model() -> ModelDescriptor {
ModelDescriptor {
family: "fixture_alpha".into(),
architecture: "fixture_arch_a".into(),
artifact_digest: format!("sha256:{}", "a".repeat(64)),
weight_format: "fixture:format_a".into(),
}
}
#[test]
fn descriptor_requires_exact_sha256_digest() {
let mut descriptor = model();
assert!(descriptor.validate().is_ok());
descriptor.artifact_digest = "sha256:abc".into();
assert_eq!(
descriptor.validate(),
Err(ContractError::InvalidField("artifact_digest"))
);
}
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!(!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]
fn backend_api_version_is_explicit_and_exact() {
let current = BackendIdentity {
name: "test".into(),
implementation_version: "0.1.0".into(),
api_version: BACKEND_API_VERSION,
};
assert!(current.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]
fn stream_accepts_deltas_then_exactly_one_terminal() {
let (sink, mut stream) = GenerationSink::channel();
sink.emit(GenerationEvent::TextDelta { text: "hi".into() })
.unwrap();
sink.complete(FinishReason::Stop, Usage::default()).unwrap();
assert_eq!(sink.cancel(), Err(ContractError::GenerationAlreadyTerminal));
assert!(matches!(
stream.recv().unwrap(),
Some(GenerationEvent::TextDelta { .. })
));
assert!(matches!(
stream.recv().unwrap(),
Some(GenerationEvent::Terminal(_))
));
assert_eq!(stream.recv().unwrap(), None);
}
#[test]
fn dropped_producer_without_terminal_is_detected() {
let (sink, mut stream) = GenerationSink::channel();
sink.emit(GenerationEvent::Usage(Usage::default())).unwrap();
drop(sink);
assert!(matches!(
stream.recv().unwrap(),
Some(GenerationEvent::Usage(_))
));
assert_eq!(stream.recv(), Err(StreamError::MissingTerminal));
}
#[test]
fn deltas_after_terminal_are_rejected() {
let (sink, _stream) = GenerationSink::channel();
sink.cancel().unwrap();
assert_eq!(
sink.emit(GenerationEvent::TextDelta {
text: "late".into()
}),
Err(ContractError::GenerationAlreadyTerminal)
);
}
}