From c9aad38caa8a6d386d6691abf6aa6494d53e61c2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 02:42:11 +0200 Subject: [PATCH] refactor: extract the runtime gRPC client into leleka-runtime-client and add GrpcBackend proto/runtime.proto, the wire conversions and the validated RuntimeClient move out of strata-desktop-core so strata-next can use them; strata-desktop-core re-exports them unchanged. GrpcBackend implements the Backend contract by attaching to a runtime an operator already loaded (no Load/Unload RPC), re-reading epoch and handle before every generation, and ending a generation without a terminal event on any transport or frame error. 9 loopback HTTP/2 tests with a scripted runtime server. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 17 + Cargo.toml | 4 +- crates/runtime-client/Cargo.toml | 28 + crates/runtime-client/build.rs | 11 + .../runtime-client}/proto/runtime.proto | 0 crates/runtime-client/src/backend.rs | 334 +++++++++ crates/runtime-client/src/client.rs | 557 +++++++++++++++ crates/runtime-client/src/convert.rs | 275 ++++++++ crates/runtime-client/src/lib.rs | 24 + crates/runtime-client/tests/grpc_backend.rs | 643 ++++++++++++++++++ desktop-core/Cargo.toml | 1 + desktop-core/build.rs | 3 +- desktop-core/src/runtime_client.rs | 559 +-------------- desktop-core/src/runtime_rpc.rs | 164 +---- 14 files changed, 1904 insertions(+), 716 deletions(-) create mode 100644 crates/runtime-client/Cargo.toml create mode 100644 crates/runtime-client/build.rs rename {desktop-core => crates/runtime-client}/proto/runtime.proto (100%) create mode 100644 crates/runtime-client/src/backend.rs create mode 100644 crates/runtime-client/src/client.rs create mode 100644 crates/runtime-client/src/convert.rs create mode 100644 crates/runtime-client/src/lib.rs create mode 100644 crates/runtime-client/tests/grpc_backend.rs diff --git a/Cargo.lock b/Cargo.lock index 1b9dbe4c..4ecee01c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1085,6 +1085,22 @@ dependencies = [ "sha2", ] +[[package]] +name = "leleka-runtime-client" +version = "0.1.0" +dependencies = [ + "futures-util", + "leleka-backend-api", + "prost", + "protoc-bin-vendored", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", + "tonic-prost-build", + "uuid", +] + [[package]] name = "leleka-sampler-ref" version = "0.1.0" @@ -2157,6 +2173,7 @@ dependencies = [ "jsonschema", "leleka-backend-api", "leleka-runtime", + "leleka-runtime-client", "leleka-sampler-ref", "leleka-serving-policy", "minijinja", diff --git a/Cargo.toml b/Cargo.toml index 6e193132..26494d9a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/crates/runtime-client/Cargo.toml b/crates/runtime-client/Cargo.toml new file mode 100644 index 00000000..229ab442 --- /dev/null +++ b/crates/runtime-client/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "leleka-runtime-client" +version = "0.1.0" +description = "Client side of the leleka.runtime.v1 gRPC contract: wire messages, validated client, and a Backend that attaches to a running leleka-inference" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +leleka-backend-api = { path = "../backend-api" } +prost = "0.14" +tokio = { version = "1", features = ["rt", "time", "sync", "net"] } +tonic = "0.14.6" +tonic-prost = "0.14.6" +uuid = { version = "1", features = ["v4"] } + +[build-dependencies] +protoc-bin-vendored = "3" +tonic-prost-build = "0.14.6" + +[dev-dependencies] +futures-util = "0.3" +leleka-backend-api = { path = "../backend-api", features = ["scripted"] } +tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "time", "sync", "net"] } +tokio-stream = { version = "0.1", features = ["net", "sync"] } + +[lints] +workspace = true diff --git a/crates/runtime-client/build.rs b/crates/runtime-client/build.rs new file mode 100644 index 00000000..56c19807 --- /dev/null +++ b/crates/runtime-client/build.rs @@ -0,0 +1,11 @@ +fn main() -> Result<(), Box> { + let mut config = tonic_prost_build::Config::new(); + config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); + tonic_prost_build::configure().compile_with_config( + config, + &["proto/runtime.proto"], + &["proto"], + )?; + println!("cargo:rerun-if-changed=proto/runtime.proto"); + Ok(()) +} diff --git a/desktop-core/proto/runtime.proto b/crates/runtime-client/proto/runtime.proto similarity index 100% rename from desktop-core/proto/runtime.proto rename to crates/runtime-client/proto/runtime.proto diff --git a/crates/runtime-client/src/backend.rs b/crates/runtime-client/src/backend.rs new file mode 100644 index 00000000..dd20cd05 --- /dev/null +++ b/crates/runtime-client/src/backend.rs @@ -0,0 +1,334 @@ +//! [`GrpcBackend`]: the backend contract over a running `leleka-inference`. +//! +//! It **attaches**: [`Backend::load`] returns the model the runtime already reports as loaded, after +//! checking it against what the caller expects (descriptor, load configuration version, effective +//! mode). It never sends a `Load` or `Unload` RPC; the runtime's lifecycle belongs to its operator +//! (`leleka-cli load-mtp`), and an HTTP request must not be able to start a multi-gigabyte load. +//! +//! Every generation re-reads the runtime snapshot and sends the epoch and handle it saw, so a +//! restarted runtime (new epoch, no model) is refused before dispatch instead of being addressed with +//! a stale identity. Nothing is retried: a generation that may have been dispatched is never replayed. +//! +//! The trait is synchronous; calls must come from a thread that may block (a `spawn_blocking` task, +//! never an async task), and `runtime` must be a handle of a runtime that is running. + +use std::{ + net::SocketAddr, + sync::{Arc, Mutex}, +}; + +use leleka_backend_api as api; +use tokio::runtime::Handle; +use tonic::Code; + +use crate::{ + client::{RuntimeClient, RuntimeGeneration}, + convert, proto, +}; + +pub struct GrpcBackend { + runtime: Handle, + address: SocketAddr, + token: String, + client: Option, + attached: Option, + /// Shared with the pump task so `cancel` can address the running request. + active: Arc>>, +} + +#[derive(Clone)] +struct Attached { + epoch: String, + handle: String, +} + +#[derive(Clone)] +struct ActiveRequest { + id: String, + epoch: String, +} + +fn error(code: api::ErrorCode, message: impl Into, retryable: bool) -> api::BackendError { + api::BackendError { + code, + message: message.into(), + retryable, + } +} + +/// A transport or protocol failure is `BackendUnavailable` (the caller attaches again); a refusal +/// that proves nothing was accepted keeps its meaning. +fn from_status(status: &tonic::Status) -> api::BackendError { + let proven_unaccepted = status + .metadata() + .get("x-leleka-accepted") + .and_then(|v| v.to_str().ok()) + == Some("false"); + let (code, retryable) = match status.code() { + Code::InvalidArgument => (api::ErrorCode::InvalidRequest, false), + Code::FailedPrecondition => (api::ErrorCode::UnsupportedModel, false), + Code::ResourceExhausted => (api::ErrorCode::ResourceExhausted, proven_unaccepted), + Code::Unauthenticated | Code::PermissionDenied => (api::ErrorCode::Internal, false), + Code::Unavailable | Code::DeadlineExceeded | Code::Cancelled | Code::DataLoss => { + (api::ErrorCode::BackendUnavailable, false) + } + _ => (api::ErrorCode::Internal, false), + }; + error( + code, + format!("runtime: {} ({:?})", status.message(), status.code()), + retryable, + ) +} + +impl GrpcBackend { + pub fn new(runtime: Handle, address: SocketAddr, token: String) -> Self { + Self { + runtime, + address, + token, + client: None, + attached: None, + active: Arc::new(Mutex::new(None)), + } + } + + /// The current runtime snapshot, connecting first if needed. A failure forgets the connection + /// so the next call connects again. + fn snapshot(&mut self) -> Result { + if self.client.is_none() { + let (address, token) = (self.address, self.token.clone()); + let client = self + .runtime + .block_on(RuntimeClient::connect(address, token)) + .map_err(|status| from_status(&status))?; + self.client = Some(client); + } + let client = self.client.as_mut().expect("client was just set"); + match self.runtime.block_on(client.snapshot()) { + Ok(snapshot) => Ok(snapshot), + Err(status) => { + self.client = None; + Err(from_status(&status)) + } + } + } +} + +impl api::Backend for GrpcBackend { + fn identity(&self) -> api::BackendIdentity { + api::BackendIdentity { + name: "leleka-runtime-grpc".into(), + implementation_version: env!("CARGO_PKG_VERSION").into(), + api_version: api::BACKEND_API_VERSION, + } + } + + /// What the runtime advertises right now: re-read on every call (a health probe), empty when + /// it is unreachable, has no model loaded, or has restarted since the attach. + fn capabilities(&self) -> api::BackendCapabilities { + // `capabilities` takes `&self` by contract; the probe needs a connection of its own. + let (address, token) = (self.address, self.token.clone()); + let attached = self.attached.clone(); + let existing = self.client.clone(); + let probe = self.runtime.block_on(async move { + let mut client = match existing { + Some(client) => client, + None => RuntimeClient::connect(address, token).await.ok()?, + }; + client.snapshot().await.ok() + }); + match (probe, attached) { + (Some(snapshot), Some(attached)) + if snapshot.model_ready + && snapshot.epoch == attached.epoch + && snapshot + .loaded + .as_ref() + .is_some_and(|l| l.handle == attached.handle) => + { + snapshot + .capabilities + .as_ref() + .map(convert::capabilities_from_proto) + .unwrap_or_default() + } + _ => api::BackendCapabilities::default(), + } + } + + fn load( + &mut self, + model: api::ModelDescriptor, + config: api::RuntimeConfig, + ) -> Result { + self.attached = None; + let snapshot = self.snapshot()?; + let loaded = match snapshot.loaded.as_ref().filter(|_| snapshot.model_ready) { + Some(loaded) => convert::loaded_from_proto(loaded).map_err(|s| from_status(&s))?, + None => { + return Err(error( + api::ErrorCode::BackendUnavailable, + "the runtime has no model loaded; load it with leleka-cli", + true, + )); + } + }; + loaded.validate_for_load(&model, &config).map_err(|_| { + error( + api::ErrorCode::UnsupportedModel, + "the runtime's loaded model, load configuration or mode is not the one expected", + false, + ) + })?; + self.attached = Some(Attached { + epoch: snapshot.epoch, + handle: loaded.handle.clone(), + }); + Ok(loaded) + } + + fn start_generation( + &mut self, + model: &api::LoadedModel, + request: api::GenerationRequest, + ) -> Result { + let attached = self.attached.clone().ok_or_else(|| { + error( + api::ErrorCode::BackendUnavailable, + "not attached to a loaded model", + true, + ) + })?; + if attached.handle != model.handle { + return Err(error( + api::ErrorCode::BackendUnavailable, + "stale model handle", + true, + )); + } + // Fresh identity check: the runtime may have restarted since the last call. + let snapshot = match self.snapshot() { + Ok(snapshot) => snapshot, + Err(error) => { + self.attached = None; + return Err(error); + } + }; + let still = snapshot + .loaded + .as_ref() + .is_some_and(|l| l.handle == attached.handle); + if snapshot.epoch != attached.epoch || !snapshot.model_ready || !still { + self.attached = None; + return Err(error( + api::ErrorCode::BackendUnavailable, + "the runtime restarted or unloaded the model", + true, + )); + } + let mut wire = proto::GenerateRequest { + request_id: request.request_id.clone(), + expected_epoch: attached.epoch.clone(), + handle: attached.handle.clone(), + ..Default::default() + }; + convert::apply_generation_request(&mut wire, &request); + let client = self.client.as_mut().expect("snapshot connected the client"); + let generation = self + .runtime + .block_on(client.generate(wire)) + .map_err(|status| from_status(&status))?; + *self.active.lock().expect("active lock") = Some(ActiveRequest { + id: request.request_id, + epoch: attached.epoch, + }); + let (sink, stream) = api::GenerationSink::channel(); + let active = Arc::clone(&self.active); + self.runtime.spawn(pump(generation, sink, active)); + Ok(stream) + } + + fn cancel(&mut self, request_id: &str) -> Result<(), api::BackendError> { + let active = self.active.lock().expect("active lock").clone(); + let Some(active) = active.filter(|a| a.id == request_id) else { + return Err(error( + api::ErrorCode::InvalidRequest, + "generation is not active", + false, + )); + }; + let Some(client) = self.client.as_mut() else { + return Err(error( + api::ErrorCode::BackendUnavailable, + "not connected", + true, + )); + }; + self.runtime + .block_on(client.cancel(proto::CancelRequest { + request_id: active.id, + expected_epoch: active.epoch, + })) + .map(|_| ()) + .map_err(|status| from_status(&status)) + } + + fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> { + Err(error( + api::ErrorCode::InvalidRequest, + "this backend only attaches to a loaded runtime; unload it with leleka-cli", + false, + )) + } +} + +/// Completes when the consumer dropped its stream. +async fn consumer_gone(sink: &api::GenerationSink) { + while !sink.is_closed() { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } +} + +/// Forward frames to the consumer. A transport failure or a malformed frame ends the stream +/// *without* a terminal event, which the consumer reports as a lost engine; dropping `generation` +/// afterwards asks the runtime to cancel the request. +async fn pump( + mut generation: RuntimeGeneration, + sink: api::GenerationSink, + active: Arc>>, +) { + let clear = |active: &Arc>>| { + *active.lock().expect("active lock") = None; + }; + loop { + // A consumer that dropped the stream is a cancellation the runtime must hear about. + if sink.is_closed() { + break; // dropping `generation` below sends the Cancel + } + let frame = tokio::select! { + frame = generation.message() => match frame { + Ok(Some(frame)) => frame, + Ok(None) | Err(_) => break, + }, + // The consumer can go away while the runtime is silent (a long prefill). + () = consumer_gone(&sink) => break, + }; + let Some(payload) = frame.payload else { break }; + if matches!(payload, proto::generation_frame::Payload::Accepted(_)) { + continue; + } + let Ok(event) = convert::event_from_proto(payload) else { + break; + }; + let terminal = matches!(event, api::GenerationEvent::Terminal(_)); + // Release the active slot before the terminal is visible, so the next generation can start. + if terminal { + clear(&active); + } + if sink.emit(event).is_err() || terminal { + return; + } + } + clear(&active); +} diff --git a/crates/runtime-client/src/client.rs b/crates/runtime-client/src/client.rs new file mode 100644 index 00000000..f6a0b4d1 --- /dev/null +++ b/crates/runtime-client/src/client.rs @@ -0,0 +1,557 @@ +//! One-shot runtime commands. No generation replay or automatic lifecycle retry. +use crate::{FRAME_LIMIT, MESSAGE_LIMIT, PROTOCOL_VERSION, convert, 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, + token: String, +} + +impl RuntimeClient { + pub async fn connect(address: SocketAddr, token: String) -> Result { + convert::literal_loopback(address)?; + if !convert::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( + &self, + value: T, + limit: usize, + timeout: Duration, + ) -> Result, 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 { + 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 { + 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, 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 { + 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 { + 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 { + 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 { + 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 { + 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 = convert::descriptor_from_proto( + loaded + .descriptor + .as_ref() + .ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?, + )?; + let config = convert::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, + client: RuntimeClient, + id: String, + epoch: String, + sequence: u64, + terminal: bool, + failed: bool, +} +impl RuntimeGeneration { + pub async fn message(&mut self) -> Result, 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(convert::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, + } + 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, + ) -> Result, Status> { + Ok(Response::new(self.snapshot())) + } + async fn snapshot( + &self, + _: Request, + ) -> Result, Status> { + Ok(Response::new(self.snapshot())) + } + type WatchStream = Pin> + Send>>; + async fn watch( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn load( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn unload( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn operation( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn cancel( + &self, + request: Request, + ) -> Result, 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> + Send>>; + async fn generate( + &self, + request: Request, + ) -> Result, 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, + ..Default::default() + }) + .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(); + } + } +} diff --git a/crates/runtime-client/src/convert.rs b/crates/runtime-client/src/convert.rs new file mode 100644 index 00000000..f41027e6 --- /dev/null +++ b/crates/runtime-client/src/convert.rs @@ -0,0 +1,275 @@ +//! Conversions between the backend contract and the `leleka.runtime.v1` wire messages, shared by +//! the server (`strata-desktop-core`) and the clients (the daemon gateway and `strata-next`). +use leleka_backend_api as api; +use std::net::SocketAddr; +use tonic::Status; + +use crate::proto; + +pub fn valid_token(token: &str) -> bool { + (32..=4096).contains(&token.len()) && token.bytes().all(|b| (0x21..=0x7e).contains(&b)) +} +pub fn literal_loopback(address: SocketAddr) -> Result<(), Status> { + if !address.ip().is_loopback() { + return Err(Status::permission_denied("loopback_required")); + } + Ok(()) +} +/// Only this marker is positive evidence of nonacceptance. Absence is uncertain. +pub fn refusal(code: tonic::Code, reason: &'static str) -> Status { + let mut status = Status::new(code, reason); + status.metadata_mut().insert( + "x-leleka-accepted", + "false".parse().expect("literal metadata"), + ); + status +} + +pub fn descriptor_to_proto(value: &api::ModelDescriptor) -> proto::ModelDescriptor { + proto::ModelDescriptor { + family: value.family.clone(), + architecture: value.architecture.clone(), + artifact_digest: value.artifact_digest.clone(), + weight_format: value.weight_format.clone(), + } +} +pub fn descriptor_from_proto( + value: &proto::ModelDescriptor, +) -> Result { + let model = api::ModelDescriptor { + family: value.family.clone(), + architecture: value.architecture.clone(), + artifact_digest: value.artifact_digest.clone(), + weight_format: value.weight_format.clone(), + }; + if [ + model.family.len(), + model.architecture.len(), + model.weight_format.len(), + ] + .into_iter() + .any(|n| n > 128) + || model.validate().is_err() + { + return Err(refusal( + tonic::Code::InvalidArgument, + "invalid_model_descriptor", + )); + } + Ok(model) +} +pub fn mode_to_proto(mode: &api::InferenceMode) -> proto::InferenceMode { + use proto::inference_mode::Selection; + let selection = match mode { + api::InferenceMode::Native => Selection::Native(proto::NativeMode {}), + api::InferenceMode::ExperimentalKarPle { profile_id } => { + Selection::KarPle(proto::KarPleMode { + profile_id: profile_id.clone(), + }) + } + api::InferenceMode::ExperimentalMtp { profile_id } => Selection::Mtp(proto::MtpMode { + profile_id: profile_id.clone(), + }), + api::InferenceMode::ExperimentalKarExperts(e) => { + Selection::KarExperts(proto::KarExpertsMode { + bundle_directory: e.bundle_directory.clone(), + archive_file: e.archive_file.clone(), + binding_file: e.binding_file.clone(), + provenance_file: e.provenance_file.clone(), + levels: u32::from(e.levels), + cache_mib: e.cache_mib, + prefill_mode: match e.prefill_mode { + api::KarPrefillMode::DecodeOnly => 1, + api::KarPrefillMode::AllRoutedBatched => 2, + }, + }) + } + }; + proto::InferenceMode { + selection: Some(selection), + } +} +pub fn config_to_proto(config: &api::RuntimeConfig) -> proto::LoadConfig { + proto::LoadConfig { + version: u32::from(config.load_config_version), + mode: Some(mode_to_proto(&config.inference_mode)), + gpu_memory_limit_bytes: config.gpu_memory_limit_bytes, + allow_experimental: config.allow_experimental, + } +} +pub fn config_from_proto(config: &proto::LoadConfig) -> Result { + use proto::inference_mode::Selection; + let mode = match config.mode.as_ref().and_then(|m| m.selection.as_ref()) { + Some(Selection::Native(_)) => api::InferenceMode::Native, + Some(Selection::KarPle(p)) => api::InferenceMode::ExperimentalKarPle { + profile_id: p.profile_id.clone(), + }, + Some(Selection::Mtp(p)) => api::InferenceMode::ExperimentalMtp { + profile_id: p.profile_id.clone(), + }, + Some(Selection::KarExperts(e)) => { + api::InferenceMode::ExperimentalKarExperts(api::KarExpertLoad { + bundle_directory: e.bundle_directory.clone(), + archive_file: e.archive_file.clone(), + binding_file: e.binding_file.clone(), + provenance_file: e.provenance_file.clone(), + levels: u8::try_from(e.levels) + .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_expert_levels"))?, + cache_mib: e.cache_mib, + prefill_mode: match e.prefill_mode { + 1 => api::KarPrefillMode::DecodeOnly, + 2 => api::KarPrefillMode::AllRoutedBatched, + _ => { + return Err(refusal( + tonic::Code::InvalidArgument, + "invalid_expert_prefill", + )); + } + }, + }) + } + None => { + return Err(refusal( + tonic::Code::InvalidArgument, + "missing_inference_mode", + )); + } + }; + let value = api::RuntimeConfig { + load_config_version: u16::try_from(config.version) + .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_version"))?, + inference_mode: mode, + gpu_memory_limit_bytes: config.gpu_memory_limit_bytes, + allow_experimental: config.allow_experimental, + }; + value + .validate() + .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_config"))?; + Ok(value) +} +pub fn loaded_to_proto(value: &api::LoadedModel) -> proto::LoadedModel { + proto::LoadedModel { + handle: value.handle.clone(), + descriptor: Some(descriptor_to_proto(&value.descriptor)), + load_config_version: u32::from(value.load_config_version), + effective_mode: Some(mode_to_proto(&value.effective_mode)), + mode_identity_digest: value.mode_identity_digest.clone(), + } +} + +/// The loaded model a runtime reports in a snapshot, as the backend contract describes it. +/// Experimental permission is implied by an experimental mode that is already running; this only +/// reads what the runtime says, it does not authorise a load. +pub fn loaded_from_proto(value: &proto::LoadedModel) -> Result { + let descriptor = descriptor_from_proto( + value + .descriptor + .as_ref() + .ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?, + )?; + let config = config_from_proto(&proto::LoadConfig { + version: value.load_config_version, + mode: value.effective_mode.clone(), + gpu_memory_limit_bytes: None, + allow_experimental: true, + })?; + Ok(api::LoadedModel { + handle: value.handle.clone(), + descriptor, + load_config_version: config.load_config_version, + effective_mode: config.inference_mode, + mode_identity_digest: value.mode_identity_digest.clone(), + }) +} + +pub fn capabilities_from_proto(value: &proto::Capabilities) -> api::BackendCapabilities { + api::BackendCapabilities { + supported_models: value + .models + .iter() + .map(|m| api::SupportedModelTuple { + family: m.family.clone(), + architecture: m.architecture.clone(), + weight_format: m.weight_format.clone(), + }) + .collect(), + max_concurrent_generations: value.max_concurrent_generations as usize, + supports_cancellation: value.cancellation, + supports_tool_call_streaming: value.tool_call_streaming, + } +} + +fn usage_from_proto(value: &proto::Usage) -> api::Usage { + api::Usage { + input_tokens: value.input_tokens, + output_tokens: value.output_tokens, + reused_input_tokens: value.reused_input_tokens, + } +} + +/// One generation frame as a backend event. A frame the contract cannot express is an error: the +/// caller must end the generation without a terminal event rather than invent one. +pub fn event_from_proto( + payload: proto::generation_frame::Payload, +) -> Result { + use proto::generation_frame::Payload; + Ok(match payload { + Payload::Accepted(_) => return Err(Status::data_loss("unexpected_accepted_frame")), + Payload::Text(text) => api::GenerationEvent::TextDelta { text: text.text }, + Payload::Tool(tool) => api::GenerationEvent::ToolCallDelta { + index: tool.index, + id: tool.id, + name: tool.name, + arguments_delta: tool.arguments_delta, + }, + Payload::Usage(usage) => api::GenerationEvent::Usage(usage_from_proto(&usage)), + Payload::Terminal(terminal) => api::GenerationEvent::Terminal(match terminal.state { + 1 => api::GenerationTerminal::Completed { + reason: match terminal.reason.as_str() { + "stop" => api::FinishReason::Stop, + "length" => api::FinishReason::Length, + "tool_calls" => api::FinishReason::ToolCalls, + _ => return Err(Status::data_loss("unknown_finish_reason")), + }, + usage: usage_from_proto( + terminal + .usage + .as_ref() + .ok_or_else(|| Status::data_loss("missing_terminal_usage"))?, + ), + }, + 2 => api::GenerationTerminal::Failed { + code: match terminal.error_code.as_str() { + "invalid_request" => api::ErrorCode::InvalidRequest, + "unsupported_model" => api::ErrorCode::UnsupportedModel, + "resource_exhausted" => api::ErrorCode::ResourceExhausted, + "backend_unavailable" => api::ErrorCode::BackendUnavailable, + _ => api::ErrorCode::Internal, + }, + message: terminal.reason, + retryable: terminal.retryable, + }, + 3 => api::GenerationTerminal::Cancelled, + _ => return Err(Status::data_loss("invalid_generation_terminal")), + }), + }) +} + +/// The prompt and sampling controls of a backend request as wire fields. +pub fn apply_generation_request( + wire: &mut proto::GenerateRequest, + request: &api::GenerationRequest, +) { + wire.prompt = request.prompt.clone(); + wire.max_output_tokens = request.max_output_tokens; + wire.temperature_milli = request.temperature_milli; + let s = &request.sampling; + wire.top_p_micro = s.top_p_micro; + wire.top_k = s.top_k; + wire.min_p_micro = s.min_p_micro; + wire.repetition_penalty_micro = s.repetition_penalty_micro; + wire.frequency_penalty_micro = s.frequency_penalty_micro; + wire.presence_penalty_micro = s.presence_penalty_micro; + wire.penalty_last_n = s.penalty_last_n; + wire.seed = s.seed; +} diff --git a/crates/runtime-client/src/lib.rs b/crates/runtime-client/src/lib.rs new file mode 100644 index 00000000..6e6d5b53 --- /dev/null +++ b/crates/runtime-client/src/lib.rs @@ -0,0 +1,24 @@ +//! The client side of the `leleka.runtime.v1` gRPC contract between a gateway and `leleka-inference`. +//! +//! * [`proto`]: the generated wire messages and both service stubs (the server implementation lives in +//! `strata-desktop-core`); +//! * [`convert`]: backend-contract <-> wire conversions and the credential / loopback rules; +//! * [`client`]: [`client::RuntimeClient`], one authenticated channel whose every answer is validated +//! (epochs, sequence numbers, a terminal frame before end of stream); +//! * [`backend`]: [`backend::GrpcBackend`], a [`leleka_backend_api::Backend`] that attaches to a runtime +//! some operator already loaded, so a gateway can drive the Rust engine through the same trait the +//! in-process backends implement. +//! +//! No CUDA, model, Strata or Python dependency. + +pub mod backend; +pub mod client; +pub mod convert; + +pub mod proto { + tonic::include_proto!("leleka.runtime.v1"); +} + +pub const PROTOCOL_VERSION: u32 = 1; +pub const MESSAGE_LIMIT: usize = 2 * 1024 * 1024; +pub const FRAME_LIMIT: usize = 64 * 1024; diff --git a/crates/runtime-client/tests/grpc_backend.rs b/crates/runtime-client/tests/grpc_backend.rs new file mode 100644 index 00000000..d209f1df --- /dev/null +++ b/crates/runtime-client/tests/grpc_backend.rs @@ -0,0 +1,643 @@ +//! `GrpcBackend` against a scripted `leleka.runtime.v1` server over real loopback HTTP/2. +//! +//! The server here is a stand-in: it answers snapshots, replays the frames a test gives it and counts +//! cancels. The full chain with the real `RuntimeServer` and a scripted engine behind it is exercised +//! in `strata-desktop-core` (`tests/api_over_runtime.rs`). Nothing here loads a model. + +use std::{ + net::SocketAddr, + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +use futures_util::Stream; +use leleka_backend_api::{ + Backend, ErrorCode, FinishReason, GenerationEvent, GenerationRequest, GenerationTerminal, + InferenceMode, LoadedModel, ModelDescriptor, RuntimeConfig, SamplingOptions, StreamError, + Usage, +}; +use leleka_runtime_client::{ + backend::GrpcBackend, + convert, + proto::{self, generation_frame::Payload}, +}; +use tonic::{Request, Response, Status}; + +const TOKEN: &str = "synthetic-grpc-backend-token-000000000"; +type Frames = Vec>; + +fn descriptor() -> ModelDescriptor { + ModelDescriptor { + family: "fixture_family".into(), + architecture: "fixture_arch".into(), + artifact_digest: format!("sha256:{}", "e".repeat(64)), + weight_format: "fixture:format".into(), + } +} + +fn config() -> RuntimeConfig { + RuntimeConfig { + load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION, + inference_mode: InferenceMode::Native, + gpu_memory_limit_bytes: None, + allow_experimental: false, + } +} + +fn loaded(handle: &str) -> LoadedModel { + LoadedModel { + handle: handle.into(), + descriptor: descriptor(), + load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION, + effective_mode: InferenceMode::Native, + mode_identity_digest: format!("sha256:{}", "f".repeat(64)), + } +} + +#[derive(Clone)] +struct Fake { + state: Arc>, + cancels: Arc, +} + +struct FakeState { + epoch: String, + sequence: u64, + loaded: Option, + scripts: Vec, + requests: Vec, + cancel_requests: Vec, +} + +impl Fake { + fn new(loaded: Option) -> Self { + Self { + state: Arc::new(Mutex::new(FakeState { + epoch: uuid::Uuid::new_v4().to_string(), + sequence: 1, + loaded, + scripts: Vec::new(), + requests: Vec::new(), + cancel_requests: Vec::new(), + })), + cancels: Arc::new(AtomicUsize::new(0)), + } + } + + fn snapshot(&self) -> proto::Snapshot { + let mut state = self.state.lock().unwrap(); + state.sequence += 1; + proto::Snapshot { + protocol_version: 1, + backend_api_version: 2, + epoch: state.epoch.clone(), + sequence: state.sequence, + full_snapshot: true, + transport_ready: true, + model_ready: state.loaded.is_some(), + loaded: state.loaded.as_ref().map(convert::loaded_to_proto), + capabilities: Some(proto::Capabilities { + models: if state.loaded.is_some() { + vec![proto::SupportedModelTuple { + family: descriptor().family, + architecture: descriptor().architecture, + weight_format: descriptor().weight_format, + }] + } else { + Vec::new() + }, + max_concurrent_generations: 1, + cancellation: true, + tool_call_streaming: false, + }), + active_request_id: String::new(), + } + } + + /// A new process: new epoch, model gone until `set_loaded`. + fn restart(&self) { + let mut state = self.state.lock().unwrap(); + state.epoch = uuid::Uuid::new_v4().to_string(); + state.loaded = None; + } + + fn set_loaded(&self, loaded: Option) { + self.state.lock().unwrap().loaded = loaded; + } + + fn push(&self, frames: Frames) { + self.state.lock().unwrap().scripts.push(frames); + } +} + +#[tonic::async_trait] +impl proto::runtime_server::Runtime for Fake { + async fn handshake( + &self, + _: Request, + ) -> Result, Status> { + Ok(Response::new(self.snapshot())) + } + async fn snapshot( + &self, + _: Request, + ) -> Result, Status> { + Ok(Response::new(self.snapshot())) + } + type WatchStream = Pin> + Send>>; + async fn watch( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn load( + &self, + _: Request, + ) -> Result, Status> { + panic!("an attach-only backend must never send Load"); + } + async fn unload( + &self, + _: Request, + ) -> Result, Status> { + panic!("an attach-only backend must never send Unload"); + } + async fn operation( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn cancel( + &self, + request: Request, + ) -> Result, Status> { + self.cancels.fetch_add(1, Ordering::SeqCst); + let request = request.into_inner(); + let ack = proto::CancelAck { + request_id: request.request_id.clone(), + epoch: request.expected_epoch.clone(), + acknowledged: true, + }; + self.state.lock().unwrap().cancel_requests.push(request); + Ok(Response::new(ack)) + } + type GenerateStream = + Pin> + Send>>; + async fn generate( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let (epoch, frames) = { + let mut state = self.state.lock().unwrap(); + state.requests.push(request.clone()); + let frames = if state.scripts.is_empty() { + Vec::new() + } else { + state.scripts.remove(0) + }; + (state.epoch.clone(), frames) + }; + let id = request.request_id; + let mut out: Vec> = Vec::new(); + let sequence = 1; + let frame = |sequence, payload| proto::GenerationFrame { + request_id: id.clone(), + epoch: epoch.clone(), + sequence, + payload: Some(payload), + }; + out.push(Ok(frame( + sequence, + Payload::Accepted(proto::Accepted { accepted: true }), + ))); + for (sequence, item) in (2..).zip(frames) { + out.push(item.map(|payload| frame(sequence, payload))); + } + // A trailing `Aborted("hang")` means: stay open and silent after the scripted frames. + let hang = matches!(out.last(), Some(Err(s)) if s.code() == tonic::Code::Aborted && s.message() == "hang"); + if hang { + out.pop(); + } + let stream: Self::GenerateStream = if hang { + Box::pin(tokio_stream::StreamExt::chain( + tokio_stream::iter(out), + futures_util::stream::pending(), + )) + } else { + Box::pin(tokio_stream::iter(out)) + }; + let mut response = Response::new(stream); + response + .metadata_mut() + .insert("x-leleka-accepted", "true".parse().unwrap()); + Ok(response) + } +} + +struct Server { + address: SocketAddr, + fake: Fake, + stop: Option>, + task: tokio::task::JoinHandle<()>, +} + +impl Server { + async fn start(loaded: Option) -> Self { + let fake = Fake::new(loaded); + 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 service = fake.clone(); + 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(); + }); + Self { + address, + fake, + stop: Some(stop), + task, + } + } + + fn backend(&self) -> GrpcBackend { + GrpcBackend::new( + tokio::runtime::Handle::current(), + self.address, + TOKEN.into(), + ) + } + + async fn finish(mut self) { + let _ = self.stop.take().unwrap().send(()); + if tokio::time::timeout(Duration::from_millis(300), &mut self.task) + .await + .is_err() + { + self.task.abort(); + } + } +} + +fn usage(i: u64, o: u64, r: u64) -> proto::Usage { + proto::Usage { + input_tokens: i, + output_tokens: o, + reused_input_tokens: r, + } +} + +fn terminal(state: i32, reason: &str, with_usage: bool) -> Payload { + Payload::Terminal(proto::Terminal { + state, + reason: reason.into(), + usage: with_usage.then(|| usage(10, 3, 2)), + error_code: if state == 2 { + "resource_exhausted".into() + } else { + String::new() + }, + retryable: false, + }) +} + +fn text(s: &str) -> Payload { + Payload::Text(proto::TextDelta { text: s.into() }) +} + +fn request(id: &str) -> GenerationRequest { + GenerationRequest { + request_id: id.into(), + prompt: "<|im_start|>user\nhi<|im_end|>\n".into(), + max_output_tokens: 64, + temperature_milli: 700, + sampling: SamplingOptions { + top_p_micro: Some(900_000), + top_k: Some(20), + min_p_micro: Some(50_000), + repetition_penalty_micro: Some(1_100_000), + frequency_penalty_micro: Some(-500_000), + presence_penalty_micro: Some(250_000), + penalty_last_n: Some(64), + seed: Some(42), + }, + } +} + +/// Run a blocking backend call on a blocking thread, as the control plane does. +async fn blocking( + mut backend: GrpcBackend, + call: impl FnOnce(&mut GrpcBackend) -> T + Send + 'static, +) -> (GrpcBackend, T) { + tokio::task::spawn_blocking(move || { + let value = call(&mut backend); + (backend, value) + }) + .await + .unwrap() +} + +fn id() -> String { + uuid::Uuid::new_v4().to_string() +} + +fn drain(stream: &mut leleka_backend_api::GenerationStream) -> (Vec, bool) { + let mut events = Vec::new(); + loop { + match stream.recv() { + Ok(Some(event)) => events.push(event), + Ok(None) => return (events, true), + Err(StreamError::MissingTerminal) => return (events, false), + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn attach_returns_the_loaded_model_and_never_sends_load() { + let server = Server::start(Some(loaded("h-1"))).await; + let backend = server.backend(); + let (_backend, result) = blocking(backend, |b| b.load(descriptor(), config())).await; + let attached = result.unwrap(); + assert_eq!(attached.handle, "h-1"); + assert_eq!(attached.descriptor, descriptor()); + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn attach_refuses_what_it_did_not_expect() { + // No model loaded: retryable, so the caller waits and tries again. + let server = Server::start(None).await; + let (_b, result) = blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::BackendUnavailable); + assert!(error.retryable); + + // A different artifact digest, and a different mode, are not silently accepted. + server.fake.set_loaded(Some(loaded("h-1"))); + let other = ModelDescriptor { + artifact_digest: format!("sha256:{}", "0".repeat(64)), + ..descriptor() + }; + let (_b, result) = blocking(server.backend(), move |b| b.load(other, config())).await; + assert_eq!(result.unwrap_err().code, ErrorCode::UnsupportedModel); + let mtp = RuntimeConfig { + inference_mode: InferenceMode::ExperimentalMtp { + profile_id: "qwen4exp-kar-ple-mtp-v1".into(), + }, + allow_experimental: true, + ..config() + }; + let (_b, result) = blocking(server.backend(), move |b| b.load(descriptor(), mtp)).await; + assert_eq!(result.unwrap_err().code, ErrorCode::UnsupportedModel); + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_generation_sends_the_identity_and_every_sampling_field_and_maps_frames() { + let server = Server::start(Some(loaded("h-1"))).await; + server.fake.push(vec![ + Ok(text("hel")), + Ok(text("lo")), + Ok(Payload::Usage(usage(10, 2, 2))), + Ok(terminal(1, "stop", true)), + ]); + let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let attached = attached.unwrap(); + let request_id = id(); + let sent = request(&request_id); + let (_backend, stream) = blocking(backend, move |b| b.start_generation(&attached, sent)).await; + let mut stream = stream.unwrap(); + let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) + .await + .unwrap(); + assert!(terminated); + assert_eq!( + events, + vec![ + GenerationEvent::TextDelta { text: "hel".into() }, + GenerationEvent::TextDelta { text: "lo".into() }, + GenerationEvent::Usage(Usage { + input_tokens: 10, + output_tokens: 2, + reused_input_tokens: 2 + }), + GenerationEvent::Terminal(GenerationTerminal::Completed { + reason: FinishReason::Stop, + usage: Usage { + input_tokens: 10, + output_tokens: 3, + reused_input_tokens: 2 + } + }), + ] + ); + let seen = server.fake.state.lock().unwrap().requests[0].clone(); + assert_eq!(seen.request_id, request_id); + assert_eq!(seen.handle, "h-1"); + assert_eq!(seen.expected_epoch, server.fake.state.lock().unwrap().epoch); + assert_eq!(seen.prompt, "<|im_start|>user\nhi<|im_end|>\n"); + assert_eq!((seen.max_output_tokens, seen.temperature_milli), (64, 700)); + assert_eq!(seen.top_p_micro, Some(900_000)); + assert_eq!(seen.top_k, Some(20)); + assert_eq!(seen.min_p_micro, Some(50_000)); + assert_eq!(seen.repetition_penalty_micro, Some(1_100_000)); + assert_eq!(seen.frequency_penalty_micro, Some(-500_000)); + assert_eq!(seen.presence_penalty_micro, Some(250_000)); + assert_eq!(seen.penalty_last_n, Some(64)); + assert_eq!(seen.seed, Some(42)); + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn failed_and_cancelled_terminals_keep_their_meaning() { + let server = Server::start(Some(loaded("h-1"))).await; + server.fake.push(vec![ + Ok(text("x")), + Ok(terminal(2, "engine exploded", false)), + ]); + server.fake.push(vec![Ok(terminal(3, "cancelled", false))]); + let (mut backend, attached) = + blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let attached = attached.unwrap(); + for expected in ["failed", "cancelled"] { + let (b, stream) = { + let attached = attached.clone(); + blocking(backend, move |b| { + b.start_generation(&attached, request(&id())) + }) + .await + }; + backend = b; + let mut stream = stream.unwrap(); + let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) + .await + .unwrap(); + assert!(terminated, "{expected}"); + match (expected, events.last().unwrap()) { + ( + "failed", + GenerationEvent::Terminal(GenerationTerminal::Failed { code, message, .. }), + ) => { + assert_eq!(*code, ErrorCode::ResourceExhausted); + assert_eq!(message, "engine exploded"); + } + ("cancelled", GenerationEvent::Terminal(GenerationTerminal::Cancelled)) => {} + other => panic!("{other:?}"), + } + } + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_stream_that_ends_without_a_terminal_or_with_a_transport_error_has_no_terminal() { + let server = Server::start(Some(loaded("h-1"))).await; + server.fake.push(vec![Ok(text("half"))]); + server + .fake + .push(vec![Ok(text("half")), Err(Status::internal("reset"))]); + // A frame the contract cannot express (unknown finish reason) is not turned into a success. + server.fake.push(vec![Ok(terminal(1, "weird", true))]); + let (mut backend, attached) = + blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let attached = attached.unwrap(); + for case in 0..3 { + let (b, stream) = { + let attached = attached.clone(); + blocking(backend, move |b| { + b.start_generation(&attached, request(&id())) + }) + .await + }; + backend = b; + let mut stream = stream.unwrap(); + let (_, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) + .await + .unwrap(); + assert!( + !terminated, + "case {case}: no terminal event may be invented" + ); + } + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn dropping_the_stream_cancels_the_request_on_the_runtime() { + let server = Server::start(Some(loaded("h-1"))).await; + // The runtime stays silent after one delta; the consumer goes away while the pump waits. + server + .fake + .push(vec![Ok(text("a")), Err(Status::aborted("hang"))]); + let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let attached = attached.unwrap(); + let (_backend, stream) = blocking(backend, move |b| { + b.start_generation(&attached, request(&id())) + }) + .await; + let mut stream = stream.unwrap(); + let first = tokio::task::spawn_blocking(move || { + let first = stream.recv(); + drop(stream); + first + }) + .await + .unwrap(); + assert!(matches!(first, Ok(Some(GenerationEvent::TextDelta { .. })))); + for _ in 0..200 { + if server.fake.cancels.load(Ordering::SeqCst) > 0 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!(server.fake.cancels.load(Ordering::SeqCst), 1); + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn explicit_cancel_addresses_the_active_request_and_unknown_ids_are_refused() { + let server = Server::start(Some(loaded("h-1"))).await; + // The scripted stream never terminates; the request stays active until cancelled. + server + .fake + .push(vec![Ok(text("a")), Err(Status::aborted("hang"))]); + let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let attached = attached.unwrap(); + let request_id = id(); + let sent = request(&request_id); + let (backend, stream) = blocking(backend, move |b| b.start_generation(&attached, sent)).await; + let _stream = stream.unwrap(); + let wanted = request_id.clone(); + let (backend, result) = blocking(backend, move |b| b.cancel(&wanted)).await; + result.unwrap(); + let (_backend, result) = blocking(backend, |b| b.cancel("not-the-request")).await; + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidRequest); + { + let state = server.fake.state.lock().unwrap(); + assert_eq!(state.cancel_requests[0].request_id, request_id); + assert_eq!(state.cancel_requests[0].expected_epoch, state.epoch); + } + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_restarted_runtime_is_refused_before_dispatch_and_reattach_follows_the_new_epoch() { + let server = Server::start(Some(loaded("h-1"))).await; + let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let attached = attached.unwrap(); + let (backend, empty) = + blocking(backend, |b| b.capabilities().supported_models.is_empty()).await; + assert!(!empty, "a healthy attached runtime advertises its model"); + + // The runtime process restarts and loads the same model again: same handle, new epoch. + server.fake.restart(); + server.fake.set_loaded(Some(loaded("h-1"))); + let (backend, result) = blocking(backend, move |b| { + b.start_generation(&attached, request(&id())) + }) + .await; + let error = result.err().expect("a stale epoch must not be dispatched"); + assert_eq!(error.code, ErrorCode::BackendUnavailable); + assert!(error.retryable); + assert!(server.fake.state.lock().unwrap().requests.is_empty()); + + // The health probe reports the model as gone until the caller attaches again. + let (backend, empty) = + blocking(backend, |b| b.capabilities().supported_models.is_empty()).await; + assert!(empty); + let (backend, again) = blocking(backend, |b| b.load(descriptor(), config())).await; + let again = again.unwrap(); + server.fake.push(vec![Ok(terminal(1, "stop", true))]); + let (_backend, stream) = + blocking(backend, move |b| b.start_generation(&again, request(&id()))).await; + assert!(stream.is_ok()); + server.finish().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_unreachable_runtime_is_a_retryable_unavailable_and_unload_is_refused() { + let address = { + let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + probe.local_addr().unwrap() + }; + let backend = GrpcBackend::new(tokio::runtime::Handle::current(), address, TOKEN.into()); + let (backend, result) = blocking(backend, |b| b.load(descriptor(), config())).await; + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::BackendUnavailable); + let (_backend, result) = blocking(backend, |b| b.unload(loaded("h"))).await; + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidRequest); +} diff --git a/desktop-core/Cargo.toml b/desktop-core/Cargo.toml index f26a3c25..73be07df 100644 --- a/desktop-core/Cargo.toml +++ b/desktop-core/Cargo.toml @@ -11,6 +11,7 @@ path = "src/main.rs" [dependencies] leleka-backend-api = { path = "../crates/backend-api" } leleka-runtime = { path = "../crates/leleka-runtime" } +leleka-runtime-client = { path = "../crates/runtime-client" } leleka-sampler-ref = { path = "../crates/sampler-ref" } leleka-serving-policy = { path = "../crates/serving-policy" } minijinja = { version = "=2.24.0", default-features = false, features = ["builtins", "macros", "multi_template", "adjacent_loop_items", "serde", "preserve_order", "loop_controls"] } diff --git a/desktop-core/build.rs b/desktop-core/build.rs index 75dbe4ef..93cb8f8d 100644 --- a/desktop-core/build.rs +++ b/desktop-core/build.rs @@ -3,10 +3,9 @@ fn main() -> Result<(), Box> { config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); tonic_prost_build::configure().compile_with_config( config, - &["proto/node.proto", "proto/runtime.proto"], + &["proto/node.proto"], &["proto"], )?; println!("cargo:rerun-if-changed=proto/node.proto"); - println!("cargo:rerun-if-changed=proto/runtime.proto"); Ok(()) } diff --git a/desktop-core/src/runtime_client.rs b/desktop-core/src/runtime_client.rs index bf122477..faa051a4 100644 --- a/desktop-core/src/runtime_client.rs +++ b/desktop-core/src/runtime_client.rs @@ -1,557 +1,2 @@ -//! 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, - token: String, -} - -impl RuntimeClient { - pub async fn connect(address: SocketAddr, token: String) -> Result { - 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( - &self, - value: T, - limit: usize, - timeout: Duration, - ) -> Result, 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 { - 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 { - 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, 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 { - 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 { - 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 { - 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 { - 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 { - 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, - client: RuntimeClient, - id: String, - epoch: String, - sequence: u64, - terminal: bool, - failed: bool, -} -impl RuntimeGeneration { - pub async fn message(&mut self) -> Result, 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, - } - 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, - ) -> Result, Status> { - Ok(Response::new(self.snapshot())) - } - async fn snapshot( - &self, - _: Request, - ) -> Result, Status> { - Ok(Response::new(self.snapshot())) - } - type WatchStream = Pin> + Send>>; - async fn watch( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn load( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn unload( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn operation( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn cancel( - &self, - request: Request, - ) -> Result, 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> + Send>>; - async fn generate( - &self, - request: Request, - ) -> Result, 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, - ..Default::default() - }) - .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(); - } - } -} +//! The runtime client moved to `leleka-runtime-client` so that `strata-next` can use it too. +pub use leleka_runtime_client::client::{RuntimeClient, RuntimeGeneration, validate_snapshot}; diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index b01712be..897b1a25 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -19,12 +19,15 @@ use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; use uuid::Uuid; -pub mod proto { - tonic::include_proto!("leleka.runtime.v1"); -} -pub const PROTOCOL_VERSION: u32 = 1; -pub const MESSAGE_LIMIT: usize = 2 * 1024 * 1024; -pub const FRAME_LIMIT: usize = 64 * 1024; +pub use leleka_runtime_client::{ + FRAME_LIMIT, MESSAGE_LIMIT, PROTOCOL_VERSION, + convert::{ + config_from_proto, config_to_proto, descriptor_from_proto, descriptor_to_proto, + loaded_to_proto, mode_to_proto, + }, + proto, +}; +pub(crate) use leleka_runtime_client::convert::{literal_loopback, refusal, valid_token}; const MAX_IDS: usize = 256; const EVENT_QUEUE: usize = 16; type WireStream = Pin> + Send>>; @@ -62,30 +65,12 @@ fn lock(mutex: &Mutex) -> Result, Status> { .lock() .map_err(|_| Status::internal("runtime_state_unavailable")) } -pub(crate) fn valid_token(token: &str) -> bool { - (32..=4096).contains(&token.len()) && token.bytes().all(|b| (0x21..=0x7e).contains(&b)) -} -pub(crate) fn literal_loopback(address: SocketAddr) -> Result<(), Status> { - if !address.ip().is_loopback() { - return Err(Status::permission_denied("loopback_required")); - } - Ok(()) -} fn uuid(value: &str) -> Result<(), Status> { if Uuid::parse_str(value).is_err() || value.len() != 36 { return Err(refusal(tonic::Code::InvalidArgument, "invalid_uuid")); } Ok(()) } -/// Only this marker is positive evidence of nonacceptance. Absence is uncertain. -pub(crate) fn refusal(code: tonic::Code, reason: &'static str) -> Status { - let mut status = Status::new(code, reason); - status.metadata_mut().insert( - "x-leleka-accepted", - "false".parse().expect("literal metadata"), - ); - status -} fn backend_status(error: &api::BackendError) -> Status { let (code, reason) = match error.code { api::ErrorCode::InvalidRequest => (tonic::Code::InvalidArgument, "invalid_generation"), @@ -921,137 +906,6 @@ fn pump( } } -pub fn descriptor_to_proto(value: &api::ModelDescriptor) -> proto::ModelDescriptor { - proto::ModelDescriptor { - family: value.family.clone(), - architecture: value.architecture.clone(), - artifact_digest: value.artifact_digest.clone(), - weight_format: value.weight_format.clone(), - } -} -pub fn descriptor_from_proto( - value: &proto::ModelDescriptor, -) -> Result { - let model = api::ModelDescriptor { - family: value.family.clone(), - architecture: value.architecture.clone(), - artifact_digest: value.artifact_digest.clone(), - weight_format: value.weight_format.clone(), - }; - if [ - model.family.len(), - model.architecture.len(), - model.weight_format.len(), - ] - .into_iter() - .any(|n| n > 128) - || model.validate().is_err() - { - return Err(refusal( - tonic::Code::InvalidArgument, - "invalid_model_descriptor", - )); - } - Ok(model) -} -pub fn mode_to_proto(mode: &api::InferenceMode) -> proto::InferenceMode { - use proto::inference_mode::Selection; - let selection = match mode { - api::InferenceMode::Native => Selection::Native(proto::NativeMode {}), - api::InferenceMode::ExperimentalKarPle { profile_id } => { - Selection::KarPle(proto::KarPleMode { - profile_id: profile_id.clone(), - }) - } - api::InferenceMode::ExperimentalMtp { profile_id } => Selection::Mtp(proto::MtpMode { - profile_id: profile_id.clone(), - }), - api::InferenceMode::ExperimentalKarExperts(e) => { - Selection::KarExperts(proto::KarExpertsMode { - bundle_directory: e.bundle_directory.clone(), - archive_file: e.archive_file.clone(), - binding_file: e.binding_file.clone(), - provenance_file: e.provenance_file.clone(), - levels: u32::from(e.levels), - cache_mib: e.cache_mib, - prefill_mode: match e.prefill_mode { - api::KarPrefillMode::DecodeOnly => 1, - api::KarPrefillMode::AllRoutedBatched => 2, - }, - }) - } - }; - proto::InferenceMode { - selection: Some(selection), - } -} -pub fn config_to_proto(config: &api::RuntimeConfig) -> proto::LoadConfig { - proto::LoadConfig { - version: u32::from(config.load_config_version), - mode: Some(mode_to_proto(&config.inference_mode)), - gpu_memory_limit_bytes: config.gpu_memory_limit_bytes, - allow_experimental: config.allow_experimental, - } -} -pub fn config_from_proto(config: &proto::LoadConfig) -> Result { - use proto::inference_mode::Selection; - let mode = match config.mode.as_ref().and_then(|m| m.selection.as_ref()) { - Some(Selection::Native(_)) => api::InferenceMode::Native, - Some(Selection::KarPle(p)) => api::InferenceMode::ExperimentalKarPle { - profile_id: p.profile_id.clone(), - }, - Some(Selection::Mtp(p)) => api::InferenceMode::ExperimentalMtp { - profile_id: p.profile_id.clone(), - }, - Some(Selection::KarExperts(e)) => { - api::InferenceMode::ExperimentalKarExperts(api::KarExpertLoad { - bundle_directory: e.bundle_directory.clone(), - archive_file: e.archive_file.clone(), - binding_file: e.binding_file.clone(), - provenance_file: e.provenance_file.clone(), - levels: u8::try_from(e.levels) - .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_expert_levels"))?, - cache_mib: e.cache_mib, - prefill_mode: match e.prefill_mode { - 1 => api::KarPrefillMode::DecodeOnly, - 2 => api::KarPrefillMode::AllRoutedBatched, - _ => { - return Err(refusal( - tonic::Code::InvalidArgument, - "invalid_expert_prefill", - )); - } - }, - }) - } - None => { - return Err(refusal( - tonic::Code::InvalidArgument, - "missing_inference_mode", - )); - } - }; - let value = api::RuntimeConfig { - load_config_version: u16::try_from(config.version) - .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_version"))?, - inference_mode: mode, - gpu_memory_limit_bytes: config.gpu_memory_limit_bytes, - allow_experimental: config.allow_experimental, - }; - value - .validate() - .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_config"))?; - Ok(value) -} -pub fn loaded_to_proto(value: &api::LoadedModel) -> proto::LoadedModel { - proto::LoadedModel { - handle: value.handle.clone(), - descriptor: Some(descriptor_to_proto(&value.descriptor)), - load_config_version: u32::from(value.load_config_version), - effective_mode: Some(mode_to_proto(&value.effective_mode)), - mode_identity_digest: value.mode_identity_digest.clone(), - } -} fn capabilities_to_proto(value: &api::BackendCapabilities) -> proto::Capabilities { proto::Capabilities { models: value