Files
leleka/crates/runtime-client/src/backend.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 60b48d8225 runtime reconfiguration: reopen the serve stack with new context/cache/resource settings without reloading the model
serve_tuning (settings document, validation, effective settings), Command::Reconfigure in the Original serve loop with rollback,
Backend::reconfigure, gRPC Runtime.Reconfigure, POST /v1/reconfigure, telemetry.settings; tests for each layer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:01:53 +01:00

406 lines
16 KiB
Rust

//! [`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<RuntimeClient>,
attached: Option<Attached>,
/// Shared with the pump task so `cancel` can address the running request.
active: Arc<Mutex<Option<ActiveRequest>>>,
/// The prefix-cache summary of the last snapshot a `capabilities` probe read (no extra connection per query).
prefix_summary: Mutex<Option<String>>,
/// The runtime's memory-governor report from the last probe (`Backend::memory_report`).
memory_report: Mutex<Option<String>>,
/// The runtime's telemetry document from the last probe (`Backend::telemetry_report`).
telemetry_report: Mutex<Option<String>>,
}
#[derive(Clone)]
struct Attached {
epoch: String,
handle: String,
}
#[derive(Clone)]
struct ActiveRequest {
id: String,
epoch: String,
}
fn error(code: api::ErrorCode, message: impl Into<String>, 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)),
prefix_summary: Mutex::new(None),
memory_report: Mutex::new(None),
telemetry_report: 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<proto::Snapshot, api::BackendError> {
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()
});
// the probe is one snapshot read per health tick: keep its prefix-cache summary for `prefix_cache_summary`
if let Ok(mut cell) = self.memory_report.lock() {
// memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report
*cell = probe.as_ref().filter(|snapshot| !snapshot.memory_json.is_empty()).map(|snapshot| snapshot.memory_json.clone());
}
if let Ok(mut cell) = self.telemetry_report.lock() {
*cell = probe.as_ref().filter(|snapshot| !snapshot.telemetry_json.is_empty()).map(|snapshot| snapshot.telemetry_json.clone());
}
if let Ok(mut cell) = self.prefix_summary.lock() {
*cell = probe
.as_ref()
.filter(|snapshot| {
snapshot.model_ready
&& !snapshot.prefix_cache_json.is_empty()
&& attached.as_ref().is_some_and(|a| a.epoch == snapshot.epoch)
})
.map(|snapshot| snapshot.prefix_cache_json.clone());
}
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(),
}
}
/// The runtime's prefix-cache summary as of the last `capabilities` probe (one health tick old at most); `None` when the
/// runtime is unreachable, restarted since the attach, or has no such cache.
fn prefix_cache_summary(&self) -> Option<String> {
self.prefix_summary.lock().ok().and_then(|cell| cell.clone())
}
/// The runtime's memory-governor report as of the last `capabilities` probe; `None` when unreachable or it has none.
fn memory_report(&self) -> Option<String> {
self.memory_report.lock().ok().and_then(|cell| cell.clone())
}
/// The runtime's telemetry document as of the last `capabilities` probe; `None` when unreachable or it has none.
fn telemetry_report(&self) -> Option<String> {
self.telemetry_report.lock().ok().and_then(|cell| cell.clone())
}
fn load(
&mut self,
model: api::ModelDescriptor,
config: api::RuntimeConfig,
) -> Result<api::LoadedModel, api::BackendError> {
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<api::GenerationStream, api::BackendError> {
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 reconfigure(&mut self, settings_json: &str) -> Result<String, api::BackendError> {
let Some(attached) = self.attached.clone() else {
return Err(error(api::ErrorCode::BackendUnavailable, "no model is attached", true));
};
let Some(client) = self.client.as_mut() else {
return Err(error(api::ErrorCode::BackendUnavailable, "not connected", true));
};
let reply = self
.runtime
.block_on(client.reconfigure(proto::ReconfigureRequest {
operation_id: String::new(),
expected_epoch: attached.epoch,
settings_json: settings_json.to_owned(),
}))
.map_err(|status| from_status(&status))?;
if reply.ok {
return Ok(reply.effective_json);
}
let code = match reply.error_code.as_str() {
"invalid" => api::ErrorCode::InvalidRequest,
"unsupported" => api::ErrorCode::UnsupportedModel,
"exhausted" => api::ErrorCode::ResourceExhausted,
"unavailable" => api::ErrorCode::BackendUnavailable,
_ => api::ErrorCode::Internal,
};
Err(api::BackendError { code, message: reply.error, retryable: reply.retryable })
}
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<Mutex<Option<ActiveRequest>>>,
) {
let clear = |active: &Arc<Mutex<Option<ActiveRequest>>>| {
*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);
}