Files
leleka/crates/runtime-client/src/client.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 c9aad38caa 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 <noreply@anthropic.com>
2026-10-16 02:42:11 +02:00

558 lines
20 KiB
Rust

//! 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<Channel>,
token: String,
}
impl RuntimeClient {
pub async fn connect(address: SocketAddr, token: String) -> Result<Self, Status> {
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<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 = 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<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(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<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,
..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();
}
}
}