Files
leleka/crates/runtime-client/src/client.rs
T
Pavlo Ratushnyi f78b89757c STRA-338 S12a: inline unit-test modules move to sibling tests.rs files in 118 oversize files
scripts/dev/extract_tests.py moves a trailing cfg(test) mod tests block into foo/tests.rs for 118 files of leleka-runtime, cuda-driver, control-plane, gateway-text, deploy and nine smaller crates (31,000 lines), leaving production code and test ids untouched; 22 files that are themselves loaded through a path attribute carry an explicit path to their tests file. Not touched: the files the kar-off-ab branch edits (backend.rs, backend_original_serve.rs, backend_original_serve_replay.rs, qwen4exp_resident_expert_source.rs and seven deploy files).

Verified: cargo check --all-targets for the whole workspace on x86_64 Linux and on the Windows host; the 2429 library unit-test ids of the workspace are identical before and after (Linux listing diff empty); the loadable sections of leleka-inference, leleka-daemon, leleka-cli and strata-next are byte-identical between a release build before and after (scripts/dev/elf-sections-equal.sh), so the shipped code is the same. The architecture ratchets exclude tests.rs from the path-include count; the baseline drops from 329 to 311 oversize files and from 302,000 to 273,600 lines.
2026-11-05 15:00:09 +01:00

327 lines
12 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)
}
/// Change the settings of the loaded model (JSON document, `leleka_runtime::serve_tuning`); the engine reopens its serve stack,
/// which takes tens of seconds, so the deadline is generous.
pub async fn reconfigure(
&mut self,
command: proto::ReconfigureRequest,
) -> Result<proto::ReconfigureReply, Status> {
let epoch = command.expected_epoch.clone();
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(1800))?;
let value = self.client.reconfigure(request).await?.into_inner();
if value.epoch != epoch {
return Err(Status::data_loss("invalid_reconfigure_reply"));
}
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;