feat: add versioned inference backend contract

This commit is contained in:
Pavlo Ratushnyi
2026-10-05 18:04:20 +02:00
commit 1e98febce6
6 changed files with 475 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
/target/
*.gguf
*.safetensors
*.bin
.env*
Generated
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "leleka-backend-api"
version = "0.1.0"
+14
View File
@@ -0,0 +1,14 @@
[workspace]
resolver = "3"
members = ["crates/backend-api"]
[workspace.package]
edition = "2024"
license = "Apache-2.0"
rust-version = "1.85"
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
all = "warn"
+23
View File
@@ -0,0 +1,23 @@
# Leleka
Leleka is an independent Rust inference runtime. The first checked-in slice is
the versioned backend boundary in `leleka-backend-api`.
## Current scope
- The API crate defines model identity, backend capabilities, load/generate/
cancel/unload operations, and typed generation events.
- Generation streams enforce one terminal result and report a producer that
disappears without completion.
- The crate has no Strata, Python, CUDA, model weights, or inference engine
dependency. No model family is claimed as implemented yet.
This is the interface foundation, not a runnable model server. NVIDIA engine
integration and real-model/protocol/quality qualification remain future work.
## Development
```sh
cargo test --workspace --locked
cargo clippy --workspace --all-targets --all-features -- -D warnings
```
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "leleka-backend-api"
version = "0.1.0"
description = "Versioned backend contract for the Leleka inference runtime"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
[lints]
workspace = true
+414
View File
@@ -0,0 +1,414 @@
//! 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`].
pub const BACKEND_API_VERSION: u16 = 1;
#[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.trim().is_empty() {
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(())
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BackendCapabilities {
pub supported_families: Vec<String>,
pub supported_architectures: Vec<String>,
pub supported_weight_formats: Vec<String>,
pub max_concurrent_generations: usize,
pub supports_cancellation: bool,
pub supports_tool_call_streaming: bool,
}
impl BackendCapabilities {
pub fn supports(&self, model: &ModelDescriptor) -> bool {
self.supported_families.iter().any(|v| v == &model.family)
&& self
.supported_architectures
.iter()
.any(|v| v == &model.architecture)
&& self
.supported_weight_formats
.iter()
.any(|v| v == &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 claim a model family or
/// format until it can load and serve it 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: "qwen3_moe".into(),
architecture: "qwen3_moe_v1".into(),
artifact_digest: format!("sha256:{}", "a".repeat(64)),
weight_format: "gguf:iq3_s".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"))
);
}
#[test]
fn capabilities_match_family_architecture_and_format_together() {
let capabilities = BackendCapabilities {
supported_families: vec!["qwen3_moe".into()],
supported_architectures: vec!["qwen3_moe_v1".into()],
supported_weight_formats: vec!["gguf:iq3_s".into()],
max_concurrent_generations: 2,
supports_cancellation: true,
supports_tool_call_streaming: true,
};
assert!(capabilities.supports(&model()));
let mut unsupported = model();
unsupported.weight_format = "gguf:unknown".into();
assert!(!capabilities.supports(&unsupported));
}
#[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());
let older = BackendIdentity {
api_version: 0,
..current
};
assert!(!older.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)
);
}
}