feat(linux): connect native CUDA runtime to gRPC daemon and CLI
This commit is contained in:
Generated
+4
@@ -1033,9 +1033,11 @@ dependencies = [
|
||||
name = "leleka-runtime"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"leleka-backend-api",
|
||||
"leleka-cuda-driver",
|
||||
"leleka-model-format",
|
||||
"leleka-quant-core",
|
||||
"leleka-tokenizer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2058,6 +2060,8 @@ dependencies = [
|
||||
"async-stream",
|
||||
"axum",
|
||||
"futures-util",
|
||||
"leleka-backend-api",
|
||||
"leleka-runtime",
|
||||
"prost",
|
||||
"protoc-bin-vendored",
|
||||
"reqwest",
|
||||
|
||||
@@ -4,8 +4,11 @@
|
||||
//! 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};
|
||||
use std::sync::mpsc::{self, Receiver, RecvError, SendError, Sender, SyncSender, TrySendError};
|
||||
use std::sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
mod load_mode;
|
||||
pub use load_mode::{InferenceMode, KarExpertLoad, KarPrefillMode, LOAD_CONFIG_VERSION};
|
||||
@@ -189,6 +192,7 @@ pub enum ContractError {
|
||||
UnsupportedApiVersion(u16),
|
||||
GenerationAlreadyTerminal,
|
||||
GenerationClosed,
|
||||
GenerationBackpressure,
|
||||
}
|
||||
|
||||
impl fmt::Display for ContractError {
|
||||
@@ -201,6 +205,7 @@ impl fmt::Display for ContractError {
|
||||
Self::GenerationAlreadyTerminal => {
|
||||
f.write_str("generation already has a terminal event")
|
||||
}
|
||||
Self::GenerationBackpressure => f.write_str("generation event queue is full"),
|
||||
Self::GenerationClosed => f.write_str("generation event stream is closed"),
|
||||
}
|
||||
}
|
||||
@@ -245,34 +250,95 @@ 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>,
|
||||
sender: EventSender,
|
||||
receiver_closed: Arc<AtomicBool>,
|
||||
terminal_sent: Mutex<bool>,
|
||||
}
|
||||
|
||||
impl GenerationSink {
|
||||
pub fn channel() -> (Self, GenerationStream) {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let closed = Arc::new(AtomicBool::new(false));
|
||||
(
|
||||
Self {
|
||||
sender,
|
||||
sender: EventSender::Unbounded(sender),
|
||||
receiver_closed: Arc::clone(&closed),
|
||||
terminal_sent: Mutex::new(false),
|
||||
},
|
||||
GenerationStream {
|
||||
receiver,
|
||||
receiver_closed: closed,
|
||||
terminal_seen: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// A finite event queue of 1..=16 events; invalid capacities are refused
|
||||
/// before the channel can allocate or become a rendezvous channel.
|
||||
pub fn bounded_channel(capacity: usize) -> Result<(Self, GenerationStream), ContractError> {
|
||||
if !(1..=16).contains(&capacity) {
|
||||
return Err(ContractError::InvalidField("event_capacity"));
|
||||
}
|
||||
let (sender, receiver) = mpsc::sync_channel(capacity);
|
||||
let closed = Arc::new(AtomicBool::new(false));
|
||||
Ok((
|
||||
Self {
|
||||
sender: EventSender::Bounded(sender),
|
||||
receiver_closed: Arc::clone(&closed),
|
||||
terminal_sent: Mutex::new(false),
|
||||
},
|
||||
GenerationStream {
|
||||
receiver,
|
||||
receiver_closed: closed,
|
||||
terminal_seen: false,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Receiver destruction is observable without sending a token/event.
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.receiver_closed.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Never block cancellation behind a full event queue. A rejected terminal
|
||||
/// has not been published and may be retried until capacity becomes available.
|
||||
pub fn try_emit(&self, event: GenerationEvent) -> Result<(), ContractError> {
|
||||
let is_terminal = matches!(event, GenerationEvent::Terminal(_));
|
||||
let mut terminal_sent = self
|
||||
.terminal_sent
|
||||
.lock()
|
||||
.map_err(|_| ContractError::GenerationClosed)?;
|
||||
if *terminal_sent {
|
||||
return Err(ContractError::GenerationAlreadyTerminal);
|
||||
}
|
||||
match &self.sender {
|
||||
EventSender::Unbounded(sender) => sender
|
||||
.send(event)
|
||||
.map_err(|_| ContractError::GenerationClosed)?,
|
||||
EventSender::Bounded(sender) => {
|
||||
sender.try_send(event).map_err(|error| match error {
|
||||
TrySendError::Full(_) => ContractError::GenerationBackpressure,
|
||||
TrySendError::Disconnected(_) => ContractError::GenerationClosed,
|
||||
})?
|
||||
}
|
||||
}
|
||||
if is_terminal {
|
||||
*terminal_sent = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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)?;
|
||||
match &self.sender {
|
||||
EventSender::Unbounded(sender) => sender.send(event),
|
||||
EventSender::Bounded(sender) => sender.send(event),
|
||||
}
|
||||
.map_err(|SendError(_)| ContractError::GenerationClosed)?;
|
||||
if is_terminal {
|
||||
*terminal_sent = true;
|
||||
}
|
||||
@@ -304,12 +370,24 @@ impl GenerationSink {
|
||||
}
|
||||
}
|
||||
|
||||
enum EventSender {
|
||||
Unbounded(Sender<GenerationEvent>),
|
||||
Bounded(SyncSender<GenerationEvent>),
|
||||
}
|
||||
|
||||
/// Consumer side. End-of-channel without a terminal event is a protocol error.
|
||||
pub struct GenerationStream {
|
||||
receiver: Receiver<GenerationEvent>,
|
||||
receiver_closed: Arc<AtomicBool>,
|
||||
terminal_seen: bool,
|
||||
}
|
||||
|
||||
impl Drop for GenerationStream {
|
||||
fn drop(&mut self) {
|
||||
self.receiver_closed.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
impl GenerationStream {
|
||||
pub fn recv(&mut self) -> Result<Option<GenerationEvent>, StreamError> {
|
||||
if self.terminal_seen {
|
||||
@@ -348,6 +426,48 @@ impl std::error::Error for StreamError {}
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bounded_queue_backpressure_does_not_commit_terminal() {
|
||||
let (sink, mut stream) = GenerationSink::bounded_channel(1).unwrap();
|
||||
sink.try_emit(GenerationEvent::TextDelta {
|
||||
text: "synthetic".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let terminal = GenerationEvent::Terminal(GenerationTerminal::Cancelled);
|
||||
assert_eq!(
|
||||
sink.try_emit(terminal.clone()),
|
||||
Err(ContractError::GenerationBackpressure)
|
||||
);
|
||||
assert!(matches!(
|
||||
stream.recv().unwrap(),
|
||||
Some(GenerationEvent::TextDelta { .. })
|
||||
));
|
||||
sink.try_emit(terminal).unwrap();
|
||||
assert_eq!(
|
||||
sink.try_emit(GenerationEvent::Usage(Usage::default())),
|
||||
Err(ContractError::GenerationAlreadyTerminal)
|
||||
);
|
||||
assert!(matches!(
|
||||
stream.recv().unwrap(),
|
||||
Some(GenerationEvent::Terminal(_))
|
||||
));
|
||||
assert_eq!(stream.recv().unwrap(), None);
|
||||
}
|
||||
#[test]
|
||||
fn bounded_consumer_drop_is_observable_without_a_send() {
|
||||
assert!(GenerationSink::bounded_channel(0).is_err());
|
||||
assert!(GenerationSink::bounded_channel(17).is_err());
|
||||
assert!(GenerationSink::bounded_channel(usize::MAX).is_err());
|
||||
let (sink, stream) = GenerationSink::bounded_channel(1).unwrap();
|
||||
assert!(!sink.is_closed());
|
||||
drop(stream);
|
||||
assert!(sink.is_closed());
|
||||
assert_eq!(
|
||||
sink.try_emit(GenerationEvent::Terminal(GenerationTerminal::Cancelled)),
|
||||
Err(ContractError::GenerationClosed)
|
||||
);
|
||||
}
|
||||
|
||||
fn model() -> ModelDescriptor {
|
||||
ModelDescriptor {
|
||||
family: "fixture_alpha".into(),
|
||||
|
||||
@@ -7,6 +7,8 @@ license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
leleka-backend-api = { path = "../backend-api" }
|
||||
leleka-tokenizer = { path = "../tokenizer" }
|
||||
leleka-model-format = { path = "../model-format" }
|
||||
leleka-quant-core = { path = "../quant-core" }
|
||||
leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver"] }
|
||||
|
||||
@@ -0,0 +1,931 @@
|
||||
//! Native FP16-QSA/no-MTP owner actor. Only messages cross the thread boundary;
|
||||
//! CUDA owners and borrowed buffers remain ordinary locals on that thread.
|
||||
use crate::{
|
||||
model_binding::qwen4exp_input::{InputConstants, ModelBinding},
|
||||
qwen_forward::{
|
||||
contract::{Dimension, Position, TokenId},
|
||||
executor::QwenForward,
|
||||
output::OutputStage,
|
||||
session::QwenSession,
|
||||
},
|
||||
};
|
||||
use leleka_backend_api::{
|
||||
BACKEND_API_VERSION, Backend, BackendCapabilities, BackendError, BackendIdentity,
|
||||
ContractError, ErrorCode, FinishReason, GenerationEvent, GenerationRequest, GenerationSink,
|
||||
GenerationStream, GenerationTerminal, InferenceMode, LOAD_CONFIG_VERSION, LoadedModel,
|
||||
ModelDescriptor, RuntimeConfig, SupportedModelTuple, Usage,
|
||||
};
|
||||
use leleka_cuda_driver::Driver;
|
||||
use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact};
|
||||
use leleka_tokenizer::Tokenizer;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
path::PathBuf,
|
||||
rc::Rc,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
mpsc::{self, Receiver, SyncSender},
|
||||
},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const SHARD0: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3";
|
||||
const SHARD1: &str = "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113";
|
||||
// SHA256(raw32 shard0 digest || raw32 shard1 digest), independently computed.
|
||||
const MODEL_DIGEST: &str =
|
||||
"sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3";
|
||||
// SHA256 of the newline-terminated profile declaration documented below.
|
||||
// leleka-native-v1\nmodel=<MODEL_DIGEST without prefix>\nqsa=fp16\nmtp=none\ngreedy=ordered-finite-logits\n
|
||||
const MODE_DIGEST: &str = "sha256:82b774f9c0daaf4290ae96b079224efea7da49dae74770cb32db3da69e4e3eb5";
|
||||
const PROMPT_LIMIT: usize = 1024 * 1024;
|
||||
const FRAME_LIMIT: usize = 64 * 1024;
|
||||
const OUTPUT_LIMIT: u32 = 4096;
|
||||
const QUEUE: usize = 16;
|
||||
const REPLY_TIMEOUT: Duration = Duration::from_secs(1200);
|
||||
const BACKPRESSURE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const GENERATION_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
static INSTANCE: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Operator-owned files must remain immutable until explicit unload.
|
||||
pub struct NativeBackendConfig {
|
||||
pub shard0: PathBuf,
|
||||
pub shard1: PathBuf,
|
||||
pub gpu_device_ordinal: u32,
|
||||
pub gpu_budget_bytes: u64,
|
||||
pub context_tokens: u32,
|
||||
}
|
||||
|
||||
/// Provenance only: this descriptor does not attest a successful load.
|
||||
pub fn pinned_model_descriptor() -> ModelDescriptor {
|
||||
ModelDescriptor {
|
||||
family: "qwen4exp".into(),
|
||||
architecture: "qwen4exp".into(),
|
||||
artifact_digest: MODEL_DIGEST.into(),
|
||||
weight_format: "gguf:iq3_s".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn_backend(config: NativeBackendConfig) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if config.context_tokens == 0
|
||||
|| config.context_tokens > 262_144
|
||||
|| config.gpu_budget_bytes == 0
|
||||
|| usize::try_from(config.gpu_budget_bytes).is_err()
|
||||
|| i32::try_from(config.gpu_device_ordinal).is_err()
|
||||
{
|
||||
return Err(invalid("invalid native resource configuration"));
|
||||
}
|
||||
let (tx, rx) = mpsc::sync_channel(QUEUE);
|
||||
let shared = Arc::new(Shared {
|
||||
ready: AtomicBool::new(false),
|
||||
shutdown: AtomicBool::new(false),
|
||||
active: Mutex::new(None),
|
||||
});
|
||||
let worker_shared = Arc::clone(&shared);
|
||||
let instance = INSTANCE.fetch_add(1, Ordering::Relaxed);
|
||||
thread::Builder::new()
|
||||
.name("leleka-cuda-owner".into())
|
||||
.spawn(move || {
|
||||
let _guard = OwnerGuard(Arc::clone(&worker_shared));
|
||||
owner(config, rx, &worker_shared, instance);
|
||||
})
|
||||
.map_err(|_| unavailable("native owner thread unavailable"))?;
|
||||
Ok(Box::new(Proxy {
|
||||
tx,
|
||||
shared,
|
||||
seen: HashSet::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
struct Active {
|
||||
id: String,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
struct Shared {
|
||||
ready: AtomicBool,
|
||||
shutdown: AtomicBool,
|
||||
active: Mutex<Option<Active>>,
|
||||
}
|
||||
struct Proxy {
|
||||
tx: SyncSender<Command>,
|
||||
shared: Arc<Shared>,
|
||||
seen: HashSet<String>,
|
||||
}
|
||||
type Reply<T> = SyncSender<Result<T, BackendError>>;
|
||||
enum Command {
|
||||
Load(ModelDescriptor, RuntimeConfig, Reply<LoadedModel>),
|
||||
Generate(
|
||||
LoadedModel,
|
||||
GenerationRequest,
|
||||
Arc<AtomicBool>,
|
||||
Reply<GenerationStream>,
|
||||
),
|
||||
Unload(LoadedModel, Reply<()>),
|
||||
}
|
||||
impl Proxy {
|
||||
fn idle(&self) -> Result<(), BackendError> {
|
||||
if self.shared.shutdown.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native owner stopped"));
|
||||
}
|
||||
if self
|
||||
.shared
|
||||
.active
|
||||
.lock()
|
||||
.map_err(|_| unavailable("native owner state unavailable"))?
|
||||
.is_some()
|
||||
{
|
||||
return Err(exhausted("native generation is active"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn send(&self, command: Command) -> Result<(), BackendError> {
|
||||
self.tx.try_send(command).map_err(|error| match error {
|
||||
mpsc::TrySendError::Full(_) => exhausted("native control queue is full"),
|
||||
mpsc::TrySendError::Disconnected(_) => unavailable("native owner stopped"),
|
||||
})
|
||||
}
|
||||
fn wait<T>(&self, reply: Receiver<Result<T, BackendError>>) -> Result<T, BackendError> {
|
||||
match reply.recv_timeout(REPLY_TIMEOUT) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
// A late/uncertain operation is never retried on this owner.
|
||||
self.shared.shutdown.store(true, Ordering::Release);
|
||||
cancel_active(&self.shared);
|
||||
Err(unavailable("native operation outcome unavailable"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Backend for Proxy {
|
||||
fn identity(&self) -> BackendIdentity {
|
||||
BackendIdentity {
|
||||
name: "leleka-native".into(),
|
||||
implementation_version: "0.1.0-fp16-qsa-no-mtp".into(),
|
||||
api_version: BACKEND_API_VERSION,
|
||||
}
|
||||
}
|
||||
fn capabilities(&self) -> BackendCapabilities {
|
||||
let models = if self.shared.ready.load(Ordering::Acquire)
|
||||
&& !self.shared.shutdown.load(Ordering::Acquire)
|
||||
{
|
||||
vec![SupportedModelTuple {
|
||||
family: "qwen4exp".into(),
|
||||
architecture: "qwen4exp".into(),
|
||||
weight_format: "gguf:iq3_s".into(),
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
BackendCapabilities {
|
||||
supported_models: models,
|
||||
max_concurrent_generations: 1,
|
||||
supports_cancellation: true,
|
||||
supports_tool_call_streaming: false,
|
||||
}
|
||||
}
|
||||
fn load(
|
||||
&mut self,
|
||||
model: ModelDescriptor,
|
||||
config: RuntimeConfig,
|
||||
) -> Result<LoadedModel, BackendError> {
|
||||
validate_load(&model, &config)?;
|
||||
self.idle()?;
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
self.send(Command::Load(model, config, tx))?;
|
||||
self.wait(rx)
|
||||
}
|
||||
fn start_generation(
|
||||
&mut self,
|
||||
model: &LoadedModel,
|
||||
request: GenerationRequest,
|
||||
) -> Result<GenerationStream, BackendError> {
|
||||
validate_request(&request)?;
|
||||
validate_handle(model)?;
|
||||
self.idle()?;
|
||||
if !self.shared.ready.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native model is not ready"));
|
||||
}
|
||||
if self.seen.contains(&request.request_id) {
|
||||
return Err(invalid("generation request was already accepted"));
|
||||
}
|
||||
if self.seen.len() == 256 {
|
||||
return Err(exhausted("generation identity registry is full"));
|
||||
}
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
*self
|
||||
.shared
|
||||
.active
|
||||
.lock()
|
||||
.map_err(|_| unavailable("native owner state unavailable"))? = Some(Active {
|
||||
id: request.request_id.clone(),
|
||||
cancel: Arc::clone(&cancel),
|
||||
});
|
||||
let id = request.request_id.clone();
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
if let Err(error) = self.send(Command::Generate(model.clone(), request, cancel, tx)) {
|
||||
clear_active(&self.shared);
|
||||
return Err(error);
|
||||
}
|
||||
let result = self.wait(rx);
|
||||
if result.is_ok() {
|
||||
self.seen.insert(id);
|
||||
} else {
|
||||
clear_active(&self.shared);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> {
|
||||
let active = self
|
||||
.shared
|
||||
.active
|
||||
.lock()
|
||||
.map_err(|_| unavailable("native owner state unavailable"))?;
|
||||
match active.as_ref() {
|
||||
Some(active) if active.id == request_id => {
|
||||
active.cancel.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(invalid("generation is not active")),
|
||||
}
|
||||
}
|
||||
fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> {
|
||||
validate_handle(&model)?;
|
||||
self.idle()?;
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
self.send(Command::Unload(model, tx))?;
|
||||
self.wait(rx)
|
||||
}
|
||||
}
|
||||
impl Drop for Proxy {
|
||||
fn drop(&mut self) {
|
||||
self.shared.shutdown.store(true, Ordering::Release);
|
||||
cancel_active(&self.shared);
|
||||
}
|
||||
}
|
||||
struct OwnerGuard(Arc<Shared>);
|
||||
impl Drop for OwnerGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.ready.store(false, Ordering::Release);
|
||||
self.0.shutdown.store(true, Ordering::Release);
|
||||
cancel_active(&self.0);
|
||||
}
|
||||
}
|
||||
struct ActiveGuard<'a>(&'a Shared);
|
||||
impl Drop for ActiveGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
clear_active(self.0);
|
||||
}
|
||||
}
|
||||
fn cancel_active(shared: &Shared) {
|
||||
if let Ok(active) = shared.active.lock()
|
||||
&& let Some(active) = active.as_ref()
|
||||
{
|
||||
active.cancel.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
fn clear_active(shared: &Shared) {
|
||||
if let Ok(mut active) = shared.active.lock() {
|
||||
*active = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn owner(config: NativeBackendConfig, rx: Receiver<Command>, shared: &Shared, instance: u64) {
|
||||
let mut serial = 0_u64;
|
||||
while !shared.shutdown.load(Ordering::Acquire) {
|
||||
let command = match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(command) => command,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(_) => break,
|
||||
};
|
||||
match command {
|
||||
Command::Load(model, requested, reply) => {
|
||||
serial = match serial.checked_add(1) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
if let Err(error) = serve_load(
|
||||
&config,
|
||||
&rx,
|
||||
shared,
|
||||
model,
|
||||
requested,
|
||||
&reply,
|
||||
(instance, serial),
|
||||
) {
|
||||
let _ = reply.send(Err(error));
|
||||
}
|
||||
}
|
||||
Command::Generate(_, _, _, reply) => {
|
||||
clear_active(shared);
|
||||
let _ = reply.send(Err(invalid("no model is loaded")));
|
||||
}
|
||||
Command::Unload(_, reply) => {
|
||||
let _ = reply.send(Err(invalid("no model is loaded")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_load(
|
||||
config: &NativeBackendConfig,
|
||||
rx: &Receiver<Command>,
|
||||
shared: &Shared,
|
||||
model: ModelDescriptor,
|
||||
requested: RuntimeConfig,
|
||||
reply: &Reply<LoadedModel>,
|
||||
identity: (u64, u64),
|
||||
) -> Result<(), BackendError> {
|
||||
validate_load(&model, &requested)?;
|
||||
if requested
|
||||
.gpu_memory_limit_bytes
|
||||
.is_some_and(|limit| limit < config.gpu_budget_bytes)
|
||||
{
|
||||
return Err(exhausted(
|
||||
"requested memory ceiling is below native owner budget",
|
||||
));
|
||||
}
|
||||
let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0)
|
||||
.map_err(|_| invalid("pinned shard 0 verification failed"))?;
|
||||
let shard1 = VerifiedGgufFile::open(&config.shard1, SHARD1)
|
||||
.map_err(|_| invalid("pinned shard 1 verification failed"))?;
|
||||
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
|
||||
.map_err(|_| invalid("pinned model binding failed"))?;
|
||||
let metadata = artifact.tokenizer();
|
||||
let tokenizer = Tokenizer::from_vocabulary(
|
||||
&metadata.model,
|
||||
&metadata.pre,
|
||||
metadata.tokens.clone(),
|
||||
metadata.merges.clone(),
|
||||
metadata.token_types.clone(),
|
||||
)
|
||||
.map_err(|_| invalid("verified tokenizer construction failed"))?;
|
||||
let eos = *metadata
|
||||
.special_ids
|
||||
.get("tokenizer.ggml.eos_token_id")
|
||||
.ok_or_else(|| invalid("verified EOS is absent"))?;
|
||||
let binding = ModelBinding::from_artifact(artifact)
|
||||
.map_err(|_| invalid("native input binding failed"))?;
|
||||
if shared.shutdown.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native load cancelled"));
|
||||
}
|
||||
let driver = Driver::load().map_err(|_| unavailable("CUDA driver unavailable"))?;
|
||||
let device = driver
|
||||
.device(config.gpu_device_ordinal as i32)
|
||||
.map_err(|_| unavailable("CUDA device unavailable"))?;
|
||||
let context = Rc::new(
|
||||
device
|
||||
.create_context(config.gpu_budget_bytes as usize)
|
||||
.map_err(|_| exhausted("native CUDA context unavailable"))?,
|
||||
);
|
||||
let output = OutputStage::load(&binding, context.as_ref())
|
||||
.map_err(|_| exhausted("native output head initialization failed"))?;
|
||||
// Exercise only structural session initialization; no synthetic inference
|
||||
// or repeated model/GPU qualification is performed during load.
|
||||
let initial_session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
|
||||
drop(initial_session);
|
||||
let loaded = LoadedModel {
|
||||
handle: format!(
|
||||
"native-{}-{}-{}",
|
||||
std::process::id(),
|
||||
identity.0,
|
||||
identity.1
|
||||
),
|
||||
descriptor: model,
|
||||
load_config_version: LOAD_CONFIG_VERSION,
|
||||
effective_mode: InferenceMode::Native,
|
||||
mode_identity_digest: MODE_DIGEST.into(),
|
||||
};
|
||||
loaded
|
||||
.validate_for_load(&loaded.descriptor, &requested)
|
||||
.map_err(|_| unavailable("native load identity failed"))?;
|
||||
if shared.shutdown.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native load cancelled"));
|
||||
}
|
||||
shared.ready.store(true, Ordering::Release);
|
||||
if reply.send(Ok(loaded.clone())).is_err() {
|
||||
shared.ready.store(false, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
let mut unload_reply = None;
|
||||
while !shared.shutdown.load(Ordering::Acquire) {
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(_) => break,
|
||||
Ok(Command::Load(_, _, reply)) => {
|
||||
let _ = reply.send(Err(exhausted(
|
||||
"unload the existing model before another load",
|
||||
)));
|
||||
}
|
||||
Ok(Command::Unload(candidate, reply)) => {
|
||||
if candidate != loaded {
|
||||
let _ = reply.send(Err(invalid("unknown loaded model handle")));
|
||||
} else {
|
||||
unload_reply = Some(reply);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Command::Generate(candidate, request, cancel, reply)) => {
|
||||
let _guard = ActiveGuard(shared);
|
||||
if candidate != loaded {
|
||||
let _ = reply.send(Err(invalid("unknown loaded model handle")));
|
||||
continue;
|
||||
}
|
||||
if !shared.ready.load(Ordering::Acquire) {
|
||||
let _ = reply.send(Err(unavailable("native model is not ready")));
|
||||
continue;
|
||||
}
|
||||
let prompt = match prepare_prompt(&tokenizer, &request, config.context_tokens) {
|
||||
Ok(prompt) => prompt,
|
||||
Err(error) => {
|
||||
let _ = reply.send(Err(error));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (sink, stream) = GenerationSink::bounded_channel(QUEUE)
|
||||
.map_err(|_| unavailable("generation queue unavailable"))?;
|
||||
if reply.send(Ok(stream)).is_err() {
|
||||
continue;
|
||||
}
|
||||
let mut session =
|
||||
QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
|
||||
let run = Generation {
|
||||
binding: &binding,
|
||||
output: &output,
|
||||
session: &mut session,
|
||||
tokenizer: &tokenizer,
|
||||
sink: &sink,
|
||||
cancel: &cancel,
|
||||
shared,
|
||||
context_tokens: config.context_tokens,
|
||||
eos,
|
||||
};
|
||||
let result = generate(run, &prompt, request.max_output_tokens);
|
||||
let terminal = match result {
|
||||
Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage },
|
||||
Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled,
|
||||
Err(GenerationFailure::Backend(error)) => GenerationTerminal::Failed {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
retryable: false,
|
||||
},
|
||||
};
|
||||
// Terminal publication is bounded too; after transport loss,
|
||||
// closing without a terminal is reported as MissingTerminal.
|
||||
let _ = emit_terminal(&sink, terminal);
|
||||
}
|
||||
}
|
||||
}
|
||||
shared.ready.store(false, Ordering::Release);
|
||||
drop(output);
|
||||
let closed = Rc::try_unwrap(context)
|
||||
.map_err(|_| unavailable("native context still borrowed"))?
|
||||
.close()
|
||||
.map_err(|_| unavailable("native context cleanup failed"));
|
||||
if closed.is_err() {
|
||||
shared.shutdown.store(true, Ordering::Release);
|
||||
}
|
||||
if let Some(reply) = unload_reply {
|
||||
let _ = reply.send(closed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_load(model: &ModelDescriptor, config: &RuntimeConfig) -> Result<(), BackendError> {
|
||||
config
|
||||
.validate()
|
||||
.map_err(|_| invalid("invalid load configuration"))?;
|
||||
if model != &pinned_model_descriptor() {
|
||||
return Err(unsupported("unsupported pinned model identity"));
|
||||
}
|
||||
if config.inference_mode != InferenceMode::Native {
|
||||
return Err(unsupported("experimental mode is not model-qualified"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn validate_handle(model: &LoadedModel) -> Result<(), BackendError> {
|
||||
if model.handle.is_empty()
|
||||
|| model.handle.len() > 128
|
||||
|| model.handle.chars().any(char::is_control)
|
||||
|| model.descriptor != pinned_model_descriptor()
|
||||
|| model.load_config_version != LOAD_CONFIG_VERSION
|
||||
|| model.effective_mode != InferenceMode::Native
|
||||
|| model.mode_identity_digest != MODE_DIGEST
|
||||
{
|
||||
return Err(invalid("invalid loaded model identity"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> {
|
||||
if request.request_id.is_empty()
|
||||
|| request.request_id.len() > 128
|
||||
|| request.request_id.chars().any(char::is_control)
|
||||
|| request.prompt.len() > PROMPT_LIMIT
|
||||
|| request.max_output_tokens == 0
|
||||
|| request.max_output_tokens > OUTPUT_LIMIT
|
||||
|| request.temperature_milli != 0
|
||||
{
|
||||
return Err(invalid("unsupported generation request"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn prepare_prompt(
|
||||
tokenizer: &Tokenizer,
|
||||
request: &GenerationRequest,
|
||||
context: u32,
|
||||
) -> Result<Vec<u32>, BackendError> {
|
||||
validate_request(request)?;
|
||||
let tokens = tokenizer
|
||||
.encode(&request.prompt, true)
|
||||
.map_err(|_| invalid("prompt tokenization failed"))?;
|
||||
if tokens.is_empty()
|
||||
|| tokens
|
||||
.len()
|
||||
.checked_add(request.max_output_tokens as usize)
|
||||
.is_none_or(|total| total > context as usize)
|
||||
{
|
||||
return Err(exhausted("prompt and output exceed configured context"));
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
/// The operator ceiling governs admission, while the opaque Position carries
|
||||
/// the verified model dimension used by every stage's identity validation.
|
||||
fn native_position(
|
||||
constants: &InputConstants,
|
||||
configured: u32,
|
||||
value: usize,
|
||||
) -> Result<Position, BackendError> {
|
||||
let model_context = constants.context_length();
|
||||
if configured == 0 || configured > model_context {
|
||||
return Err(invalid("native context configuration invalid"));
|
||||
}
|
||||
let value = u64::try_from(value).map_err(|_| exhausted("native context exhausted"))?;
|
||||
if value >= u64::from(configured) {
|
||||
return Err(exhausted("native configured context exhausted"));
|
||||
}
|
||||
let bound = Dimension::new(u64::from(model_context))
|
||||
.map_err(|_| invalid("verified native context invalid"))?;
|
||||
Position::new(value, bound).map_err(|_| exhausted("native model context exhausted"))
|
||||
}
|
||||
|
||||
struct Generation<'a, 'context, 'driver> {
|
||||
binding: &'a ModelBinding,
|
||||
output: &'a OutputStage<'context, 'driver>,
|
||||
session: &'a mut QwenSession<'driver>,
|
||||
tokenizer: &'a Tokenizer,
|
||||
sink: &'a GenerationSink,
|
||||
cancel: &'a AtomicBool,
|
||||
shared: &'a Shared,
|
||||
context_tokens: u32,
|
||||
eos: u32,
|
||||
}
|
||||
enum GenerationFailure {
|
||||
Cancelled,
|
||||
Backend(BackendError),
|
||||
}
|
||||
impl From<BackendError> for GenerationFailure {
|
||||
fn from(error: BackendError) -> Self {
|
||||
Self::Backend(error)
|
||||
}
|
||||
}
|
||||
impl Generation<'_, '_, '_> {
|
||||
fn cancelled(&self) -> bool {
|
||||
self.cancel.load(Ordering::Acquire)
|
||||
|| self.shared.shutdown.load(Ordering::Acquire)
|
||||
|| self.sink.is_closed()
|
||||
}
|
||||
fn step(&mut self, token: u32, position: usize) -> Result<u32, GenerationFailure> {
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
let vocabulary =
|
||||
Dimension::new(248_320).map_err(|_| invalid("native vocabulary invalid"))?;
|
||||
|
||||
let token = TokenId::new(u64::from(token), vocabulary)
|
||||
.map_err(|_| invalid("native token invalid"))?;
|
||||
let position = native_position(
|
||||
self.binding.input_constants(),
|
||||
self.context_tokens,
|
||||
position,
|
||||
)?;
|
||||
let token =
|
||||
QwenForward::step_with_output(self.binding, token, position, self.session, self.output)
|
||||
.map_err(|failure| {
|
||||
// Fixed enums and numeric position only; no token/prompt/path
|
||||
// diagnostics. A stderr failure cannot replace the real error.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"leleka-native phase=forward position={} error={failure:?}",
|
||||
position.get()
|
||||
);
|
||||
// A failed full step never commits its session. Keep the retained
|
||||
// owners for explicit unload, but withdraw serving readiness.
|
||||
self.shared.ready.store(false, Ordering::Release);
|
||||
match failure {
|
||||
crate::qwen_forward::contract::Error::InputAllocation => {
|
||||
exhausted("native step allocation failed")
|
||||
}
|
||||
crate::qwen_forward::contract::Error::Unsupported(_) => {
|
||||
unsupported("native forward operator unavailable")
|
||||
}
|
||||
crate::qwen_forward::contract::Error::NonFinite => error(
|
||||
ErrorCode::Internal,
|
||||
"native forward produced invalid values",
|
||||
),
|
||||
_ => unavailable("native forward failed"),
|
||||
}
|
||||
})?;
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
Ok(token.get())
|
||||
}
|
||||
fn emit(&self, event: GenerationEvent) -> Result<(), GenerationFailure> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
match self.sink.try_emit(event.clone()) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(ContractError::GenerationBackpressure)
|
||||
if start.elapsed() < BACKPRESSURE_TIMEOUT =>
|
||||
{
|
||||
thread::sleep(Duration::from_millis(5))
|
||||
}
|
||||
Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled),
|
||||
_ => {
|
||||
return Err(
|
||||
exhausted("generation output backpressure deadline exceeded").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn generate(
|
||||
mut run: Generation<'_, '_, '_>,
|
||||
prompt: &[u32],
|
||||
max: u32,
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
let start = Instant::now();
|
||||
let mut next = 0;
|
||||
for (position, &token) in prompt.iter().enumerate() {
|
||||
if start.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
next = run.step(token, position)?;
|
||||
}
|
||||
let mut utf8 = Utf8Pending::default();
|
||||
let mut count = 0;
|
||||
for index in 0..max {
|
||||
if start.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
if run.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
if next == run.eos {
|
||||
utf8.finish()?;
|
||||
let usage = Usage {
|
||||
input_tokens: prompt.len() as u64,
|
||||
output_tokens: count + 1,
|
||||
reused_input_tokens: 0,
|
||||
};
|
||||
run.emit(GenerationEvent::Usage(usage.clone()))?;
|
||||
return Ok((FinishReason::Stop, usage));
|
||||
}
|
||||
let bytes = run
|
||||
.tokenizer
|
||||
.decode_bytes(&[next])
|
||||
.map_err(|_| unavailable("native token decoding failed"))?;
|
||||
if let Some(text) = utf8.push(&bytes)? {
|
||||
run.emit(GenerationEvent::TextDelta { text })?;
|
||||
}
|
||||
count += 1;
|
||||
if index + 1 < max {
|
||||
next = run.step(next, prompt.len() + index as usize)?;
|
||||
}
|
||||
}
|
||||
utf8.finish()?;
|
||||
let usage = Usage {
|
||||
input_tokens: prompt.len() as u64,
|
||||
output_tokens: count,
|
||||
reused_input_tokens: 0,
|
||||
};
|
||||
run.emit(GenerationEvent::Usage(usage.clone()))?;
|
||||
Ok((FinishReason::Length, usage))
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Utf8Pending(Vec<u8>);
|
||||
impl Utf8Pending {
|
||||
fn push(&mut self, bytes: &[u8]) -> Result<Option<String>, BackendError> {
|
||||
if self
|
||||
.0
|
||||
.len()
|
||||
.checked_add(bytes.len())
|
||||
.is_none_or(|len| len > FRAME_LIMIT)
|
||||
{
|
||||
return Err(exhausted("decoded token exceeds output frame limit"));
|
||||
}
|
||||
self.0
|
||||
.try_reserve(bytes.len())
|
||||
.map_err(|_| exhausted("token decoding allocation failed"))?;
|
||||
self.0.extend_from_slice(bytes);
|
||||
let valid = match std::str::from_utf8(&self.0) {
|
||||
Ok(_) => self.0.len(),
|
||||
Err(error) if error.error_len().is_none() => error.valid_up_to(),
|
||||
Err(_) => return Err(unavailable("native token contains invalid UTF8")),
|
||||
};
|
||||
if valid == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let text = std::str::from_utf8(&self.0[..valid])
|
||||
.map_err(|_| unavailable("native UTF8 prefix invalid"))?
|
||||
.to_owned();
|
||||
self.0.drain(..valid);
|
||||
Ok(Some(text))
|
||||
}
|
||||
fn finish(&self) -> Result<(), BackendError> {
|
||||
if self.0.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(unavailable("generation ended with incomplete UTF8"))
|
||||
}
|
||||
}
|
||||
}
|
||||
fn emit_terminal(sink: &GenerationSink, terminal: GenerationTerminal) -> Result<(), ContractError> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match sink.try_emit(GenerationEvent::Terminal(terminal.clone())) {
|
||||
Err(ContractError::GenerationBackpressure)
|
||||
if start.elapsed() < BACKPRESSURE_TIMEOUT =>
|
||||
{
|
||||
thread::sleep(Duration::from_millis(5))
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn error(code: ErrorCode, message: &'static str) -> BackendError {
|
||||
BackendError {
|
||||
code,
|
||||
message: message.into(),
|
||||
retryable: false,
|
||||
}
|
||||
}
|
||||
fn invalid(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::InvalidRequest, message)
|
||||
}
|
||||
fn unsupported(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::UnsupportedModel, message)
|
||||
}
|
||||
fn exhausted(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::ResourceExhausted, message)
|
||||
}
|
||||
fn unavailable(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::BackendUnavailable, message)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn native_config() -> RuntimeConfig {
|
||||
RuntimeConfig {
|
||||
load_config_version: LOAD_CONFIG_VERSION,
|
||||
inference_mode: InferenceMode::Native,
|
||||
gpu_memory_limit_bytes: None,
|
||||
allow_experimental: false,
|
||||
}
|
||||
}
|
||||
fn request() -> GenerationRequest {
|
||||
GenerationRequest {
|
||||
request_id: "synthetic-1".into(),
|
||||
prompt: "x".into(),
|
||||
max_output_tokens: 1,
|
||||
temperature_milli: 0,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn configured_context_admission_preserves_verified_position_identity() {
|
||||
let constants = InputConstants::test_fixture();
|
||||
let model_bound = Dimension::new(u64::from(constants.context_length())).unwrap();
|
||||
let configured_bound = Dimension::new(128).unwrap();
|
||||
for value in [0, 127] {
|
||||
let position = native_position(&constants, 128, value).unwrap();
|
||||
assert_eq!(position, Position::new(value as u64, model_bound).unwrap());
|
||||
assert_ne!(
|
||||
position,
|
||||
Position::new(value as u64, configured_bound).unwrap()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
native_position(&constants, 128, 128).unwrap_err().code,
|
||||
ErrorCode::ResourceExhausted
|
||||
);
|
||||
assert!(native_position(&constants, 0, 0).is_err());
|
||||
assert!(native_position(&constants, constants.context_length() + 1, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_identity_and_native_refusal_precede_artifact_access() {
|
||||
let model = pinned_model_descriptor();
|
||||
assert_eq!(model.artifact_digest, MODEL_DIGEST);
|
||||
assert!(validate_load(&model, &native_config()).is_ok());
|
||||
let mut config = native_config();
|
||||
config.allow_experimental = true;
|
||||
assert!(validate_load(&model, &config).is_ok());
|
||||
config.inference_mode = InferenceMode::ExperimentalKarPle {
|
||||
profile_id: "synthetic".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
validate_load(&model, &config).unwrap_err().code,
|
||||
ErrorCode::UnsupportedModel
|
||||
);
|
||||
let mut loaded = LoadedModel {
|
||||
handle: "synthetic-handle".into(),
|
||||
descriptor: model.clone(),
|
||||
load_config_version: LOAD_CONFIG_VERSION,
|
||||
effective_mode: InferenceMode::Native,
|
||||
mode_identity_digest: MODE_DIGEST.into(),
|
||||
};
|
||||
assert!(validate_handle(&loaded).is_ok());
|
||||
loaded.handle = "x".repeat(129);
|
||||
assert!(validate_handle(&loaded).is_err());
|
||||
let mut wrong = model;
|
||||
wrong.artifact_digest = SHARD0.into();
|
||||
assert!(validate_load(&wrong, &native_config()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn request_caps_are_checked_before_acceptance() {
|
||||
let mut r = request();
|
||||
assert!(validate_request(&r).is_ok());
|
||||
r.max_output_tokens = 4097;
|
||||
assert!(validate_request(&r).is_err());
|
||||
r.max_output_tokens = 1;
|
||||
r.temperature_milli = 1;
|
||||
assert!(validate_request(&r).is_err());
|
||||
r.temperature_milli = 0;
|
||||
r.prompt = "x".repeat(PROMPT_LIMIT + 1);
|
||||
assert!(validate_request(&r).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn utf8_split_tokens_publish_only_complete_prefix() {
|
||||
let mut pending = Utf8Pending::default();
|
||||
assert_eq!(pending.push(&[b'a', 0xf0]).unwrap(), Some("a".into()));
|
||||
assert!(pending.finish().is_err());
|
||||
assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None);
|
||||
assert_eq!(pending.push(&[0x80]).unwrap(), Some("😀".into()));
|
||||
assert!(pending.finish().is_ok());
|
||||
assert!(pending.push(&[0xff]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn utf8_frame_bound_refuses_before_growth() {
|
||||
let mut pending = Utf8Pending::default();
|
||||
assert!(pending.push(&vec![b'x'; FRAME_LIMIT + 1]).is_err());
|
||||
assert!(pending.0.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn cancel_is_independent_of_full_control_queue() {
|
||||
let (tx, _rx) = mpsc::sync_channel(1);
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let shared = Arc::new(Shared {
|
||||
ready: AtomicBool::new(true),
|
||||
shutdown: AtomicBool::new(false),
|
||||
active: Mutex::new(Some(Active {
|
||||
id: "synthetic-1".into(),
|
||||
cancel: Arc::clone(&cancel),
|
||||
})),
|
||||
});
|
||||
let mut proxy = Proxy {
|
||||
tx,
|
||||
shared,
|
||||
seen: HashSet::new(),
|
||||
};
|
||||
let (reply, _) = mpsc::sync_channel(1);
|
||||
proxy
|
||||
.send(Command::Load(
|
||||
pinned_model_descriptor(),
|
||||
native_config(),
|
||||
reply,
|
||||
))
|
||||
.unwrap();
|
||||
proxy.cancel("synthetic-1").unwrap();
|
||||
assert!(cancel.load(Ordering::Acquire));
|
||||
assert!(proxy.cancel("unknown").is_err());
|
||||
assert!(proxy.idle().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn prompt_context_admission_is_before_forward() {
|
||||
let tokenizer =
|
||||
Tokenizer::from_vocabulary("gpt2", "qwen35", vec!["x".into()], vec![], None).unwrap();
|
||||
assert_eq!(prepare_prompt(&tokenizer, &request(), 2).unwrap(), vec![0]);
|
||||
assert!(prepare_prompt(&tokenizer, &request(), 1).is_err());
|
||||
let mut r = request();
|
||||
r.prompt.clear();
|
||||
assert!(prepare_prompt(&tokenizer, &r, 2).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Private runtime bootstrap. The declared contract and leaf shells are supplied
|
||||
//! by the sequential bootstrap phase; no runnable model is exposed here.
|
||||
//! Independent Qwen runtime. CUDA state stays inside its dedicated owner thread.
|
||||
|
||||
pub mod backend;
|
||||
|
||||
pub(crate) mod model_binding;
|
||||
pub(crate) mod qwen_forward;
|
||||
|
||||
@@ -96,6 +96,50 @@ impl Tokenizer {
|
||||
{
|
||||
return Err("token type count mismatch".into());
|
||||
}
|
||||
for &id in config.special_ids.values() {
|
||||
if id as usize >= tokens.len() {
|
||||
return Err("special token ID exceeds vocabulary".into());
|
||||
}
|
||||
}
|
||||
drop(vocab);
|
||||
Self::from_vocabulary(
|
||||
&config.model,
|
||||
&config.pre,
|
||||
tokens,
|
||||
merges.into_iter().map(str::to_owned).collect(),
|
||||
token_types,
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct the same tokenizer from already verified model metadata.
|
||||
pub fn from_vocabulary(
|
||||
model: &str,
|
||||
pre: &str,
|
||||
tokens: Vec<String>,
|
||||
merges: Vec<String>,
|
||||
token_types: Option<Vec<u32>>,
|
||||
) -> Result<Self> {
|
||||
if model != "gpt2" || pre != "qwen35" {
|
||||
return Err("unsupported tokenizer configuration".into());
|
||||
}
|
||||
if tokens.is_empty() || tokens.len() > u32::MAX as usize {
|
||||
return Err("vocabulary size mismatch".into());
|
||||
}
|
||||
let mut vocab = HashMap::with_capacity(tokens.len());
|
||||
for (id, token) in tokens.iter().enumerate() {
|
||||
if token.is_empty()
|
||||
|| token.contains('\0')
|
||||
|| vocab.insert(token.clone(), id as u32).is_some()
|
||||
{
|
||||
return Err("vocabulary contains NUL or duplicate tokens".into());
|
||||
}
|
||||
}
|
||||
if token_types
|
||||
.as_ref()
|
||||
.is_some_and(|types| types.len() != tokens.len())
|
||||
{
|
||||
return Err("token type count mismatch".into());
|
||||
}
|
||||
let mut ranks = HashMap::with_capacity(merges.len());
|
||||
for (rank, merge) in merges.iter().enumerate() {
|
||||
let Some((left, right)) = merge.split_once(' ') else {
|
||||
@@ -111,11 +155,6 @@ impl Tokenizer {
|
||||
return Err("BPE merge is invalid or duplicated".into());
|
||||
}
|
||||
}
|
||||
for &id in config.special_ids.values() {
|
||||
if id as usize >= tokens.len() {
|
||||
return Err("special token ID exceeds vocabulary".into());
|
||||
}
|
||||
}
|
||||
let types = token_types.unwrap_or_default();
|
||||
let always = literal_matcher(&tokens, &types, false)?;
|
||||
let special = literal_matcher(&tokens, &types, true)?;
|
||||
@@ -371,6 +410,23 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn verified_vocabulary_constructor_rejects_invalid_metadata() {
|
||||
let build = |tokens, merges, types| {
|
||||
Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, merges, types)
|
||||
};
|
||||
assert!(build(vec![], vec![], None).is_err());
|
||||
assert!(build(vec![String::new()], vec![], None).is_err());
|
||||
assert!(build(vec!["a".into(), "a".into()], vec![], None).is_err());
|
||||
assert!(build(vec!["a\0".into()], vec![], None).is_err());
|
||||
assert!(build(vec!["a".into()], vec![], Some(vec![])).is_err());
|
||||
assert!(build(vec!["a".into()], vec!["a missing".into()], None).is_err());
|
||||
assert!(
|
||||
Tokenizer::from_vocabulary("unknown", "qwen35", vec!["a".into()], vec![], None)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_alphabet_is_bijective() {
|
||||
let (forward, reverse) = byte_alphabet();
|
||||
@@ -455,6 +511,31 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let tokenizer = Tokenizer::from_assets(&root).unwrap();
|
||||
let retained = Tokenizer::from_vocabulary(
|
||||
"gpt2",
|
||||
"qwen35",
|
||||
tokens,
|
||||
"H e\nHe l\nl l\nll o\nx x\nxx xx"
|
||||
.split('\n')
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
Some(types),
|
||||
)
|
||||
.unwrap();
|
||||
for text in [
|
||||
"Hello, world!",
|
||||
"😀",
|
||||
"<|im_end|>",
|
||||
"<tool_response>",
|
||||
"e\u{301}",
|
||||
] {
|
||||
for special in [false, true] {
|
||||
assert_eq!(
|
||||
tokenizer.encode(text, special).unwrap(),
|
||||
retained.encode(text, special).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
tokenizer.encode("Hello, world!", false).unwrap(),
|
||||
vec![257, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
|
||||
|
||||
@@ -9,6 +9,8 @@ name = "strata-desktop"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
leleka-backend-api = { path = "../crates/backend-api" }
|
||||
leleka-runtime = { path = "../crates/leleka-runtime" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sysinfo = { version = "0.39.6", default-features = false, features = ["system"] }
|
||||
|
||||
@@ -3,9 +3,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?);
|
||||
tonic_prost_build::configure().compile_with_config(
|
||||
config,
|
||||
&["proto/node.proto"],
|
||||
&["proto/node.proto", "proto/runtime.proto"],
|
||||
&["proto"],
|
||||
)?;
|
||||
println!("cargo:rerun-if-changed=proto/node.proto");
|
||||
println!("cargo:rerun-if-changed=proto/runtime.proto");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
syntax = "proto3";
|
||||
package leleka.runtime.v1;
|
||||
|
||||
// Separate inference-process contract; strata.node.v1 is unchanged.
|
||||
service Runtime {
|
||||
rpc Handshake(Hello) returns (.leleka.runtime.v1.Snapshot);
|
||||
rpc Snapshot(Empty) returns (.leleka.runtime.v1.Snapshot);
|
||||
rpc Watch(Cursor) returns (stream .leleka.runtime.v1.Snapshot);
|
||||
rpc Load(LoadRequest) returns (OperationResult);
|
||||
rpc Unload(UnloadRequest) returns (OperationResult);
|
||||
rpc Operation(OperationQuery) returns (OperationResult);
|
||||
rpc Generate(GenerateRequest) returns (stream GenerationFrame);
|
||||
rpc Cancel(CancelRequest) returns (CancelAck);
|
||||
}
|
||||
message Empty {}
|
||||
message Hello { uint32 protocol_version = 1; uint32 backend_api_version = 2; }
|
||||
message Cursor { string epoch = 1; uint64 sequence = 2; }
|
||||
message ModelDescriptor {
|
||||
string family = 1;
|
||||
string architecture = 2;
|
||||
string artifact_digest = 3;
|
||||
string weight_format = 4;
|
||||
}
|
||||
message NativeMode {}
|
||||
message KarPleMode { string profile_id = 1; }
|
||||
message KarExpertsMode {
|
||||
string bundle_directory = 1; string archive_file = 2;
|
||||
string binding_file = 3; string provenance_file = 4;
|
||||
uint32 levels = 5; uint32 cache_mib = 6;
|
||||
enum Prefill { UNSPECIFIED = 0; DECODE_ONLY = 1; ALL_ROUTED_BATCHED = 2; }
|
||||
Prefill prefill_mode = 7;
|
||||
}
|
||||
message InferenceMode {
|
||||
oneof selection { NativeMode native = 1; KarPleMode kar_ple = 2; KarExpertsMode kar_experts = 3; }
|
||||
}
|
||||
message LoadConfig {
|
||||
uint32 version = 1; InferenceMode mode = 2;
|
||||
optional uint64 gpu_memory_limit_bytes = 3; bool allow_experimental = 4;
|
||||
}
|
||||
message LoadedModel {
|
||||
string handle = 1; ModelDescriptor descriptor = 2;
|
||||
uint32 load_config_version = 3; InferenceMode effective_mode = 4;
|
||||
string mode_identity_digest = 5;
|
||||
}
|
||||
message SupportedModelTuple { string family = 1; string architecture = 2; string weight_format = 3; }
|
||||
message Capabilities {
|
||||
repeated SupportedModelTuple models = 1;
|
||||
uint32 max_concurrent_generations = 2;
|
||||
bool cancellation = 3; bool tool_call_streaming = 4;
|
||||
}
|
||||
message Snapshot {
|
||||
uint32 protocol_version = 1; uint32 backend_api_version = 2;
|
||||
string epoch = 3; uint64 sequence = 4; bool full_snapshot = 5;
|
||||
bool transport_ready = 6; bool model_ready = 7;
|
||||
LoadedModel loaded = 8; Capabilities capabilities = 9;
|
||||
string active_request_id = 10;
|
||||
}
|
||||
message LoadRequest { string operation_id = 1; string expected_epoch = 2; ModelDescriptor model = 3; LoadConfig config = 4; }
|
||||
message UnloadRequest { string operation_id = 1; string expected_epoch = 2; string handle = 3; }
|
||||
message OperationQuery { string operation_id = 1; string expected_epoch = 2; }
|
||||
message OperationResult {
|
||||
string operation_id = 1; string epoch = 2;
|
||||
enum State { UNSPECIFIED = 0; ACCEPTED = 1; COMPLETED = 2; FAILED = 3; INDETERMINATE = 4; }
|
||||
State state = 3; string reason = 4; LoadedModel loaded = 5;
|
||||
}
|
||||
message GenerateRequest {
|
||||
string request_id = 1; string expected_epoch = 2; string handle = 3;
|
||||
string prompt = 4; uint32 max_output_tokens = 5; uint32 temperature_milli = 6;
|
||||
}
|
||||
message CancelRequest { string request_id = 1; string expected_epoch = 2; }
|
||||
message CancelAck { string request_id = 1; string epoch = 2; bool acknowledged = 3; }
|
||||
message Accepted { bool accepted = 1; }
|
||||
message TextDelta { string text = 1; }
|
||||
message ToolCallDelta { uint32 index = 1; optional string id = 2; optional string name = 3; string arguments_delta = 4; }
|
||||
message Usage { uint64 input_tokens = 1; uint64 output_tokens = 2; uint64 reused_input_tokens = 3; }
|
||||
message Terminal {
|
||||
enum State { UNSPECIFIED = 0; COMPLETED = 1; FAILED = 2; CANCELLED = 3; }
|
||||
State state = 1; string reason = 2; Usage usage = 3;
|
||||
string error_code = 4; bool retryable = 5;
|
||||
}
|
||||
message GenerationFrame {
|
||||
string request_id = 1; string epoch = 2; uint64 sequence = 3;
|
||||
oneof payload { Accepted accepted = 4; TextDelta text = 5; ToolCallDelta tool = 6; Usage usage = 7; Terminal terminal = 8; }
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Configuration and typed lifecycle control through the local daemon.
|
||||
use serde_json::{Value, json};
|
||||
use std::{path::Path, time::Duration};
|
||||
use strata_desktop_core::runtime_gateway::Config;
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.as_slice() == ["--help"] {
|
||||
println!(
|
||||
"leleka-cli --config PATH validate|models|status|load MODEL native|load MODEL kar-ple PROFILE|unload MODEL|operation MODEL UUID EPOCH\nLoad and unload print an operation UUID before sending. They never retry uncertain commands; query that UUID with operation."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if args.len() < 3 || args[0] != "--config" {
|
||||
return Err("invalid_cli_arguments".into());
|
||||
}
|
||||
let config = Config::read(Path::new(&args[1]))?;
|
||||
let command: Vec<&str> = args[2..].iter().map(String::as_str).collect();
|
||||
if command.as_slice() == ["validate"] {
|
||||
println!("configuration_valid");
|
||||
return Ok(());
|
||||
}
|
||||
let token = config.credential()?;
|
||||
let client = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()?;
|
||||
let base = format!("http://{}", config.listen);
|
||||
let (route, body) = match command.as_slice() {
|
||||
["models"] => ("/v1/models", None),
|
||||
["status"] => ("/runtime/status", None),
|
||||
["operation", model, id, epoch] => {
|
||||
uuid::Uuid::parse_str(id).map_err(|_| "invalid_operation_id")?;
|
||||
uuid::Uuid::parse_str(epoch).map_err(|_| "invalid_epoch")?;
|
||||
(
|
||||
"/runtime/operation",
|
||||
Some(json!({"model":model,"operation_id":id,"epoch":epoch})),
|
||||
)
|
||||
}
|
||||
["load", model, "native"] | ["load", model, "kar-ple", _] | ["unload", model] => {
|
||||
if !config.runtimes.iter().any(|m| m.id == *model) {
|
||||
return Err("unknown_model".into());
|
||||
}
|
||||
let state = request(&client, &base, &token, "/runtime/status", None).await?;
|
||||
let epoch = state["runtimes"]
|
||||
.as_array()
|
||||
.and_then(|states| states.iter().find(|s| s["id"] == *model))
|
||||
.and_then(|s| s["epoch"].as_str())
|
||||
.ok_or("runtime_not_connected")?;
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
// Operator can reconcile this exact command even if the response is lost.
|
||||
println!("{}", json!({"operation_id":id,"epoch":epoch,"model":model}));
|
||||
let mut body = json!({"model":model,"operation_id":id,"epoch":epoch});
|
||||
let route = if command[0] == "load" {
|
||||
body["mode"] = json!(command[2]);
|
||||
if command[2] == "kar-ple" {
|
||||
body["profile_id"] = json!(command[3]);
|
||||
}
|
||||
"/runtime/load"
|
||||
} else {
|
||||
let handle = state["runtimes"]
|
||||
.as_array()
|
||||
.and_then(|states| states.iter().find(|s| s["id"] == *model))
|
||||
.and_then(|s| s["loaded_handle"].as_str())
|
||||
.ok_or("model_not_loaded")?;
|
||||
body["handle"] = json!(handle);
|
||||
"/runtime/unload"
|
||||
};
|
||||
(route, Some(body))
|
||||
}
|
||||
_ => return Err("invalid_cli_arguments".into()),
|
||||
};
|
||||
let result = request(&client, &base, &token, route, body).await?;
|
||||
println!("{}", serde_json::to_string_pretty(&result)?);
|
||||
Ok(())
|
||||
}
|
||||
async fn request(
|
||||
client: &reqwest::Client,
|
||||
base: &str,
|
||||
token: &str,
|
||||
route: &str,
|
||||
body: Option<Value>,
|
||||
) -> Result<Value, Box<dyn std::error::Error>> {
|
||||
let mut request = match body {
|
||||
Some(body) => client
|
||||
.post(format!("{base}{route}"))
|
||||
.header("content-type", "application/json")
|
||||
.body(serde_json::to_vec(&body)?),
|
||||
None => client.get(format!("{base}{route}")),
|
||||
};
|
||||
request = request.bearer_auth(token);
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| "daemon_request_outcome_unknown")?;
|
||||
let status = response.status();
|
||||
use futures_util::StreamExt;
|
||||
let mut stream = response.bytes_stream();
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|_| "daemon_response_interrupted")?;
|
||||
if bytes.len() + chunk.len() > 1024 * 1024 {
|
||||
return Err("daemon_response_limit".into());
|
||||
}
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
let value: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid_daemon_response")?;
|
||||
if !status.is_success() {
|
||||
// Only fixed error fields from our authenticated daemon, no server diagnostics.
|
||||
println!(
|
||||
"{}",
|
||||
json!({"http_status":status.as_u16(),"operation_id":value.get("operation_id"),"epoch":value.get("epoch"),"state":value.get("state")})
|
||||
);
|
||||
return Err("daemon_command_failed".into());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Local OpenAI gateway for an explicit set of authenticated gRPC runtimes.
|
||||
use std::path::Path;
|
||||
use strata_desktop_core::runtime_gateway::{Config, Registry};
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.as_slice() == ["--help"] {
|
||||
println!("leleka-daemon --config PATH");
|
||||
return Ok(());
|
||||
}
|
||||
let [flag, path] = args.as_slice() else {
|
||||
return Err("invalid_daemon_arguments".into());
|
||||
};
|
||||
if flag != "--config" {
|
||||
return Err("invalid_daemon_arguments".into());
|
||||
}
|
||||
let config = Config::read(Path::new(path))?;
|
||||
let listener = tokio::net::TcpListener::bind(config.listen).await?;
|
||||
let registry = Registry::new(config)?;
|
||||
let monitor = registry.clone();
|
||||
let monitor = tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
interval.tick().await;
|
||||
monitor.refresh().await;
|
||||
}
|
||||
});
|
||||
let (stop, stopped) = tokio::sync::oneshot::channel();
|
||||
let serving = axum::serve(listener, registry.router()).with_graceful_shutdown(async {
|
||||
let _ = stopped.await;
|
||||
});
|
||||
let serving = std::future::IntoFuture::into_future(serving);
|
||||
tokio::pin!(serving);
|
||||
let result = tokio::select! {
|
||||
result = &mut serving => result,
|
||||
_ = tokio::signal::ctrl_c() => {
|
||||
let _ = stop.send(());
|
||||
// Dropping the bounded grace future closes stalled streams; their
|
||||
// RuntimeGeneration drop path requests cancellation without replay.
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(10), &mut serving).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
};
|
||||
monitor.abort();
|
||||
let _ = monitor.await;
|
||||
result?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Linux CUDA inference process. Operator-owned artifact paths never enter RPCs.
|
||||
use leleka_runtime::backend::{NativeBackendConfig, spawn_backend};
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
use strata_desktop_core::runtime_rpc::RuntimeServer;
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.as_slice() == ["--help"] {
|
||||
println!(
|
||||
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let [
|
||||
l,
|
||||
address,
|
||||
t,
|
||||
token_env,
|
||||
s0,
|
||||
shard0,
|
||||
s1,
|
||||
shard1,
|
||||
g,
|
||||
gpu,
|
||||
b,
|
||||
budget,
|
||||
c,
|
||||
context,
|
||||
] = args.as_slice()
|
||||
else {
|
||||
return Err("invalid_inference_arguments".into());
|
||||
};
|
||||
if l != "--listen"
|
||||
|| t != "--token-env"
|
||||
|| s0 != "--shard0"
|
||||
|| s1 != "--shard1"
|
||||
|| g != "--gpu"
|
||||
|| b != "--gpu-budget"
|
||||
|| c != "--context-tokens"
|
||||
{
|
||||
return Err("invalid_inference_arguments".into());
|
||||
}
|
||||
let address: SocketAddr = address.parse().map_err(|_| "invalid_runtime_endpoint")?;
|
||||
if !address.ip().is_loopback() {
|
||||
return Err("loopback_required".into());
|
||||
}
|
||||
if token_env.is_empty()
|
||||
|| !token_env
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
{
|
||||
return Err("invalid_token_environment_name".into());
|
||||
}
|
||||
let token = std::env::var(token_env).map_err(|_| "missing_runtime_credential")?;
|
||||
if !(32..=4096).contains(&token.len()) || !token.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
|
||||
return Err("invalid_runtime_credential".into());
|
||||
}
|
||||
let config = NativeBackendConfig {
|
||||
shard0: PathBuf::from(shard0),
|
||||
shard1: PathBuf::from(shard1),
|
||||
gpu_device_ordinal: gpu.parse().map_err(|_| "invalid_gpu_ordinal")?,
|
||||
gpu_budget_bytes: budget.parse().map_err(|_| "invalid_gpu_budget")?,
|
||||
context_tokens: context.parse().map_err(|_| "invalid_context_bound")?,
|
||||
};
|
||||
let backend = spawn_backend(config).map_err(|_| "runtime_startup_failed")?;
|
||||
let server = RuntimeServer::new(backend, token.clone())?;
|
||||
let listener = tokio::net::TcpListener::bind(address).await?;
|
||||
// Transport starts closed for model admission. Loading is an explicit typed
|
||||
// lifecycle command; successful configuration parsing is never model ready.
|
||||
server
|
||||
.serve(listener, async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -74,6 +74,35 @@ fn secret(name: &str) -> Result<String, String> {
|
||||
Ok(value)
|
||||
}
|
||||
impl Gateway {
|
||||
pub(crate) async fn dispatch(&self, headers: HeaderMap, body: Bytes) -> Response {
|
||||
responses(State(self.clone()), headers, body).await
|
||||
}
|
||||
pub(crate) fn ready_catalog(&self) -> Vec<Value> {
|
||||
let ready: HashSet<_> = self
|
||||
.0
|
||||
.pool
|
||||
.snapshot()
|
||||
.workers
|
||||
.into_iter()
|
||||
.filter(|w| w.ready)
|
||||
.map(|w| w.id)
|
||||
.collect();
|
||||
self.0
|
||||
.config
|
||||
.deployments
|
||||
.iter()
|
||||
.filter(|d| ready.contains(&d.id))
|
||||
.map(|d| json!({"id":d.id,"object":"model","owned_by":"configured-pool"}))
|
||||
.chain(
|
||||
self.0
|
||||
.config
|
||||
.aliases
|
||||
.iter()
|
||||
.filter(|(_, members)| members.iter().any(|m| ready.contains(m)))
|
||||
.map(|(id, _)| json!({"id":id,"object":"model","owned_by":"configured-pool"})),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
pub fn new(config: Config) -> Result<Self, String> {
|
||||
let token = secret(&config.token_env)?;
|
||||
Self::with_token(config, token)
|
||||
|
||||
@@ -8,6 +8,14 @@ pub mod node_proxy;
|
||||
pub mod planner;
|
||||
pub mod pool;
|
||||
pub mod remote;
|
||||
pub mod runtime_client;
|
||||
pub mod runtime_gateway;
|
||||
pub mod runtime_rpc;
|
||||
// Reuse the verified pure Rust template; no control-plane crate/C bridge link.
|
||||
#[path = "../../control-plane/src/prompt.rs"]
|
||||
#[allow(dead_code)]
|
||||
// This text-only adapter supports Effort::None; other existing render modes are unused here.
|
||||
mod runtime_prompt;
|
||||
|
||||
mod operation_journal;
|
||||
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
//! One-shot runtime commands. No generation replay or automatic lifecycle retry.
|
||||
use crate::runtime_rpc::{self, FRAME_LIMIT, MESSAGE_LIMIT, PROTOCOL_VERSION, proto};
|
||||
use prost::Message;
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use tonic::{Request, Status, transport::Channel};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RuntimeClient {
|
||||
client: proto::runtime_client::RuntimeClient<Channel>,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl RuntimeClient {
|
||||
pub async fn connect(address: SocketAddr, token: String) -> Result<Self, Status> {
|
||||
runtime_rpc::literal_loopback(address)?;
|
||||
if !runtime_rpc::valid_token(&token) {
|
||||
return Err(Status::invalid_argument("invalid_runtime_credential"));
|
||||
}
|
||||
let channel = tonic::transport::Endpoint::from_shared(format!("http://{address}"))
|
||||
.map_err(|_| Status::invalid_argument("invalid_runtime_endpoint"))?
|
||||
.connect_timeout(Duration::from_secs(2))
|
||||
.tcp_nodelay(true)
|
||||
.connect()
|
||||
.await
|
||||
.map_err(|_| Status::unavailable("runtime_connection_failed"))?;
|
||||
let mut client = Self {
|
||||
client: proto::runtime_client::RuntimeClient::new(channel)
|
||||
.max_decoding_message_size(MESSAGE_LIMIT)
|
||||
.max_encoding_message_size(MESSAGE_LIMIT),
|
||||
token,
|
||||
};
|
||||
client.handshake().await?;
|
||||
Ok(client)
|
||||
}
|
||||
fn request<T: Message>(
|
||||
&self,
|
||||
value: T,
|
||||
limit: usize,
|
||||
timeout: Duration,
|
||||
) -> Result<Request<T>, Status> {
|
||||
if value.encoded_len() > limit {
|
||||
return Err(Status::resource_exhausted("message_limit"));
|
||||
}
|
||||
let mut request = Request::new(value);
|
||||
request.metadata_mut().insert(
|
||||
"authorization",
|
||||
format!("Bearer {}", self.token)
|
||||
.parse()
|
||||
.map_err(|_| Status::invalid_argument("invalid_runtime_credential"))?,
|
||||
);
|
||||
request.set_timeout(timeout);
|
||||
Ok(request)
|
||||
}
|
||||
pub async fn handshake(&mut self) -> Result<proto::Snapshot, Status> {
|
||||
let request = self.request(
|
||||
proto::Hello {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
backend_api_version: 2,
|
||||
},
|
||||
FRAME_LIMIT,
|
||||
Duration::from_secs(2),
|
||||
)?;
|
||||
let value = self.client.handshake(request).await?.into_inner();
|
||||
validate_snapshot(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
pub async fn snapshot(&mut self) -> Result<proto::Snapshot, Status> {
|
||||
let request = self.request(proto::Empty {}, FRAME_LIMIT, Duration::from_secs(2))?;
|
||||
let value = self.client.snapshot(request).await?.into_inner();
|
||||
validate_snapshot(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
pub async fn watch(
|
||||
&mut self,
|
||||
cursor: proto::Cursor,
|
||||
) -> Result<tonic::Streaming<proto::Snapshot>, Status> {
|
||||
let request = self.request(cursor, FRAME_LIMIT, Duration::from_secs(3600))?;
|
||||
Ok(self.client.watch(request).await?.into_inner())
|
||||
}
|
||||
pub async fn load(
|
||||
&mut self,
|
||||
command: proto::LoadRequest,
|
||||
) -> Result<proto::OperationResult, Status> {
|
||||
let id = command.operation_id.clone();
|
||||
let epoch = command.expected_epoch.clone();
|
||||
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(5))?;
|
||||
let value = self.client.load(request).await?.into_inner();
|
||||
validate_operation(&value, &id, &epoch, false)?;
|
||||
Ok(value)
|
||||
}
|
||||
pub async fn unload(
|
||||
&mut self,
|
||||
command: proto::UnloadRequest,
|
||||
) -> Result<proto::OperationResult, Status> {
|
||||
let id = command.operation_id.clone();
|
||||
let epoch = command.expected_epoch.clone();
|
||||
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(5))?;
|
||||
let value = self.client.unload(request).await?.into_inner();
|
||||
validate_operation(&value, &id, &epoch, false)?;
|
||||
Ok(value)
|
||||
}
|
||||
pub async fn operation(
|
||||
&mut self,
|
||||
query: proto::OperationQuery,
|
||||
) -> Result<proto::OperationResult, Status> {
|
||||
let id = query.operation_id.clone();
|
||||
let epoch = query.expected_epoch.clone();
|
||||
let request = self.request(query, FRAME_LIMIT, Duration::from_secs(2))?;
|
||||
let value = self.client.operation(request).await?.into_inner();
|
||||
validate_operation(&value, &id, &epoch, true)?;
|
||||
Ok(value)
|
||||
}
|
||||
pub async fn cancel(
|
||||
&mut self,
|
||||
command: proto::CancelRequest,
|
||||
) -> Result<proto::CancelAck, Status> {
|
||||
let id = command.request_id.clone();
|
||||
let epoch = command.expected_epoch.clone();
|
||||
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(5))?;
|
||||
let value = self.client.cancel(request).await?.into_inner();
|
||||
if value.request_id != id || value.epoch != epoch || !value.acknowledged {
|
||||
return Err(Status::data_loss("invalid_cancel_ack"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
pub async fn generate(
|
||||
&mut self,
|
||||
command: proto::GenerateRequest,
|
||||
) -> Result<RuntimeGeneration, Status> {
|
||||
let id = command.request_id.clone();
|
||||
let epoch = command.expected_epoch.clone();
|
||||
let request = self.request(command, MESSAGE_LIMIT, Duration::from_secs(3600))?;
|
||||
let response = self.client.generate(request).await?;
|
||||
if response
|
||||
.metadata()
|
||||
.get("x-leleka-accepted")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
!= Some("true")
|
||||
{
|
||||
// Dispatch may already have occurred: never mark this retryable.
|
||||
return Err(Status::data_loss("missing_acceptance_state"));
|
||||
}
|
||||
Ok(RuntimeGeneration {
|
||||
stream: response.into_inner(),
|
||||
client: self.clone(),
|
||||
id,
|
||||
epoch,
|
||||
sequence: 0,
|
||||
terminal: false,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn validate_operation(
|
||||
value: &proto::OperationResult,
|
||||
id: &str,
|
||||
epoch: &str,
|
||||
query: bool,
|
||||
) -> Result<(), Status> {
|
||||
if value.operation_id != id
|
||||
|| !matches!(value.state, 1..=4)
|
||||
|| value.encoded_len() > FRAME_LIMIT
|
||||
|| uuid::Uuid::parse_str(&value.epoch).is_err()
|
||||
|| (value.epoch != epoch && !(query && value.state == 4))
|
||||
{
|
||||
return Err(Status::data_loss("invalid_operation_result"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_snapshot(value: &proto::Snapshot) -> Result<(), Status> {
|
||||
if value.protocol_version != PROTOCOL_VERSION
|
||||
|| value.backend_api_version != 2
|
||||
|| uuid::Uuid::parse_str(&value.epoch).is_err()
|
||||
|| value.sequence == 0
|
||||
|| !value.full_snapshot
|
||||
|| (value.model_ready && value.loaded.is_none())
|
||||
|| value.encoded_len() > FRAME_LIMIT
|
||||
{
|
||||
return Err(Status::data_loss("invalid_runtime_snapshot"));
|
||||
}
|
||||
if !value.model_ready
|
||||
&& value
|
||||
.capabilities
|
||||
.as_ref()
|
||||
.is_some_and(|c| !c.models.is_empty())
|
||||
{
|
||||
return Err(Status::data_loss("unloaded_capability_advertisement"));
|
||||
}
|
||||
if let Some(loaded) = &value.loaded {
|
||||
let descriptor = runtime_rpc::descriptor_from_proto(
|
||||
loaded
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?,
|
||||
)?;
|
||||
let config = runtime_rpc::config_from_proto(&proto::LoadConfig {
|
||||
version: loaded.load_config_version,
|
||||
mode: loaded.effective_mode.clone(),
|
||||
gpu_memory_limit_bytes: None,
|
||||
allow_experimental: true,
|
||||
})?;
|
||||
let result = leleka_backend_api::LoadedModel {
|
||||
handle: loaded.handle.clone(),
|
||||
descriptor: descriptor.clone(),
|
||||
load_config_version: config.load_config_version,
|
||||
effective_mode: config.inference_mode.clone(),
|
||||
mode_identity_digest: loaded.mode_identity_digest.clone(),
|
||||
};
|
||||
result
|
||||
.validate_for_load(&descriptor, &config)
|
||||
.map_err(|_| Status::data_loss("invalid_loaded_identity"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates request/epoch/sequence, initial acceptance and terminal completeness.
|
||||
/// Drop cancels observation's request; it never retries it or unloads the model.
|
||||
pub struct RuntimeGeneration {
|
||||
stream: tonic::Streaming<proto::GenerationFrame>,
|
||||
client: RuntimeClient,
|
||||
id: String,
|
||||
epoch: String,
|
||||
sequence: u64,
|
||||
terminal: bool,
|
||||
failed: bool,
|
||||
}
|
||||
impl RuntimeGeneration {
|
||||
pub async fn message(&mut self) -> Result<Option<proto::GenerationFrame>, Status> {
|
||||
if self.terminal {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.failed {
|
||||
return Err(Status::data_loss("generation_stream_failed"));
|
||||
}
|
||||
let value = match self.stream.message().await {
|
||||
Ok(Some(value)) => value,
|
||||
Ok(None) => {
|
||||
self.failed = true;
|
||||
return Err(Status::data_loss("generation_missing_terminal"));
|
||||
}
|
||||
Err(status) => {
|
||||
self.failed = true;
|
||||
return Err(status);
|
||||
}
|
||||
};
|
||||
let first = self.sequence == 0;
|
||||
if value.request_id != self.id
|
||||
|| value.epoch != self.epoch
|
||||
|| value.sequence != self.sequence + 1
|
||||
|| value.encoded_len() > FRAME_LIMIT
|
||||
|| value.payload.is_none()
|
||||
|| (first
|
||||
&& !matches!(
|
||||
value.payload,
|
||||
Some(proto::generation_frame::Payload::Accepted(
|
||||
proto::Accepted { accepted: true }
|
||||
))
|
||||
))
|
||||
|| (!first
|
||||
&& matches!(
|
||||
value.payload,
|
||||
Some(proto::generation_frame::Payload::Accepted(_))
|
||||
))
|
||||
{
|
||||
self.failed = true;
|
||||
return Err(Status::data_loss("invalid_generation_frame"));
|
||||
}
|
||||
if let Some(proto::generation_frame::Payload::Terminal(terminal)) = &value.payload {
|
||||
if !matches!(terminal.state, 1..=3) || (terminal.state == 1 && terminal.usage.is_none())
|
||||
{
|
||||
self.failed = true;
|
||||
return Err(Status::data_loss("invalid_generation_terminal"));
|
||||
}
|
||||
// Do not publish the terminal until the HTTP2 stream finishes
|
||||
// successfully. Duplicate frames and errors after terminal fail.
|
||||
match self.stream.message().await {
|
||||
Ok(None) => {}
|
||||
Ok(Some(_)) => {
|
||||
self.failed = true;
|
||||
return Err(Status::data_loss("generation_after_terminal"));
|
||||
}
|
||||
Err(status) => {
|
||||
self.failed = true;
|
||||
return Err(status);
|
||||
}
|
||||
}
|
||||
self.terminal = true;
|
||||
}
|
||||
self.sequence = value.sequence;
|
||||
Ok(Some(value))
|
||||
}
|
||||
}
|
||||
impl Drop for RuntimeGeneration {
|
||||
fn drop(&mut self) {
|
||||
if !self.terminal {
|
||||
let mut client = self.client.clone();
|
||||
let command = proto::CancelRequest {
|
||||
request_id: self.id.clone(),
|
||||
expected_epoch: self.epoch.clone(),
|
||||
};
|
||||
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||
handle.spawn(async move {
|
||||
let _ = client.cancel(command).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures_util::Stream;
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
use tonic::Response;
|
||||
#[test]
|
||||
fn runtime_client_retained_handle_is_not_ready() {
|
||||
let model = leleka_backend_api::ModelDescriptor {
|
||||
family: "fixture".into(),
|
||||
architecture: "fixture".into(),
|
||||
weight_format: "fixture".into(),
|
||||
artifact_digest: format!("sha256:{}", "a".repeat(64)),
|
||||
};
|
||||
let loaded = leleka_backend_api::LoadedModel {
|
||||
handle: "retained-fixture".into(),
|
||||
descriptor: model,
|
||||
load_config_version: 1,
|
||||
effective_mode: leleka_backend_api::InferenceMode::Native,
|
||||
mode_identity_digest: format!("sha256:{}", "b".repeat(64)),
|
||||
};
|
||||
let mut snapshot = proto::Snapshot {
|
||||
protocol_version: 1,
|
||||
backend_api_version: 2,
|
||||
epoch: uuid::Uuid::new_v4().to_string(),
|
||||
sequence: 1,
|
||||
full_snapshot: true,
|
||||
transport_ready: true,
|
||||
model_ready: false,
|
||||
loaded: Some(runtime_rpc::loaded_to_proto(&loaded)),
|
||||
capabilities: Some(proto::Capabilities::default()),
|
||||
active_request_id: String::new(),
|
||||
};
|
||||
assert!(validate_snapshot(&snapshot).is_ok());
|
||||
snapshot
|
||||
.capabilities
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.models
|
||||
.push(proto::SupportedModelTuple {
|
||||
family: "fixture".into(),
|
||||
architecture: "fixture".into(),
|
||||
weight_format: "fixture".into(),
|
||||
});
|
||||
assert!(validate_snapshot(&snapshot).is_err());
|
||||
snapshot.capabilities = Some(proto::Capabilities::default());
|
||||
snapshot.loaded = None;
|
||||
snapshot.model_ready = true;
|
||||
assert!(validate_snapshot(&snapshot).is_err());
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct FaultServer {
|
||||
epoch: String,
|
||||
fault: u8,
|
||||
cancels: Arc<AtomicUsize>,
|
||||
}
|
||||
impl FaultServer {
|
||||
fn snapshot(&self) -> proto::Snapshot {
|
||||
proto::Snapshot {
|
||||
protocol_version: 1,
|
||||
backend_api_version: 2,
|
||||
epoch: self.epoch.clone(),
|
||||
sequence: 1,
|
||||
full_snapshot: true,
|
||||
transport_ready: true,
|
||||
model_ready: false,
|
||||
loaded: None,
|
||||
capabilities: Some(proto::Capabilities::default()),
|
||||
active_request_id: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tonic::async_trait]
|
||||
impl proto::runtime_server::Runtime for FaultServer {
|
||||
async fn handshake(
|
||||
&self,
|
||||
_: Request<proto::Hello>,
|
||||
) -> Result<Response<proto::Snapshot>, Status> {
|
||||
Ok(Response::new(self.snapshot()))
|
||||
}
|
||||
async fn snapshot(
|
||||
&self,
|
||||
_: Request<proto::Empty>,
|
||||
) -> Result<Response<proto::Snapshot>, Status> {
|
||||
Ok(Response::new(self.snapshot()))
|
||||
}
|
||||
type WatchStream = Pin<Box<dyn Stream<Item = Result<proto::Snapshot, Status>> + Send>>;
|
||||
async fn watch(
|
||||
&self,
|
||||
_: Request<proto::Cursor>,
|
||||
) -> Result<Response<Self::WatchStream>, Status> {
|
||||
Err(Status::unimplemented("fixture"))
|
||||
}
|
||||
async fn load(
|
||||
&self,
|
||||
_: Request<proto::LoadRequest>,
|
||||
) -> Result<Response<proto::OperationResult>, Status> {
|
||||
Err(Status::unimplemented("fixture"))
|
||||
}
|
||||
async fn unload(
|
||||
&self,
|
||||
_: Request<proto::UnloadRequest>,
|
||||
) -> Result<Response<proto::OperationResult>, Status> {
|
||||
Err(Status::unimplemented("fixture"))
|
||||
}
|
||||
async fn operation(
|
||||
&self,
|
||||
_: Request<proto::OperationQuery>,
|
||||
) -> Result<Response<proto::OperationResult>, Status> {
|
||||
Err(Status::unimplemented("fixture"))
|
||||
}
|
||||
async fn cancel(
|
||||
&self,
|
||||
request: Request<proto::CancelRequest>,
|
||||
) -> Result<Response<proto::CancelAck>, Status> {
|
||||
self.cancels.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(Response::new(proto::CancelAck {
|
||||
request_id: request.get_ref().request_id.clone(),
|
||||
epoch: self.epoch.clone(),
|
||||
acknowledged: true,
|
||||
}))
|
||||
}
|
||||
type GenerateStream =
|
||||
Pin<Box<dyn Stream<Item = Result<proto::GenerationFrame, Status>> + Send>>;
|
||||
async fn generate(
|
||||
&self,
|
||||
request: Request<proto::GenerateRequest>,
|
||||
) -> Result<Response<Self::GenerateStream>, Status> {
|
||||
let id = request.into_inner().request_id;
|
||||
let frame = |sequence, payload| proto::GenerationFrame {
|
||||
request_id: id.clone(),
|
||||
epoch: self.epoch.clone(),
|
||||
sequence,
|
||||
payload: Some(payload),
|
||||
};
|
||||
let mut frames = vec![Ok(frame(
|
||||
1,
|
||||
proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true }),
|
||||
))];
|
||||
let terminal = frame(
|
||||
if self.fault == 4 { 5 } else { 2 },
|
||||
proto::generation_frame::Payload::Terminal(proto::Terminal {
|
||||
state: 1,
|
||||
reason: "stop".into(),
|
||||
usage: Some(proto::Usage::default()),
|
||||
error_code: String::new(),
|
||||
retryable: false,
|
||||
}),
|
||||
);
|
||||
if self.fault != 1 {
|
||||
frames.push(Ok(terminal));
|
||||
}
|
||||
if self.fault == 2 {
|
||||
frames.push(Ok(frame(
|
||||
3,
|
||||
proto::generation_frame::Payload::Text(proto::TextDelta {
|
||||
text: "must-not-publish".into(),
|
||||
}),
|
||||
)));
|
||||
}
|
||||
if self.fault == 3 {
|
||||
frames.push(Err(Status::internal("fixture_trailer_error")));
|
||||
}
|
||||
let stream = Box::pin(tokio_stream::iter(frames)) as Self::GenerateStream;
|
||||
let mut response = Response::new(stream);
|
||||
response
|
||||
.metadata_mut()
|
||||
.insert("x-leleka-accepted", "true".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn runtime_client_requires_terminal_eof_and_rejects_trailing_data_or_status() {
|
||||
for fault in 0..=4 {
|
||||
let epoch = uuid::Uuid::new_v4().to_string();
|
||||
let cancels = Arc::new(AtomicUsize::new(0));
|
||||
let service = FaultServer {
|
||||
epoch: epoch.clone(),
|
||||
fault,
|
||||
cancels: cancels.clone(),
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let (stop, stopped) = tokio::sync::oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(proto::runtime_server::RuntimeServer::new(service))
|
||||
.serve_with_incoming_shutdown(
|
||||
tokio_stream::wrappers::TcpListenerStream::new(listener),
|
||||
async {
|
||||
let _ = stopped.await;
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let mut client =
|
||||
RuntimeClient::connect(address, "synthetic-runtime-test-token-00000000".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut stream = client
|
||||
.generate(proto::GenerateRequest {
|
||||
request_id: uuid::Uuid::new_v4().to_string(),
|
||||
expected_epoch: epoch,
|
||||
handle: "fixture".into(),
|
||||
prompt: String::new(),
|
||||
max_output_tokens: 1,
|
||||
temperature_milli: 0,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
stream.message().await.unwrap().unwrap().payload,
|
||||
Some(proto::generation_frame::Payload::Accepted(_))
|
||||
));
|
||||
if fault == 0 {
|
||||
assert!(matches!(
|
||||
stream.message().await.unwrap().unwrap().payload,
|
||||
Some(proto::generation_frame::Payload::Terminal(_))
|
||||
));
|
||||
assert!(stream.message().await.unwrap().is_none());
|
||||
} else {
|
||||
assert!(stream.message().await.is_err());
|
||||
}
|
||||
drop(stream);
|
||||
if fault != 0 {
|
||||
for _ in 0..50 {
|
||||
if cancels.load(Ordering::SeqCst) > 0 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
}
|
||||
assert_eq!(cancels.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
drop(client);
|
||||
stop.send(()).unwrap();
|
||||
task.await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,871 @@
|
||||
//! Explicit runtime catalog and OpenAI text adapter; compute stays behind gRPC.
|
||||
use crate::{
|
||||
gateway,
|
||||
runtime_client::{RuntimeClient, RuntimeGeneration},
|
||||
runtime_prompt::{self, Effort, Message, Role},
|
||||
runtime_rpc::proto,
|
||||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::{Body, Bytes},
|
||||
extract::{DefaultBodyLimit, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{collections::HashSet, net::SocketAddr, sync::Arc, time::Duration};
|
||||
use subtle::ConstantTimeEq;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Member {
|
||||
pub id: String,
|
||||
pub address: SocketAddr,
|
||||
pub token_env: String,
|
||||
pub artifact_digest: String,
|
||||
}
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
pub schema_version: u32,
|
||||
pub listen: SocketAddr,
|
||||
pub token_env: String,
|
||||
pub runtimes: Vec<Member>,
|
||||
pub http_pool: Option<gateway::Config>,
|
||||
}
|
||||
struct MemberState {
|
||||
client: Option<RuntimeClient>,
|
||||
snapshot: Option<proto::Snapshot>,
|
||||
blocked: bool,
|
||||
}
|
||||
struct Peer {
|
||||
config: Member,
|
||||
token: String,
|
||||
state: Mutex<MemberState>,
|
||||
}
|
||||
struct Inner {
|
||||
token: String,
|
||||
peers: Vec<Peer>,
|
||||
fallback: Option<gateway::Gateway>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Registry(Arc<Inner>);
|
||||
|
||||
fn credential(name: &str) -> Result<String, String> {
|
||||
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
|
||||
return Err("invalid_credential_name".into());
|
||||
}
|
||||
let token = std::env::var(name).map_err(|_| "missing_credential")?;
|
||||
if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| (0x21..=0x7e).contains(&b))
|
||||
{
|
||||
return Err("invalid_credential".into());
|
||||
}
|
||||
Ok(token)
|
||||
}
|
||||
impl Config {
|
||||
pub fn read(path: &std::path::Path) -> Result<Self, String> {
|
||||
use std::io::Read;
|
||||
let file = std::fs::File::open(path).map_err(|_| "configuration_read_failed")?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(1024 * 1024 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| "configuration_read_failed")?;
|
||||
if bytes.len() > 1024 * 1024 {
|
||||
return Err("configuration_limit".into());
|
||||
}
|
||||
let config: Self = serde_json::from_slice(&bytes).map_err(|_| "invalid_configuration")?;
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
pub fn credential(&self) -> Result<String, String> {
|
||||
credential(&self.token_env)
|
||||
}
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.schema_version != 1
|
||||
|| !self.listen.ip().is_loopback()
|
||||
|| self.listen.port() == 0
|
||||
|| self.runtimes.is_empty()
|
||||
|| self.runtimes.len() > 64
|
||||
{
|
||||
return Err("invalid_daemon_configuration".into());
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
for m in &self.runtimes {
|
||||
let digest = m
|
||||
.artifact_digest
|
||||
.strip_prefix("sha256:")
|
||||
.ok_or("invalid_model_digest")?;
|
||||
if m.id.is_empty()
|
||||
|| m.id.len() > 128
|
||||
|| !m
|
||||
.id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
|
||||
|| !ids.insert(&m.id)
|
||||
|| !m.address.ip().is_loopback()
|
||||
|| m.address.port() == 0
|
||||
|| digest.len() != 64
|
||||
|| !digest.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
{
|
||||
return Err("invalid_runtime_member".into());
|
||||
}
|
||||
}
|
||||
if let Some(pool) = &self.http_pool
|
||||
&& (pool.listen != self.listen
|
||||
|| pool.deployments.iter().any(|d| ids.contains(&d.id))
|
||||
|| pool.aliases.keys().any(|id| ids.contains(id)))
|
||||
{
|
||||
return Err("conflicting_pool_configuration".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Registry {
|
||||
pub fn new(config: Config) -> Result<Self, String> {
|
||||
config.validate()?;
|
||||
let token = credential(&config.token_env)?;
|
||||
let peers = config
|
||||
.runtimes
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
Ok(Peer {
|
||||
token: credential(&m.token_env)?,
|
||||
config: m,
|
||||
state: Mutex::new(MemberState {
|
||||
client: None,
|
||||
snapshot: None,
|
||||
blocked: false,
|
||||
}),
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
let fallback = config
|
||||
.http_pool
|
||||
.map(|p| gateway::Gateway::with_token(p, token.clone()))
|
||||
.transpose()?;
|
||||
Ok(Self(Arc::new(Inner {
|
||||
token,
|
||||
peers,
|
||||
fallback,
|
||||
})))
|
||||
}
|
||||
fn authorized(&self, h: &HeaderMap) -> bool {
|
||||
h.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.is_some_and(|v| bool::from(v.as_bytes().ct_eq(self.0.token.as_bytes())))
|
||||
}
|
||||
async fn observe(&self, index: usize) -> Option<(RuntimeClient, proto::Snapshot)> {
|
||||
let peer = &self.0.peers[index];
|
||||
let mut state = peer.state.lock().await;
|
||||
if state.blocked {
|
||||
return None;
|
||||
}
|
||||
let result = async {
|
||||
let mut client = match &state.client {
|
||||
Some(c) => c.clone(),
|
||||
None => RuntimeClient::connect(peer.config.address, peer.token.clone()).await?,
|
||||
};
|
||||
let snap = client.snapshot().await?;
|
||||
if let Some(prior) = &state.snapshot
|
||||
&& prior.epoch == snap.epoch
|
||||
&& prior.sequence > snap.sequence
|
||||
{
|
||||
return Err(tonic::Status::data_loss("snapshot_regression"));
|
||||
}
|
||||
if let Some(loaded) = &snap.loaded
|
||||
&& loaded
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.is_none_or(|d| d.artifact_digest != peer.config.artifact_digest)
|
||||
{
|
||||
return Err(tonic::Status::data_loss("runtime_model_identity_mismatch"));
|
||||
}
|
||||
Ok((client, snap))
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok((client, snap)) => {
|
||||
state.client = Some(client.clone());
|
||||
state.snapshot = Some(snap.clone());
|
||||
Some((client, snap))
|
||||
}
|
||||
Err(e) => {
|
||||
state.client = None;
|
||||
state.snapshot = None;
|
||||
state.blocked = matches!(
|
||||
e.code(),
|
||||
tonic::Code::Unauthenticated
|
||||
| tonic::Code::PermissionDenied
|
||||
| tonic::Code::DataLoss
|
||||
| tonic::Code::FailedPrecondition
|
||||
| tonic::Code::InvalidArgument
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
pub async fn refresh(&self) {
|
||||
futures_util::future::join_all((0..self.0.peers.len()).map(|i| self.observe(i))).await;
|
||||
}
|
||||
pub fn router(&self) -> Router {
|
||||
Router::new()
|
||||
.route("/v1/models", get(models))
|
||||
.route("/v1/responses", post(responses))
|
||||
.route("/runtime/status", get(status))
|
||||
.route("/runtime/load", post(load))
|
||||
.route("/runtime/unload", post(unload))
|
||||
.route("/runtime/operation", post(operation))
|
||||
.layer(DefaultBodyLimit::max(1024 * 1024))
|
||||
.with_state(self.clone())
|
||||
}
|
||||
}
|
||||
/// Commands can address only members already admitted by operator configuration.
|
||||
/// UUID and epoch identify uncertain outcomes; lifecycle calls are never replayed.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Control {
|
||||
model: String,
|
||||
operation_id: String,
|
||||
epoch: String,
|
||||
mode: Option<String>,
|
||||
profile_id: Option<String>,
|
||||
handle: Option<String>,
|
||||
}
|
||||
fn control(body: &Bytes) -> Result<Control, &'static str> {
|
||||
let c: Control = serde_json::from_slice(body).map_err(|_| "invalid_control_command")?;
|
||||
if uuid::Uuid::parse_str(&c.operation_id).is_err() || uuid::Uuid::parse_str(&c.epoch).is_err() {
|
||||
return Err("invalid_control_identity");
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
async fn control_peer(
|
||||
r: &Registry,
|
||||
c: &Control,
|
||||
) -> Result<(RuntimeClient, proto::Snapshot), (StatusCode, &'static str)> {
|
||||
let i =
|
||||
r.0.peers
|
||||
.iter()
|
||||
.position(|p| p.config.id == c.model)
|
||||
.ok_or((StatusCode::NOT_FOUND, "unknown_model"))?;
|
||||
let pair = r
|
||||
.observe(i)
|
||||
.await
|
||||
.ok_or((StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"))?;
|
||||
if pair.1.epoch != c.epoch {
|
||||
return Err((StatusCode::CONFLICT, "runtime_epoch_changed"));
|
||||
}
|
||||
Ok(pair)
|
||||
}
|
||||
fn operation_value(c: &Control, result: Result<proto::OperationResult, tonic::Status>) -> Response {
|
||||
match result {
|
||||
Ok(v)=>Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":v.state,"reason":v.reason,"loaded_handle":v.loaded.map(|v|v.handle)})).into_response(),
|
||||
Err(_)=>(StatusCode::BAD_GATEWAY,Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":"outcome_unknown","error":{"type":"runtime_command_failed"}}))).into_response()
|
||||
}
|
||||
}
|
||||
async fn load(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Response {
|
||||
if !r.authorized(&h) {
|
||||
return error(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let c = match control(&body) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||
};
|
||||
if c.handle.is_some() {
|
||||
return error(StatusCode::BAD_REQUEST, "unexpected_handle");
|
||||
}
|
||||
let mode = match (c.mode.as_deref(), c.profile_id.as_deref()) {
|
||||
(Some("native"), None) => proto::inference_mode::Selection::Native(proto::NativeMode {}),
|
||||
(Some("kar-ple"), Some(id)) if !id.is_empty() && id.len() <= 128 => {
|
||||
proto::inference_mode::Selection::KarPle(proto::KarPleMode {
|
||||
profile_id: id.to_owned(),
|
||||
})
|
||||
}
|
||||
_ => return error(StatusCode::BAD_REQUEST, "invalid_explicit_mode"),
|
||||
};
|
||||
let (mut client, _) = match control_peer(&r, &c).await {
|
||||
Ok(p) => p,
|
||||
Err((code, e)) => return error(code, e),
|
||||
};
|
||||
let d = leleka_runtime::backend::pinned_model_descriptor();
|
||||
if r.0
|
||||
.peers
|
||||
.iter()
|
||||
.find(|p| p.config.id == c.model)
|
||||
.is_none_or(|p| p.config.artifact_digest != d.artifact_digest)
|
||||
{
|
||||
return error(StatusCode::BAD_REQUEST, "unsupported_model_identity");
|
||||
}
|
||||
let result = client
|
||||
.load(proto::LoadRequest {
|
||||
operation_id: c.operation_id.clone(),
|
||||
expected_epoch: c.epoch.clone(),
|
||||
model: Some(proto::ModelDescriptor {
|
||||
family: d.family,
|
||||
architecture: d.architecture,
|
||||
artifact_digest: d.artifact_digest,
|
||||
weight_format: d.weight_format,
|
||||
}),
|
||||
config: Some(proto::LoadConfig {
|
||||
version: 1,
|
||||
mode: Some(proto::InferenceMode {
|
||||
selection: Some(mode),
|
||||
}),
|
||||
gpu_memory_limit_bytes: None,
|
||||
allow_experimental: c.mode.as_deref() == Some("kar-ple"),
|
||||
}),
|
||||
})
|
||||
.await;
|
||||
operation_value(&c, result)
|
||||
}
|
||||
async fn unload(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Response {
|
||||
if !r.authorized(&h) {
|
||||
return error(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let c = match control(&body) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||
};
|
||||
if c.mode.is_some() || c.profile_id.is_some() {
|
||||
return error(StatusCode::BAD_REQUEST, "unexpected_mode");
|
||||
}
|
||||
let Some(handle) = c.handle.as_ref().filter(|s| {
|
||||
!s.is_empty() && s.len() <= 128 && s.bytes().all(|b| (0x21..=0x7e).contains(&b))
|
||||
}) else {
|
||||
return error(StatusCode::BAD_REQUEST, "expected_handle_required");
|
||||
};
|
||||
let (mut client, _) = match control_peer(&r, &c).await {
|
||||
Ok(p) => p,
|
||||
Err((code, e)) => return error(code, e),
|
||||
};
|
||||
let result = client
|
||||
.unload(proto::UnloadRequest {
|
||||
operation_id: c.operation_id.clone(),
|
||||
expected_epoch: c.epoch.clone(),
|
||||
handle: handle.clone(),
|
||||
})
|
||||
.await;
|
||||
operation_value(&c, result)
|
||||
}
|
||||
async fn operation(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Response {
|
||||
if !r.authorized(&h) {
|
||||
return error(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let c = match control(&body) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||
};
|
||||
if c.mode.is_some() || c.profile_id.is_some() || c.handle.is_some() {
|
||||
return error(StatusCode::BAD_REQUEST, "unexpected_mode");
|
||||
}
|
||||
let (mut client, _) = match control_peer(&r, &c).await {
|
||||
Ok(p) => p,
|
||||
Err((code, e)) => return error(code, e),
|
||||
};
|
||||
let result = client
|
||||
.operation(proto::OperationQuery {
|
||||
operation_id: c.operation_id.clone(),
|
||||
expected_epoch: c.epoch.clone(),
|
||||
})
|
||||
.await;
|
||||
operation_value(&c, result)
|
||||
}
|
||||
fn error(code: StatusCode, kind: &str) -> Response {
|
||||
(code, Json(json!({"error":{"type":kind,"message":kind}}))).into_response()
|
||||
}
|
||||
async fn models(State(r): State<Registry>, h: HeaderMap) -> Response {
|
||||
if !r.authorized(&h) {
|
||||
return error(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let observed = futures_util::future::join_all((0..r.0.peers.len()).map(|i| r.observe(i))).await;
|
||||
let mut data =
|
||||
r.0.fallback
|
||||
.as_ref()
|
||||
.map(gateway::Gateway::ready_catalog)
|
||||
.unwrap_or_default();
|
||||
for (i, entry) in observed.into_iter().enumerate() {
|
||||
if let Some((_, snap)) = entry
|
||||
&& snap.model_ready
|
||||
&& let Some(loaded) = snap.loaded
|
||||
{
|
||||
data.push(json!({"id":r.0.peers[i].config.id,"object":"model","owned_by":"leleka-runtime","artifact_digest":r.0.peers[i].config.artifact_digest,"mode_identity_digest":loaded.mode_identity_digest}));
|
||||
}
|
||||
}
|
||||
Json(json!({"object":"list","data":data})).into_response()
|
||||
}
|
||||
async fn status(State(r): State<Registry>, h: HeaderMap) -> Response {
|
||||
if !r.authorized(&h) {
|
||||
return error(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let mut states = Vec::new();
|
||||
r.refresh().await;
|
||||
for p in &r.0.peers {
|
||||
let s = p.state.lock().await;
|
||||
states.push(json!({"id":p.config.id,"connected":s.snapshot.is_some(),"epoch":s.snapshot.as_ref().map(|v|&v.epoch),"loaded_handle":s.snapshot.as_ref().and_then(|v|v.loaded.as_ref()).map(|v|&v.handle),"model_ready":s.snapshot.as_ref().is_some_and(|v|v.model_ready),"configuration_action_required":s.blocked}));
|
||||
}
|
||||
Json(json!({"schema_version":1,"runtimes":states})).into_response()
|
||||
}
|
||||
fn render(v: &Value) -> Result<(String, u32), &'static str> {
|
||||
let o = v.as_object().ok_or("invalid_json")?;
|
||||
for (key, value) in o {
|
||||
match key.as_str() {
|
||||
"model" | "input" | "instructions" | "stream" | "max_output_tokens" => {}
|
||||
"temperature" if value.as_f64() == Some(0.0) => {}
|
||||
"store" if value == &Value::Bool(false) => {}
|
||||
"tools" if value.as_array().is_some_and(Vec::is_empty) => {}
|
||||
"text" if value == &json!({"format":{"type":"text"}}) => {}
|
||||
_ => return Err("unsupported_request_field"),
|
||||
}
|
||||
}
|
||||
if o.get("stream").is_some_and(|v| !v.is_boolean()) {
|
||||
return Err("invalid_stream");
|
||||
}
|
||||
let cap = o
|
||||
.get("max_output_tokens")
|
||||
.map(|v| v.as_u64().ok_or("invalid_output_limit"))
|
||||
.transpose()?
|
||||
.unwrap_or(256);
|
||||
if !(1..=4096).contains(&cap) {
|
||||
return Err("invalid_output_limit");
|
||||
}
|
||||
let mut owned = Vec::new();
|
||||
if let Some(s) = o.get("instructions") {
|
||||
owned.push((
|
||||
Role::System,
|
||||
s.as_str().ok_or("invalid_instructions")?.to_owned(),
|
||||
));
|
||||
}
|
||||
match o.get("input").ok_or("input_required")? {
|
||||
Value::String(s) => owned.push((Role::User, s.clone())),
|
||||
Value::Array(items) if !items.is_empty() && items.len() <= 1024 => {
|
||||
for item in items {
|
||||
let fields = item.as_object().ok_or("invalid_message")?;
|
||||
if fields
|
||||
.keys()
|
||||
.any(|k| !matches!(k.as_str(), "type" | "role" | "content"))
|
||||
|| fields.get("type").is_some_and(|t| t != "message")
|
||||
{
|
||||
return Err("unsupported_input_item");
|
||||
}
|
||||
let role = match item.get("role").and_then(Value::as_str) {
|
||||
Some("system") => Role::System,
|
||||
Some("developer") => Role::Developer,
|
||||
Some("user") => Role::User,
|
||||
Some("assistant") => Role::Assistant,
|
||||
_ => return Err("invalid_role"),
|
||||
};
|
||||
let content = match item.get("content").ok_or("content_required")? {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(parts) => {
|
||||
let mut s = String::new();
|
||||
for part in parts {
|
||||
if !matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("input_text" | "output_text")
|
||||
) || part.as_object().is_none_or(|m| {
|
||||
m.keys().any(|k| !matches!(k.as_str(), "type" | "text"))
|
||||
}) {
|
||||
return Err("unsupported_content");
|
||||
}
|
||||
s.push_str(
|
||||
part.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("invalid_text")?,
|
||||
);
|
||||
}
|
||||
s
|
||||
}
|
||||
_ => return Err("invalid_content"),
|
||||
};
|
||||
owned.push((role, content));
|
||||
}
|
||||
}
|
||||
_ => return Err("invalid_input"),
|
||||
}
|
||||
let messages = owned
|
||||
.iter()
|
||||
.map(|(role, content)| Message {
|
||||
role: *role,
|
||||
content,
|
||||
reasoning: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let prompt = runtime_prompt::render(&messages, Effort::None)?;
|
||||
if prompt.len() > 1024 * 1024 {
|
||||
return Err("prompt_limit");
|
||||
}
|
||||
Ok((prompt, cap as u32))
|
||||
}
|
||||
fn response_value(id: &str, model: &str, text: &str, status: &str, usage: &proto::Usage) -> Value {
|
||||
json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}})
|
||||
}
|
||||
struct Trace {
|
||||
id: String,
|
||||
model: String,
|
||||
text: String,
|
||||
usage: proto::Usage,
|
||||
sequence: u64,
|
||||
}
|
||||
impl Trace {
|
||||
fn beginning(&mut self) -> Vec<Bytes> {
|
||||
let mut initial = response_value(&self.id, &self.model, "", "in_progress", &self.usage);
|
||||
initial["output"] = json!([]);
|
||||
initial["usage"] = Value::Null;
|
||||
let item = json!({"id":format!("msg_{}",self.id),"type":"message","role":"assistant","status":"in_progress","content":[]});
|
||||
vec![self.event("response.created",json!({"response":initial})),self.event("response.in_progress",json!({"response":initial})),self.event("response.output_item.added",json!({"output_index":0,"item":item})),self.event("response.content_part.added",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}))]
|
||||
}
|
||||
fn interrupted(&mut self) -> Bytes {
|
||||
let mut failed = response_value(&self.id, &self.model, &self.text, "failed", &self.usage);
|
||||
failed["error"] = json!({"code":"runtime_interrupted","message":"runtime_interrupted"});
|
||||
self.event("response.failed", json!({"response":failed}))
|
||||
}
|
||||
fn event(&mut self, kind: &str, mut value: Value) -> Bytes {
|
||||
value["type"] = json!(kind);
|
||||
value["sequence_number"] = json!(self.sequence);
|
||||
self.sequence += 1;
|
||||
Bytes::from(format!("event: {kind}\ndata: {value}\n\n"))
|
||||
}
|
||||
fn frame(&mut self, frame: proto::GenerationFrame) -> Result<Vec<Bytes>, &'static str> {
|
||||
match frame.payload.ok_or("missing_payload")? {
|
||||
proto::generation_frame::Payload::Accepted(_) => Ok(Vec::new()),
|
||||
proto::generation_frame::Payload::Text(delta) => {
|
||||
if self.text.len() + delta.text.len() > 8 * 1024 * 1024 {
|
||||
return Err("response_limit");
|
||||
}
|
||||
self.text.push_str(&delta.text);
|
||||
Ok(vec![self.event("response.output_text.delta",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"delta":delta.text}))])
|
||||
}
|
||||
proto::generation_frame::Payload::Usage(usage) => {
|
||||
self.usage = usage;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
proto::generation_frame::Payload::Tool(_) => Err("unadvertised_tool_output"),
|
||||
proto::generation_frame::Payload::Terminal(terminal) => {
|
||||
if terminal.state == 1 && !matches!(terminal.reason.as_str(), "stop" | "length") {
|
||||
return Err("unadvertised_finish_reason");
|
||||
}
|
||||
if let Some(usage) = terminal.usage {
|
||||
self.usage = usage;
|
||||
}
|
||||
let status = match terminal.state {
|
||||
1 if terminal.reason == "length" => "incomplete",
|
||||
1 => "completed",
|
||||
_ => "failed",
|
||||
};
|
||||
let mut value =
|
||||
response_value(&self.id, &self.model, &self.text, status, &self.usage);
|
||||
if status == "failed" {
|
||||
value["error"] =
|
||||
json!({"code":"runtime_interrupted","message":"runtime_interrupted"});
|
||||
}
|
||||
let part = json!({"type":"output_text","text":self.text,"annotations":[]});
|
||||
let item = value["output"][0].clone();
|
||||
let mut events = Vec::new();
|
||||
if status != "failed" {
|
||||
events.push(self.event("response.output_text.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"text":self.text})));
|
||||
events.push(self.event("response.content_part.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":part})));
|
||||
events.push(self.event(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":0,"item":item}),
|
||||
));
|
||||
}
|
||||
events.push(self.event(&format!("response.{status}"), json!({"response":value})));
|
||||
Ok(events)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn accepted(
|
||||
client: &mut RuntimeClient,
|
||||
request: proto::GenerateRequest,
|
||||
) -> Result<RuntimeGeneration, tonic::Status> {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
for attempt in 0..3 {
|
||||
let result = tokio::time::timeout_at(deadline, client.generate(request.clone()))
|
||||
.await
|
||||
.map_err(|_| tonic::Status::deadline_exceeded("dispatch_outcome_unknown"))?;
|
||||
match result {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(e) => {
|
||||
let safe = e
|
||||
.metadata()
|
||||
.get("x-leleka-accepted")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
== Some("false")
|
||||
&& matches!(
|
||||
e.code(),
|
||||
tonic::Code::ResourceExhausted | tonic::Code::Unavailable
|
||||
);
|
||||
if !safe || attempt == 2 {
|
||||
return Err(e);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(tonic::Status::unavailable("dispatch_refused"))
|
||||
}
|
||||
async fn responses(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Response {
|
||||
if !r.authorized(&h) {
|
||||
return error(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let v: Value = match serde_json::from_slice(&body) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return error(StatusCode::BAD_REQUEST, "invalid_json"),
|
||||
};
|
||||
let Some(model) = v.get("model").and_then(Value::as_str) else {
|
||||
return error(StatusCode::BAD_REQUEST, "model_required");
|
||||
};
|
||||
let Some(index) = r.0.peers.iter().position(|p| p.config.id == model) else {
|
||||
return match &r.0.fallback {
|
||||
Some(g) => g.dispatch(h, body).await,
|
||||
None => error(StatusCode::NOT_FOUND, "unknown_model"),
|
||||
};
|
||||
};
|
||||
let (prompt, cap) = match render(&v) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||
};
|
||||
let Some((mut client, snapshot)) = r.observe(index).await else {
|
||||
return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable");
|
||||
};
|
||||
let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else {
|
||||
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
|
||||
};
|
||||
let request_id = uuid::Uuid::new_v4().to_string();
|
||||
let stream = match accepted(
|
||||
&mut client,
|
||||
proto::GenerateRequest {
|
||||
request_id: request_id.clone(),
|
||||
expected_epoch: snapshot.epoch,
|
||||
handle: loaded.handle,
|
||||
prompt,
|
||||
max_output_tokens: cap,
|
||||
temperature_milli: 0,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(s) => s,
|
||||
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
|
||||
};
|
||||
let mut trace = Trace {
|
||||
id: format!("resp_{}", request_id.replace('-', "")),
|
||||
model: model.to_owned(),
|
||||
text: String::new(),
|
||||
usage: proto::Usage::default(),
|
||||
sequence: 0,
|
||||
};
|
||||
if v.get("stream") == Some(&Value::Bool(true)) {
|
||||
let output = async_stream::stream! {
|
||||
for event in trace.beginning(){yield Ok::<Bytes,std::io::Error>(event);}
|
||||
let mut stream=stream;
|
||||
loop {match tokio::time::timeout(Duration::from_secs(3600),stream.message()).await {
|
||||
Ok(Ok(Some(frame)))=>{let terminal=matches!(frame.payload,Some(proto::generation_frame::Payload::Terminal(_)));match trace.frame(frame){Ok(events)=>for event in events{yield Ok(event);},Err(_)=>{yield Ok(trace.interrupted());break;}}if terminal{break;}},
|
||||
_=>{yield Ok(trace.interrupted());break;}
|
||||
}}
|
||||
};
|
||||
let mut response = Body::from_stream(output).into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "text/event-stream".parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("cache-control", "no-store".parse().unwrap());
|
||||
response
|
||||
} else {
|
||||
let mut stream = stream;
|
||||
let mut terminal = None;
|
||||
loop {
|
||||
match tokio::time::timeout(Duration::from_secs(3600), stream.message()).await {
|
||||
Ok(Ok(Some(frame))) => {
|
||||
if let Some(proto::generation_frame::Payload::Terminal(t)) = &frame.payload {
|
||||
terminal = Some(t.clone());
|
||||
}
|
||||
if trace.frame(frame).is_err() {
|
||||
return error(StatusCode::BAD_GATEWAY, "runtime_protocol_failed");
|
||||
}
|
||||
}
|
||||
Ok(Ok(None)) => break,
|
||||
_ => return error(StatusCode::BAD_GATEWAY, "runtime_interrupted"),
|
||||
}
|
||||
}
|
||||
let Some(t) = terminal else {
|
||||
return error(StatusCode::BAD_GATEWAY, "runtime_missing_terminal");
|
||||
};
|
||||
if t.state != 1 {
|
||||
return error(StatusCode::BAD_GATEWAY, "runtime_generation_failed");
|
||||
}
|
||||
Json(response_value(
|
||||
&trace.id,
|
||||
&trace.model,
|
||||
&trace.text,
|
||||
if t.reason == "length" {
|
||||
"incomplete"
|
||||
} else {
|
||||
"completed"
|
||||
},
|
||||
&trace.usage,
|
||||
))
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn runtime_gateway_refuses_silent_sampling_tools_and_state() {
|
||||
for extra in [
|
||||
json!({"temperature":0.5}),
|
||||
json!({"tools":[{"type":"function","name":"run"}]}),
|
||||
json!({"previous_response_id":"resp_x"}),
|
||||
json!({"store":true}),
|
||||
json!({"max_output_tokens":0}),
|
||||
] {
|
||||
let mut value = json!({"model":"native","input":"hello"});
|
||||
value
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(extra.as_object().unwrap().clone());
|
||||
assert!(render(&value).is_err());
|
||||
}
|
||||
let (prompt, limit) =
|
||||
render(&json!({"model":"native","input":"hello","max_output_tokens":2,"store":false}))
|
||||
.unwrap();
|
||||
assert_eq!(limit, 2);
|
||||
assert!(prompt.ends_with("<|im_start|>assistant\n<think>\n\n</think>\n\n"));
|
||||
}
|
||||
fn trace() -> Trace {
|
||||
Trace {
|
||||
id: "resp_test".into(),
|
||||
model: "native".into(),
|
||||
text: String::new(),
|
||||
usage: proto::Usage::default(),
|
||||
sequence: 0,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn runtime_gateway_sse_lifecycle_has_one_terminal_and_ordered_parts() {
|
||||
let mut trace = trace();
|
||||
let mut events = trace.beginning();
|
||||
events.extend(
|
||||
trace
|
||||
.frame(proto::GenerationFrame {
|
||||
payload: Some(proto::generation_frame::Payload::Text(proto::TextDelta {
|
||||
text: "ok".into(),
|
||||
})),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
events.extend(
|
||||
trace
|
||||
.frame(proto::GenerationFrame {
|
||||
payload: Some(proto::generation_frame::Payload::Terminal(
|
||||
proto::Terminal {
|
||||
state: 1,
|
||||
reason: "length".into(),
|
||||
usage: Some(proto::Usage {
|
||||
input_tokens: 3,
|
||||
output_tokens: 2,
|
||||
reused_input_tokens: 0,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
let parsed = events
|
||||
.iter()
|
||||
.map(|b| {
|
||||
serde_json::from_str::<Value>(
|
||||
std::str::from_utf8(b)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("data: "))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let kinds = parsed
|
||||
.iter()
|
||||
.map(|v| v["type"].as_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
"response.created",
|
||||
"response.in_progress",
|
||||
"response.output_item.added",
|
||||
"response.content_part.added",
|
||||
"response.output_text.delta",
|
||||
"response.output_text.done",
|
||||
"response.content_part.done",
|
||||
"response.output_item.done",
|
||||
"response.incomplete"
|
||||
]
|
||||
);
|
||||
for (i, event) in parsed.iter().enumerate() {
|
||||
assert_eq!(event["sequence_number"], i);
|
||||
}
|
||||
assert_eq!(
|
||||
parsed.last().unwrap()["response"]["output"][0]["content"][0]["text"],
|
||||
"ok"
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.last().unwrap()["response"]["usage"]["total_tokens"],
|
||||
5
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn runtime_gateway_unadvertised_tool_is_terminal_failure_not_success() {
|
||||
let mut trace = trace();
|
||||
assert!(
|
||||
trace
|
||||
.frame(proto::GenerationFrame {
|
||||
payload: Some(proto::generation_frame::Payload::Tool(
|
||||
proto::ToolCallDelta::default()
|
||||
)),
|
||||
..Default::default()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
let failure = trace.interrupted();
|
||||
assert!(
|
||||
std::str::from_utf8(&failure)
|
||||
.unwrap()
|
||||
.starts_with("event: response.failed\n")
|
||||
);
|
||||
assert!(
|
||||
!std::str::from_utf8(&failure)
|
||||
.unwrap()
|
||||
.contains("response.completed")
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn runtime_gateway_terminal_without_advertised_text_finish_is_refused() {
|
||||
for reason in ["tool_calls", "unknown", ""] {
|
||||
assert!(
|
||||
trace()
|
||||
.frame(proto::GenerationFrame {
|
||||
payload: Some(proto::generation_frame::Payload::Terminal(
|
||||
proto::Terminal {
|
||||
state: 1,
|
||||
reason: reason.into(),
|
||||
..Default::default()
|
||||
}
|
||||
)),
|
||||
..Default::default()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,562 @@
|
||||
//! Independent synthetic daemon -> real HTTP/2 -> Backend boundary tests.
|
||||
//! Missing fixture credentials are supplied to an exact-test child process,
|
||||
//! never by mutating the environment of a multithreaded test process.
|
||||
//! These fixtures attest no physical model, GPU, archive or quality readiness.
|
||||
use futures_util::StreamExt;
|
||||
use leleka_backend_api as api;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use strata_desktop_core::{
|
||||
runtime_gateway::{Config, Member, Registry},
|
||||
runtime_rpc::RuntimeServer,
|
||||
};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
const TOKEN: &str = "synthetic-sdet170-token-0000000000000000";
|
||||
const ENV: &str = "LELEKA_SDET170_TOKEN";
|
||||
const PRIVATE_ERROR: &str = "synthetic-private-backend-detail";
|
||||
|
||||
fn credential_child(test: &str) -> bool {
|
||||
if std::env::var(ENV).as_deref() == Ok(TOKEN) {
|
||||
return false;
|
||||
}
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.env(ENV, TOKEN)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"exact fixture child failed: {} {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Behavior {
|
||||
Complete,
|
||||
CapacityTwice,
|
||||
Uncertain,
|
||||
AcceptedFailure,
|
||||
WaitForCancel,
|
||||
MissingTerminal,
|
||||
ToolReason,
|
||||
DelayedAck,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Facts {
|
||||
ready: AtomicBool,
|
||||
starts: AtomicUsize,
|
||||
unloads: AtomicUsize,
|
||||
cancelled: AtomicBool,
|
||||
loads: Mutex<Vec<api::RuntimeConfig>>,
|
||||
request_ids: Mutex<Vec<String>>,
|
||||
}
|
||||
struct LiteralBackend {
|
||||
facts: Arc<Facts>,
|
||||
behavior: Behavior,
|
||||
}
|
||||
fn descriptor() -> api::ModelDescriptor {
|
||||
api::ModelDescriptor {
|
||||
family: "qwen4exp".into(),
|
||||
architecture: "qwen4exp".into(),
|
||||
weight_format: "gguf:iq3_s".into(),
|
||||
artifact_digest: "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"
|
||||
.into(),
|
||||
}
|
||||
}
|
||||
fn failure(code: api::ErrorCode) -> api::BackendError {
|
||||
api::BackendError {
|
||||
code,
|
||||
message: PRIVATE_ERROR.into(),
|
||||
retryable: true,
|
||||
}
|
||||
}
|
||||
impl api::Backend for LiteralBackend {
|
||||
fn identity(&self) -> api::BackendIdentity {
|
||||
api::BackendIdentity {
|
||||
name: "independent-literal-fixture".into(),
|
||||
implementation_version: "1".into(),
|
||||
api_version: 2,
|
||||
}
|
||||
}
|
||||
fn capabilities(&self) -> api::BackendCapabilities {
|
||||
api::BackendCapabilities {
|
||||
supported_models: if self.facts.ready.load(Ordering::SeqCst) {
|
||||
vec![api::SupportedModelTuple {
|
||||
family: "qwen4exp".into(),
|
||||
architecture: "qwen4exp".into(),
|
||||
weight_format: "gguf:iq3_s".into(),
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
max_concurrent_generations: 1,
|
||||
supports_cancellation: true,
|
||||
supports_tool_call_streaming: false,
|
||||
}
|
||||
}
|
||||
fn load(
|
||||
&mut self,
|
||||
model: api::ModelDescriptor,
|
||||
config: api::RuntimeConfig,
|
||||
) -> Result<api::LoadedModel, api::BackendError> {
|
||||
self.facts.loads.lock().unwrap().push(config.clone());
|
||||
if model != descriptor() || config.inference_mode != api::InferenceMode::Native {
|
||||
return Err(failure(api::ErrorCode::UnsupportedModel));
|
||||
}
|
||||
self.facts.ready.store(true, Ordering::SeqCst);
|
||||
Ok(api::LoadedModel {
|
||||
handle: "literal-native-handle".into(),
|
||||
descriptor: model,
|
||||
load_config_version: 1,
|
||||
effective_mode: api::InferenceMode::Native,
|
||||
mode_identity_digest: format!("sha256:{}", "b".repeat(64)),
|
||||
})
|
||||
}
|
||||
fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> {
|
||||
self.facts.unloads.fetch_add(1, Ordering::SeqCst);
|
||||
self.facts.ready.store(false, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
fn cancel(&mut self, _: &str) -> Result<(), api::BackendError> {
|
||||
self.facts.cancelled.store(true, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
fn start_generation(
|
||||
&mut self,
|
||||
_: &api::LoadedModel,
|
||||
request: api::GenerationRequest,
|
||||
) -> Result<api::GenerationStream, api::BackendError> {
|
||||
let attempt = self.facts.starts.fetch_add(1, Ordering::SeqCst);
|
||||
self.facts
|
||||
.request_ids
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(request.request_id);
|
||||
if matches!(self.behavior, Behavior::CapacityTwice) && attempt < 2 {
|
||||
return Err(failure(api::ErrorCode::ResourceExhausted));
|
||||
}
|
||||
if matches!(self.behavior, Behavior::Uncertain) {
|
||||
return Err(failure(api::ErrorCode::BackendUnavailable));
|
||||
}
|
||||
if matches!(self.behavior, Behavior::DelayedAck) {
|
||||
// Exceed the daemon's two-second dispatch budget. Its HTTP/2
|
||||
// observation disappears before a backend acceptance reply exists.
|
||||
std::thread::sleep(Duration::from_millis(2500));
|
||||
}
|
||||
let (sink, stream) = api::GenerationSink::bounded_channel(4).unwrap();
|
||||
let facts = self.facts.clone();
|
||||
let behavior = self.behavior;
|
||||
std::thread::spawn(move || {
|
||||
if matches!(behavior, Behavior::MissingTerminal) {
|
||||
return;
|
||||
}
|
||||
let _ = sink.emit(api::GenerationEvent::TextDelta {
|
||||
text: "Літерал".into(),
|
||||
});
|
||||
if matches!(behavior, Behavior::WaitForCancel) {
|
||||
let end = Instant::now() + Duration::from_secs(5);
|
||||
while !facts.cancelled.load(Ordering::SeqCst) && Instant::now() < end {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
let _ = sink.cancel();
|
||||
} else if matches!(behavior, Behavior::AcceptedFailure) {
|
||||
let _ = sink.fail(api::ErrorCode::BackendUnavailable, PRIVATE_ERROR, true);
|
||||
} else {
|
||||
let usage = api::Usage {
|
||||
input_tokens: 7,
|
||||
output_tokens: 1,
|
||||
reused_input_tokens: 0,
|
||||
};
|
||||
let _ = sink.emit(api::GenerationEvent::Usage(usage.clone()));
|
||||
let reason = if matches!(behavior, Behavior::ToolReason) {
|
||||
api::FinishReason::ToolCalls
|
||||
} else {
|
||||
api::FinishReason::Stop
|
||||
};
|
||||
let _ = sink.complete(reason, usage);
|
||||
}
|
||||
});
|
||||
Ok(stream)
|
||||
}
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
base: String,
|
||||
http: reqwest::Client,
|
||||
facts: Vec<Arc<Facts>>,
|
||||
tasks: Vec<JoinHandle<()>>,
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
for facts in &self.facts {
|
||||
facts.cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Fixture {
|
||||
async fn new(behaviors: &[Behavior]) -> Self {
|
||||
assert_eq!(
|
||||
std::env::var(ENV).as_deref(),
|
||||
Ok(TOKEN),
|
||||
"supply the documented synthetic fixture credential to this test executable"
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let listen = listener.local_addr().unwrap();
|
||||
let mut facts = Vec::new();
|
||||
let mut tasks = Vec::new();
|
||||
let mut runtimes = Vec::new();
|
||||
for (index, behavior) in behaviors.iter().copied().enumerate() {
|
||||
let observed = Arc::new(Facts::default());
|
||||
let server = RuntimeServer::new(
|
||||
Box::new(LiteralBackend {
|
||||
facts: observed.clone(),
|
||||
behavior,
|
||||
}),
|
||||
TOKEN.into(),
|
||||
)
|
||||
.unwrap();
|
||||
let rpc = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = rpc.local_addr().unwrap();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
server.serve(rpc, std::future::pending()).await.unwrap();
|
||||
}));
|
||||
runtimes.push(Member {
|
||||
id: format!("native{index}"),
|
||||
address,
|
||||
token_env: ENV.into(),
|
||||
artifact_digest: descriptor().artifact_digest,
|
||||
});
|
||||
facts.push(observed);
|
||||
}
|
||||
let registry = Registry::new(Config {
|
||||
schema_version: 1,
|
||||
listen,
|
||||
token_env: ENV.into(),
|
||||
runtimes,
|
||||
http_pool: None,
|
||||
})
|
||||
.unwrap();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
axum::serve(listener, registry.router()).await.unwrap();
|
||||
}));
|
||||
Self {
|
||||
base: format!("http://{listen}"),
|
||||
http: reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(4))
|
||||
.build()
|
||||
.unwrap(),
|
||||
facts,
|
||||
tasks,
|
||||
}
|
||||
}
|
||||
async fn get(&self, route: &str, authorized: bool) -> (u16, Value) {
|
||||
let mut request = self.http.get(format!("{}{route}", self.base));
|
||||
if authorized {
|
||||
request = request.bearer_auth(TOKEN);
|
||||
}
|
||||
decode(request.send().await.unwrap()).await
|
||||
}
|
||||
async fn post(&self, route: &str, body: Value) -> (u16, Value) {
|
||||
decode(
|
||||
self.http
|
||||
.post(format!("{}{route}", self.base))
|
||||
.bearer_auth(TOKEN)
|
||||
.header("content-type", "application/json")
|
||||
.body(body.to_string())
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn epoch(&self, model: &str) -> String {
|
||||
let (status, value) = self.get("/runtime/status", true).await;
|
||||
assert_eq!(status, 200);
|
||||
value["runtimes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|v| v["id"] == model)
|
||||
.unwrap()["epoch"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.into()
|
||||
}
|
||||
async fn outcome(&self, command: &Value) -> Value {
|
||||
let query = json!({"model":command["model"],"operation_id":command["operation_id"],"epoch":command["epoch"]});
|
||||
let end = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
let (status, value) = self.post("/runtime/operation", query.clone()).await;
|
||||
assert_eq!(status, 200);
|
||||
if value["state"] != 1 {
|
||||
return value;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::Instant::now() < end,
|
||||
"operation did not finish"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
}
|
||||
}
|
||||
async fn native(&self, model: &str) -> Value {
|
||||
let command = json!({"model":model,"operation_id":uuid::Uuid::new_v4().to_string(),"epoch":self.epoch(model).await,"mode":"native"});
|
||||
let (status, _) = self.post("/runtime/load", command.clone()).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(self.outcome(&command).await["state"], 2);
|
||||
command
|
||||
}
|
||||
async fn response(&self, stream: bool) -> reqwest::Response {
|
||||
self.http.post(format!("{}/v1/responses", self.base)).bearer_auth(TOKEN).header("content-type", "application/json").body(json!({"model":"native0","input":"synthetic question","max_output_tokens":1,"stream":stream}).to_string()).send().await.unwrap()
|
||||
}
|
||||
}
|
||||
async fn decode(response: reqwest::Response) -> (u16, Value) {
|
||||
let code = response.status().as_u16();
|
||||
let text = response.text().await.unwrap();
|
||||
assert!(!text.contains(PRIVATE_ERROR));
|
||||
(code, serde_json::from_str(&text).unwrap())
|
||||
}
|
||||
fn sse(text: &str) -> Vec<Value> {
|
||||
text.split("\n\n")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(|record| {
|
||||
let data = record
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("data: "))
|
||||
.unwrap();
|
||||
serde_json::from_str(data).unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_auth_explicit_load_refusal_preserves_other_members() {
|
||||
if credential_child("catalog_auth_explicit_load_refusal_preserves_other_members") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::Complete, Behavior::Complete]).await;
|
||||
assert_eq!(f.get("/v1/models", false).await.0, 401);
|
||||
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
|
||||
let epoch = f.epoch("native0").await;
|
||||
let absent =
|
||||
json!({"model":"native0","operation_id":uuid::Uuid::new_v4().to_string(),"epoch":epoch});
|
||||
assert_eq!(f.post("/runtime/load", absent).await.0, 400);
|
||||
assert!(f.facts[0].loads.lock().unwrap().is_empty());
|
||||
f.native("native0").await;
|
||||
f.native("native1").await;
|
||||
let ple = json!({"model":"native0","operation_id":uuid::Uuid::new_v4().to_string(),"epoch":epoch,"mode":"kar-ple","profile_id":"qwen38-flash-next-ple-l2-cache64-v1"});
|
||||
assert_eq!(f.post("/runtime/load", ple.clone()).await.0, 200);
|
||||
assert_eq!(f.outcome(&ple).await["state"], 3);
|
||||
let configs = f.facts[0].loads.lock().unwrap().clone();
|
||||
assert_eq!(configs.len(), 2);
|
||||
assert_eq!(configs[0].inference_mode, api::InferenceMode::Native);
|
||||
assert!(!configs[0].allow_experimental);
|
||||
assert!(
|
||||
matches!(&configs[1].inference_mode, api::InferenceMode::ExperimentalKarPle { profile_id } if profile_id == "qwen38-flash-next-ple-l2-cache64-v1")
|
||||
);
|
||||
assert!(configs[1].allow_experimental);
|
||||
let catalog = f.get("/v1/models", true).await.1;
|
||||
let ids = catalog["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v["id"].as_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ids, ["native0", "native1"]);
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_http2_text_maps_single_ordered_sse_terminal() {
|
||||
if credential_child("actual_http2_text_maps_single_ordered_sse_terminal") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::Complete]).await;
|
||||
f.native("native0").await;
|
||||
let response = f.response(true).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["content-type"], "text/event-stream");
|
||||
let events = sse(&response.text().await.unwrap());
|
||||
let types = events
|
||||
.iter()
|
||||
.map(|v| v["type"].as_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
types,
|
||||
[
|
||||
"response.created",
|
||||
"response.in_progress",
|
||||
"response.output_item.added",
|
||||
"response.content_part.added",
|
||||
"response.output_text.delta",
|
||||
"response.output_text.done",
|
||||
"response.content_part.done",
|
||||
"response.output_item.done",
|
||||
"response.completed"
|
||||
]
|
||||
);
|
||||
for (i, event) in events.iter().enumerate() {
|
||||
assert_eq!(event["sequence_number"], i);
|
||||
}
|
||||
assert_eq!(events[4]["delta"], "Літерал");
|
||||
assert_eq!(events[8]["response"]["usage"]["total_tokens"], 8);
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proven_nonacceptance_retries_same_identity_then_succeeds() {
|
||||
if credential_child("proven_nonacceptance_retries_same_identity_then_succeeds") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::CapacityTwice]).await;
|
||||
f.native("native0").await;
|
||||
let (status, value) = decode(f.response(false).await).await;
|
||||
assert_eq!(
|
||||
status, 200,
|
||||
"two positively nonaccepted capacity refusals must permit recovery"
|
||||
);
|
||||
assert_eq!(value["status"], "completed");
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 3);
|
||||
let ids = f.facts[0].request_ids.lock().unwrap();
|
||||
assert_eq!(ids.len(), 3);
|
||||
assert!(ids.iter().all(|id| id == &ids[0]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn uncertain_dispatch_never_replays_or_advertises_ready() {
|
||||
if credential_child("uncertain_dispatch_never_replays_or_advertises_ready") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::Uncertain]).await;
|
||||
f.native("native0").await;
|
||||
let (status, value) = decode(f.response(false).await).await;
|
||||
assert_eq!(status, 502);
|
||||
assert_eq!(value["error"]["type"], "runtime_dispatch_failed");
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepted_faults_missing_terminal_and_tool_reason_fail_without_retry() {
|
||||
if credential_child("accepted_faults_missing_terminal_and_tool_reason_fail_without_retry") {
|
||||
return;
|
||||
}
|
||||
for behavior in [
|
||||
Behavior::AcceptedFailure,
|
||||
Behavior::MissingTerminal,
|
||||
Behavior::ToolReason,
|
||||
] {
|
||||
let f = Fixture::new(&[behavior]).await;
|
||||
f.native("native0").await;
|
||||
let response = f.response(true).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let text = response.text().await.unwrap();
|
||||
assert!(!text.contains(PRIVATE_ERROR));
|
||||
let events = sse(&text);
|
||||
assert_eq!(
|
||||
events
|
||||
.iter()
|
||||
.filter(|v| v["type"] == "response.failed")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(events.last().unwrap()["type"], "response.failed");
|
||||
assert!(!events.iter().any(|v| v["type"] == "response.completed"));
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
|
||||
if matches!(behavior, Behavior::MissingTerminal) {
|
||||
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_http_disconnect_cancels_one_runtime_generation() {
|
||||
if credential_child("daemon_http_disconnect_cancels_one_runtime_generation") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::WaitForCancel]).await;
|
||||
f.native("native0").await;
|
||||
let mut body = f.response(true).await.bytes_stream();
|
||||
let end = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
let mut received = Vec::new();
|
||||
let marker = b"response.output_text.delta";
|
||||
while !received.windows(marker.len()).any(|bytes| bytes == marker) {
|
||||
received.extend_from_slice(&body.next().await.unwrap().unwrap());
|
||||
assert!(tokio::time::Instant::now() < end);
|
||||
}
|
||||
drop(body);
|
||||
while !f.facts[0].cancelled.load(Ordering::SeqCst) {
|
||||
assert!(
|
||||
tokio::time::Instant::now() < end,
|
||||
"disconnect failed to cancel backend"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
}
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_unload_duplicate_returns_retained_outcome_without_reexecution() {
|
||||
if credential_child("completed_unload_duplicate_returns_retained_outcome_without_reexecution") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::Complete]).await;
|
||||
let loaded = f.native("native0").await;
|
||||
let command = json!({"model":"native0","operation_id":uuid::Uuid::new_v4().to_string(),"epoch":loaded["epoch"],"handle":"literal-native-handle"});
|
||||
assert_eq!(f.post("/runtime/unload", command.clone()).await.0, 200);
|
||||
assert_eq!(f.outcome(&command).await["state"], 2);
|
||||
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
|
||||
let (status, value) = f.post("/runtime/unload", command).await;
|
||||
assert_eq!(
|
||||
status, 200,
|
||||
"completed operation UUID must retain its outcome after unload"
|
||||
);
|
||||
assert_eq!(value["state"], 2);
|
||||
assert_eq!(f.facts[0].unloads.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lost_acknowledgement_withdraws_readiness_without_replay() {
|
||||
if credential_child("lost_acknowledgement_withdraws_readiness_without_replay") {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(&[Behavior::DelayedAck]).await;
|
||||
f.native("native0").await;
|
||||
let (status, value) = decode(f.response(false).await).await;
|
||||
assert_eq!(status, 502);
|
||||
assert_eq!(value["error"]["type"], "runtime_dispatch_failed");
|
||||
let end = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
let catalog = f.get("/v1/models", true).await.1;
|
||||
if catalog["data"] == json!([]) {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::Instant::now() < end,
|
||||
"uncertain acceptance stayed advertised ready"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
}
|
||||
while !f.facts[0].cancelled.load(Ordering::SeqCst) {
|
||||
assert!(
|
||||
tokio::time::Instant::now() < end,
|
||||
"lost acknowledgement did not schedule cancellation"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
}
|
||||
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
|
||||
let (_, states) = f.get("/runtime/status", true).await;
|
||||
assert_eq!(states["runtimes"][0]["model_ready"], false);
|
||||
}
|
||||
Reference in New Issue
Block a user