Files
leleka/desktop-core/src/runtime_rpc.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

1686 lines
64 KiB
Rust

//! Bounded, authenticated inference-process transport. CUDA owners stay in Backend.
use futures_util::Stream;
use leleka_backend_api as api;
use prost::Message;
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use subtle::ConstantTimeEq;
use tokio::{
net::TcpListener,
sync::{OwnedSemaphorePermit, Semaphore, broadcast, mpsc},
};
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status};
use uuid::Uuid;
pub(crate) use leleka_runtime_client::convert::{literal_loopback, refusal, valid_token};
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,
};
const MAX_IDS: usize = 256;
const EVENT_QUEUE: usize = 16;
type WireStream<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send>>;
#[derive(Clone)]
pub struct RuntimeServer {
inner: Arc<Inner>,
}
struct Inner {
backend: Mutex<Box<dyn api::Backend>>,
token: String,
state: Mutex<State>,
changes: broadcast::Sender<proto::Snapshot>,
controls: Arc<Semaphore>,
watchers: Arc<Semaphore>,
}
struct State {
epoch: String,
sequence: u64,
loaded: Option<api::LoadedModel>,
capabilities: api::BackendCapabilities,
operations: HashMap<String, Operation>,
requests: api::RecentIds,
lifecycle_busy: bool,
active: Option<String>,
stopping: bool,
/// The backend's prefix-cache summary as of the last observation (`Backend::prefix_cache_summary`).
prefix_cache_json: String,
/// The backend's memory-governor report as of the last observation (`Backend::memory_report`).
memory_json: String,
/// The backend's telemetry document as of the last observation (`Backend::telemetry_report`).
telemetry_json: String,
}
struct Operation {
digest: [u8; 32],
result: proto::OperationResult,
}
fn lock<T>(mutex: &Mutex<T>) -> Result<std::sync::MutexGuard<'_, T>, Status> {
mutex
.lock()
.map_err(|_| Status::internal("runtime_state_unavailable"))
}
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(())
}
fn backend_status(error: &api::BackendError) -> Status {
let (code, reason) = match error.code {
api::ErrorCode::InvalidRequest => (tonic::Code::InvalidArgument, "invalid_generation"),
api::ErrorCode::UnsupportedModel => (tonic::Code::FailedPrecondition, "unsupported_model"),
api::ErrorCode::ResourceExhausted => (tonic::Code::ResourceExhausted, "runtime_capacity"),
api::ErrorCode::BackendUnavailable => (tonic::Code::Unavailable, "backend_unavailable"),
api::ErrorCode::Internal => (tonic::Code::Internal, "backend_failed"),
};
// Unavailable/Internal can be a delivered-command acknowledgement failure.
// Only the facade's validation/capacity errors prove nonacceptance.
if matches!(
error.code,
api::ErrorCode::BackendUnavailable | api::ErrorCode::Internal
) {
Status::new(code, reason)
} else {
refusal(code, reason)
}
}
fn bounded<T: Message>(value: &T, limit: usize) -> Result<(), Status> {
if value.encoded_len() > limit {
return Err(refusal(tonic::Code::ResourceExhausted, "message_limit"));
}
Ok(())
}
fn operation_digest<T: Message>(kind: &[u8], value: &T) -> [u8; 32] {
let mut hash = Sha256::new();
hash.update(kind);
hash.update(value.encode_to_vec());
hash.finalize().into()
}
fn fence(state: &State, epoch: &str) -> Result<(), Status> {
if epoch != state.epoch {
return Err(refusal(tonic::Code::FailedPrecondition, "epoch_mismatch"));
}
Ok(())
}
fn snapshot(state: &State) -> proto::Snapshot {
proto::Snapshot {
protocol_version: PROTOCOL_VERSION,
backend_api_version: u32::from(api::BACKEND_API_VERSION),
epoch: state.epoch.clone(),
sequence: state.sequence,
full_snapshot: true,
transport_ready: !state.stopping,
model_ready: state
.loaded
.as_ref()
.is_some_and(|m| state.capabilities.supports(&m.descriptor))
&& !state.stopping,
loaded: if state.stopping {
None
} else {
state.loaded.as_ref().map(loaded_to_proto)
},
capabilities: Some(if state.stopping {
proto::Capabilities::default()
} else {
capabilities_to_proto(&state.capabilities)
}),
active_request_id: state.active.clone().unwrap_or_default(),
prefix_cache_json: if state.stopping { String::new() } else { state.prefix_cache_json.clone() },
memory_json: if state.stopping { String::new() } else { state.memory_json.clone() },
telemetry_json: if state.stopping { String::new() } else { state.telemetry_json.clone() },
}
}
fn publish(inner: &Inner, state: &mut State) {
// Saturation closes future mutations rather than wrapping the cursor.
state.sequence = state.sequence.saturating_add(1);
let _ = inner.changes.send(snapshot(state));
}
fn current_snapshot(inner: &Inner) -> Result<proto::Snapshot, Status> {
refresh_capabilities(inner);
let state = lock(&inner.state)?;
Ok(snapshot(&state))
}
impl RuntimeServer {
pub fn new(backend: Box<dyn api::Backend>, token: String) -> Result<Self, Status> {
if !valid_token(&token) {
return Err(Status::invalid_argument("invalid_runtime_credential"));
}
if !backend.identity().supports_current_api() {
return Err(Status::failed_precondition("backend_api_mismatch"));
}
let (changes, _) = broadcast::channel(EVENT_QUEUE);
Ok(Self {
inner: Arc::new(Inner {
backend: Mutex::new(backend),
token,
state: Mutex::new(State {
epoch: Uuid::new_v4().to_string(),
sequence: 1,
loaded: None,
capabilities: api::BackendCapabilities::default(),
operations: HashMap::new(),
requests: api::RecentIds::default(),
lifecycle_busy: false,
active: None,
stopping: false,
prefix_cache_json: String::new(),
memory_json: String::new(),
telemetry_json: String::new(),
}),
changes,
controls: Arc::new(Semaphore::new(16)),
watchers: Arc::new(Semaphore::new(16)),
}),
})
}
pub async fn serve<F>(
self,
listener: TcpListener,
shutdown: F,
) -> Result<(), Box<dyn std::error::Error>>
where
F: std::future::Future<Output = ()> + Send + 'static,
{
literal_loopback(listener.local_addr()?)?;
let shutdown_inner = self.inner.clone();
let shutdown = async move {
shutdown.await;
let active = if let Ok(mut state) = shutdown_inner.state.lock() {
state.stopping = true;
publish(&shutdown_inner, &mut state);
state.active.clone()
} else {
None
};
if let Some(id) = active {
cancel_detached(shutdown_inner, id);
}
};
tonic::transport::Server::builder()
.max_concurrent_streams(64)
.add_service(
proto::runtime_server::RuntimeServer::new(self)
.max_decoding_message_size(MESSAGE_LIMIT)
.max_encoding_message_size(MESSAGE_LIMIT),
)
// `serve_with_incoming*` ignores the builder's `tcp_nodelay`, and Nagle's algorithm plus the client's delayed ACK
// holds every small response frame (the accept of a generation, each text delta, the terminal) for up to ~40 ms
// on loopback: the sockets are accepted here, so set TCP_NODELAY here.
.serve_with_incoming_shutdown(
tonic::transport::server::TcpIncoming::from(listener).with_nodelay(Some(true)),
shutdown,
)
.await?;
Ok(())
}
fn authorize<T: Message>(
&self,
request: &Request<T>,
limit: usize,
) -> Result<OwnedSemaphorePermit, Status> {
if request
.remote_addr()
.is_none_or(|address| !address.ip().is_loopback())
{
return Err(Status::permission_denied("loopback_required"));
}
let supplied = request
.metadata()
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.unwrap_or("");
if !bool::from(self.inner.token.as_bytes().ct_eq(supplied.as_bytes())) {
return Err(Status::unauthenticated("unauthorized"));
}
bounded(request.get_ref(), limit)?;
self.inner
.controls
.clone()
.try_acquire_owned()
.map_err(|_| refusal(tonic::Code::ResourceExhausted, "control_capacity"))
}
fn reserve(
&self,
id: &str,
epoch: &str,
digest: [u8; 32],
) -> Result<(proto::OperationResult, bool), Status> {
uuid(id)?;
let mut state = lock(&self.inner.state)?;
fence(&state, epoch)?;
if let Some(old) = state.operations.get(id) {
if old.digest != digest {
return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict"));
}
return Ok((old.result.clone(), false));
}
if state.operations.len() >= MAX_IDS
|| state.lifecycle_busy
|| state.active.is_some()
|| state.sequence == u64::MAX
|| state.stopping
{
return Err(refusal(
tonic::Code::ResourceExhausted,
"lifecycle_capacity",
));
}
let result = proto::OperationResult {
operation_id: id.to_owned(),
epoch: state.epoch.clone(),
state: proto::operation_result::State::Accepted as i32,
reason: "accepted".into(),
loaded: None,
};
state.operations.insert(
id.to_owned(),
Operation {
digest,
result: result.clone(),
},
);
state.lifecycle_busy = true;
publish(&self.inner, &mut state);
Ok((result, true))
}
}
#[tonic::async_trait]
impl proto::runtime_server::Runtime for RuntimeServer {
async fn handshake(
&self,
request: Request<proto::Hello>,
) -> Result<Response<proto::Snapshot>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let hello = request.into_inner();
if hello.protocol_version != PROTOCOL_VERSION
|| hello.backend_api_version != u32::from(api::BACKEND_API_VERSION)
{
return Err(refusal(
tonic::Code::FailedPrecondition,
"protocol_version_mismatch",
));
}
Ok(Response::new(current_snapshot(&self.inner)?))
}
async fn snapshot(
&self,
request: Request<proto::Empty>,
) -> Result<Response<proto::Snapshot>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
Ok(Response::new(current_snapshot(&self.inner)?))
}
type WatchStream = WireStream<proto::Snapshot>;
async fn watch(
&self,
request: Request<proto::Cursor>,
) -> Result<Response<Self::WatchStream>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let watch_permit = self
.inner
.watchers
.clone()
.try_acquire_owned()
.map_err(|_| Status::resource_exhausted("watch_capacity"))?;
let mut changes = self.inner.changes.subscribe();
let first = current_snapshot(&self.inner)?;
let inner = self.inner.clone();
// Every notification is a full bounded observation, including cursor
// gaps/replacement epochs. It never starts or replays inference.
let stream = async_stream::try_stream! {
let _watch_permit = watch_permit;
let stopped = !first.transport_ready;
yield first;
if stopped { return; }
loop {
match changes.recv().await {
Ok(next) => {
let stopped = !next.transport_ready;
yield next;
if stopped { break; }
},
Err(broadcast::error::RecvError::Lagged(_)) => {
let next = current_snapshot(&inner)?;
yield next;
}
Err(broadcast::error::RecvError::Closed) => break,
}
}
};
Ok(Response::new(Box::pin(stream)))
}
async fn load(
&self,
request: Request<proto::LoadRequest>,
) -> Result<Response<proto::OperationResult>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let command = request.into_inner();
let model = descriptor_from_proto(
command
.model
.as_ref()
.ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_model"))?,
)?;
let config = config_from_proto(
command
.config
.as_ref()
.ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_config"))?,
)?;
let mut canonical = command.clone();
canonical.operation_id.clear();
let digest = operation_digest(b"load\0", &canonical);
let (accepted, execute) =
self.reserve(&command.operation_id, &command.expected_epoch, digest)?;
if execute {
let inner = self.inner.clone();
tokio::task::spawn_blocking(move || {
let mut guard = LifecycleGuard {
inner: inner.clone(),
operation_id: command.operation_id.clone(),
armed: true,
};
let result = (|| {
let mut backend = lock(&inner.backend)?;
let loaded = backend
.load(model.clone(), config.clone())
.map_err(|e| backend_status(&e))?;
loaded
.validate_for_load(&model, &config)
.map_err(|_| Status::internal("invalid_backend_load_result"))?;
Ok::<_, Status>((loaded, backend.capabilities()))
})();
if let Ok(mut state) = inner.state.lock() {
let (phase, reason, loaded) = match result {
Ok((loaded, capabilities)) => {
state.loaded = Some(loaded.clone());
state.capabilities = capabilities;
(
proto::operation_result::State::Completed,
"completed",
Some(loaded_to_proto(&loaded)),
)
}
Err(status)
if status
.metadata()
.get("x-leleka-accepted")
.and_then(|v| v.to_str().ok())
== Some("false") =>
{
(proto::operation_result::State::Failed, "load_failed", None)
}
Err(_) => {
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
(
proto::operation_result::State::Indeterminate,
"load_uncertain",
None,
)
}
};
if let Some(operation) = state.operations.get_mut(&command.operation_id) {
operation.result.state = phase as i32;
operation.result.reason = reason.into();
operation.result.loaded = loaded;
}
state.lifecycle_busy = false;
guard.armed = false;
publish(&inner, &mut state);
}
});
}
Ok(Response::new(accepted))
}
async fn unload(
&self,
request: Request<proto::UnloadRequest>,
) -> Result<Response<proto::OperationResult>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let command = request.into_inner();
let mut canonical = command.clone();
canonical.operation_id.clear();
let digest = operation_digest(b"unload\0", &canonical);
let loaded = {
let state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
// Completed duplicates are resolved even when the model was unloaded.
if let Some(old) = state.operations.get(&command.operation_id) {
if old.digest != digest {
return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict"));
}
return Ok(Response::new(old.result.clone()));
}
state
.loaded
.as_ref()
.filter(|m| m.handle == command.handle)
.cloned()
.ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))?
};
let (accepted, execute) =
self.reserve(&command.operation_id, &command.expected_epoch, digest)?;
if execute {
let inner = self.inner.clone();
tokio::task::spawn_blocking(move || {
let mut guard = LifecycleGuard {
inner: inner.clone(),
operation_id: command.operation_id.clone(),
armed: true,
};
let result = lock(&inner.backend)
.and_then(|mut b| b.unload(loaded).map_err(|e| backend_status(&e)));
if let Ok(mut state) = inner.state.lock() {
// Failed/uncertain unload also closes model admission.
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
if let Some(operation) = state.operations.get_mut(&command.operation_id) {
operation.result.state = if result.is_ok() {
proto::operation_result::State::Completed
} else {
proto::operation_result::State::Indeterminate
} as i32;
operation.result.reason = if result.is_ok() {
"completed"
} else {
"unload_uncertain"
}
.into();
}
state.lifecycle_busy = false;
guard.armed = false;
publish(&inner, &mut state);
}
});
}
Ok(Response::new(accepted))
}
async fn operation(
&self,
request: Request<proto::OperationQuery>,
) -> Result<Response<proto::OperationResult>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let query = request.into_inner();
uuid(&query.operation_id)?;
let state = lock(&self.inner.state)?;
if query.expected_epoch != state.epoch
|| !state.operations.contains_key(&query.operation_id)
{
return Ok(Response::new(proto::OperationResult {
operation_id: query.operation_id,
epoch: state.epoch.clone(),
state: proto::operation_result::State::Indeterminate as i32,
reason: "unknown_operation".into(),
loaded: None,
}));
}
Ok(Response::new(
state.operations[&query.operation_id].result.clone(),
))
}
type GenerateStream = WireStream<proto::GenerationFrame>;
async fn generate(
&self,
request: Request<proto::GenerateRequest>,
) -> Result<Response<Self::GenerateStream>, Status> {
let _permit = self.authorize(&request, MESSAGE_LIMIT)?;
let command = request.into_inner();
uuid(&command.request_id)?;
if command.prompt.len() > 1024 * 1024
|| command.max_output_tokens == 0
|| command.max_output_tokens > api::MAX_OUTPUT_TOKENS
{
return Err(refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
));
}
// Sampling is served by the backend (Original sampler chain); the Original's documented
// ranges are enforced here too, so an out-of-contract request never reaches a worker.
let sampling = crate::runtime_sampling::to_backend(&command).map_err(|()| {
refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
)
})?;
let loaded = {
let mut state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
if state.requests.contains(&command.request_id) {
// An old ID may have accepted/visible effects. Its rejection
// cannot authorize a retry of that identity on another member,
// including when this member's registry or slot is full.
return Err(Status::already_exists("generation_not_replayed"));
}
if state.active.is_some()
|| state.lifecycle_busy
|| state.stopping
|| state.sequence == u64::MAX
{
return Err(refusal(
tonic::Code::ResourceExhausted,
"generation_capacity",
));
}
let loaded = state
.loaded
.as_ref()
.filter(|m| m.handle == command.handle)
.cloned()
.ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))?;
if !state.capabilities.supports(&loaded.descriptor) {
return Err(refusal(tonic::Code::FailedPrecondition, "model_not_ready"));
}
state.requests.insert(&command.request_id);
state.active = Some(command.request_id.clone());
publish(&self.inner, &mut state);
loaded
};
let inner = self.inner.clone();
let backend_request = api::GenerationRequest {
request_id: command.request_id.clone(),
prompt: command.prompt,
max_output_tokens: command.max_output_tokens,
temperature_milli: command.temperature_milli,
sampling,
};
let mut acceptance_guard = AcceptanceGuard {
inner: self.inner.clone(),
id: command.request_id.clone(),
armed: true,
};
let started = tokio::task::spawn_blocking(move || {
lock(&inner.backend)?
.start_generation(&loaded, backend_request)
.map_err(|e| backend_status(&e))
})
.await;
let stream = match started {
Ok(Ok(stream)) => stream,
other => {
let status = match other {
Ok(Err(status)) => status,
_ => Status::internal("generation_acceptance_uncertain"),
};
if status
.metadata()
.get("x-leleka-accepted")
.and_then(|v| v.to_str().ok())
== Some("false")
{
acceptance_guard.armed = false;
// This reservation is proved to have produced no accepted
// effects. Release only it, so the daemon's bounded retry
// may reuse the same identity. Uncertain/accepted IDs stay.
let mut state = lock(&self.inner.state)?;
state.requests.remove(&command.request_id);
if state.active.as_deref() == Some(&command.request_id) {
state.active = None;
}
publish(&self.inner, &mut state);
} else {
close_admission(&self.inner);
}
return Err(status);
}
};
let (sender, receiver) = mpsc::channel(EVENT_QUEUE);
let inner = self.inner.clone();
let id = command.request_id.clone();
let epoch = command.expected_epoch.clone();
tokio::task::spawn_blocking(move || pump(inner, id, epoch, stream, sender));
acceptance_guard.armed = false;
let guarded = GenerationResponse {
receiver: ReceiverStream::new(receiver),
inner: self.inner.clone(),
id: command.request_id,
terminal: false,
};
let mut response = Response::new(Box::pin(guarded) as Self::GenerateStream);
response.metadata_mut().insert(
"x-leleka-accepted",
"true".parse().expect("literal metadata"),
);
Ok(response)
}
async fn reconfigure(
&self,
request: Request<proto::ReconfigureRequest>,
) -> Result<Response<proto::ReconfigureReply>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let command = request.into_inner();
if command.settings_json.is_empty() || command.settings_json.len() > 4096 {
return Err(refusal(tonic::Code::InvalidArgument, "settings_size"));
}
{
let state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
if state.loaded.is_none() {
return Err(refusal(tonic::Code::FailedPrecondition, "no_model_loaded"));
}
if state.active.is_some() || state.lifecycle_busy {
return Err(refusal(tonic::Code::FailedPrecondition, "runtime_busy"));
}
}
let inner = self.inner.clone();
let settings = command.settings_json.clone();
let outcome = tokio::task::spawn_blocking(move || {
let mut backend = lock(&inner.backend)?;
Ok::<_, Status>(backend.reconfigure(&settings))
})
.await
.map_err(|_| Status::internal("reconfigure_uncertain"))??;
let reply = match outcome {
Ok(effective) => proto::ReconfigureReply {
operation_id: command.operation_id,
epoch: command.expected_epoch,
ok: true,
effective_json: effective,
..Default::default()
},
Err(error) => proto::ReconfigureReply {
operation_id: command.operation_id,
epoch: command.expected_epoch,
ok: false,
error_code: match error.code {
api::ErrorCode::InvalidRequest => "invalid",
api::ErrorCode::UnsupportedModel => "unsupported",
api::ErrorCode::ResourceExhausted => "exhausted",
api::ErrorCode::BackendUnavailable => "unavailable",
api::ErrorCode::Internal => "internal",
}
.to_owned(),
error: error.message,
retryable: error.retryable,
..Default::default()
},
};
Ok(Response::new(reply))
}
async fn cancel(
&self,
request: Request<proto::CancelRequest>,
) -> Result<Response<proto::CancelAck>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let command = request.into_inner();
uuid(&command.request_id)?;
{
let state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
if !state.requests.contains(&command.request_id) {
return Err(refusal(tonic::Code::NotFound, "unknown_request"));
}
if state.active.as_deref() != Some(&command.request_id) {
return Ok(Response::new(proto::CancelAck {
request_id: command.request_id,
epoch: command.expected_epoch,
acknowledged: true,
}));
}
}
let inner = self.inner.clone();
let id = command.request_id.clone();
let outcome = tokio::task::spawn_blocking(move || {
let cancelled = lock(&inner.backend)?
.cancel(&id)
.map_err(|_| Status::internal("cancel_uncertain"));
// The request may have reached its terminal between the active
// check and the backend call; a finished request is already
// cancelled as far as the caller can observe.
if cancelled.is_err() && lock(&inner.state)?.active.as_deref() != Some(id.as_str()) {
return Ok(());
}
cancelled
})
.await
.map_err(|_| Status::internal("cancel_uncertain"))?;
outcome?;
Ok(Response::new(proto::CancelAck {
request_id: command.request_id,
epoch: command.expected_epoch,
acknowledged: true,
}))
}
}
fn clear_active(inner: &Inner, id: &str) {
if let Ok(mut state) = inner.state.lock()
&& state.active.as_deref() == Some(id)
{
state.active = None;
publish(inner, &mut state);
}
}
/// A load/unload worker that panics must not leave the lifecycle gate shut
/// with a stale "accepted" operation: it ends as indeterminate and model
/// admission closes, exactly like any other uncertain lifecycle outcome.
struct LifecycleGuard {
inner: Arc<Inner>,
operation_id: String,
/// Disarmed under the same state lock that publishes the operation's own
/// completion, so a worker that finished can never touch a later operation.
armed: bool,
}
impl Drop for LifecycleGuard {
fn drop(&mut self) {
if !self.armed {
return;
}
if let Ok(mut state) = self.inner.state.lock()
&& let Some(operation) = state.operations.get_mut(&self.operation_id)
&& operation.result.state == proto::operation_result::State::Accepted as i32
{
// Only this worker's own, still-unresolved operation is ended.
operation.result.state = proto::operation_result::State::Indeterminate as i32;
operation.result.reason = "lifecycle_worker_failed".into();
state.lifecycle_busy = false;
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
publish(&self.inner, &mut state);
}
}
}
fn close_admission(inner: &Inner) {
if let Ok(mut state) = inner.state.lock() {
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
publish(inner, &mut state);
}
}
fn refresh_capabilities(inner: &Inner) {
// Observations must not wait behind a load/acceptance acknowledgement.
let (capabilities, summary, memory, telemetry) = match inner.backend.try_lock() {
Ok(backend) => (backend.capabilities(), backend.prefix_cache_summary(), backend.memory_report(), backend.telemetry_report()),
Err(std::sync::TryLockError::WouldBlock) => return,
Err(std::sync::TryLockError::Poisoned(_)) => (api::BackendCapabilities::default(), None, None, None),
};
if let Ok(mut state) = inner.state.lock() {
// the summary changes with every request; watchers are told about it only through a snapshot they ask for
state.prefix_cache_json = summary.unwrap_or_default();
state.memory_json = memory.unwrap_or_default();
state.telemetry_json = telemetry.unwrap_or_default();
let capabilities = if state.loaded.is_some() {
capabilities
} else {
api::BackendCapabilities::default()
};
if state.capabilities != capabilities {
state.capabilities = capabilities;
publish(inner, &mut state);
}
}
}
fn cancel_detached(inner: Arc<Inner>, id: String) {
tokio::task::spawn_blocking(move || {
if let Ok(mut backend) = inner.backend.lock() {
let _ = backend.cancel(&id);
}
});
}
struct AcceptanceGuard {
inner: Arc<Inner>,
id: String,
armed: bool,
}
impl Drop for AcceptanceGuard {
fn drop(&mut self) {
if self.armed {
// The caller lost observation before acceptance was resolved. Keep
// the request fence and withdraw readiness; cancellation alone is
// not proof that the device completed or that the slot is reusable.
close_admission(&self.inner);
cancel_detached(self.inner.clone(), self.id.clone());
}
}
}
fn cancel_and_drain(inner: &Arc<Inner>, id: &str, source: &mut api::GenerationStream) {
if let Ok(mut backend) = inner.backend.lock() {
let _ = backend.cancel(id);
}
// Only a real terminal permits slot reuse. Missing/uncertain completion
// retains admission closed; no EOF is interpreted as device completion.
while let Ok(Some(event)) = source.recv() {
if matches!(event, api::GenerationEvent::Terminal(_)) {
refresh_capabilities(inner);
clear_active(inner, id);
break;
}
}
}
/// Releases the generation slot only for a terminal the backend really sent.
/// A synthesized terminal (the backend channel ended without one) gives no
/// completion proof, so the slot stays owned and model admission closes.
fn settle(
inner: &Arc<Inner>,
id: &str,
source: &mut api::GenerationStream,
terminal: bool,
confirmed: bool,
) {
if terminal && confirmed {
refresh_capabilities(inner);
clear_active(inner, id);
} else if terminal {
close_admission(inner);
} else {
cancel_and_drain(inner, id, source);
}
}
struct GenerationResponse {
receiver: ReceiverStream<Result<proto::GenerationFrame, Status>>,
inner: Arc<Inner>,
id: String,
terminal: bool,
}
impl Stream for GenerationResponse {
type Item = Result<proto::GenerationFrame, Status>;
fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let result = Pin::new(&mut self.receiver).poll_next(context);
if let Poll::Ready(Some(Ok(frame))) = &result
&& matches!(
frame.payload,
Some(proto::generation_frame::Payload::Terminal(_))
)
{
self.terminal = true;
}
result
}
}
impl Drop for GenerationResponse {
fn drop(&mut self) {
if !self.terminal {
cancel_detached(self.inner.clone(), self.id.clone());
}
}
}
fn pump(
inner: Arc<Inner>,
id: String,
epoch: String,
mut source: api::GenerationStream,
sender: mpsc::Sender<Result<proto::GenerationFrame, Status>>,
) {
let mut sequence = 1;
let accepted = proto::GenerationFrame {
request_id: id.clone(),
epoch: epoch.clone(),
sequence,
payload: Some(proto::generation_frame::Payload::Accepted(
proto::Accepted { accepted: true },
)),
};
if sender.blocking_send(Ok(accepted)).is_err() {
cancel_and_drain(&inner, &id, &mut source);
return;
}
loop {
let (event, confirmed) = match source.recv() {
Ok(Some(event)) => (event, true),
_ => (
api::GenerationEvent::Terminal(api::GenerationTerminal::Failed {
code: api::ErrorCode::Internal,
message: "missing_terminal".into(),
retryable: false,
}),
false,
),
};
sequence += 1;
let terminal = matches!(event, api::GenerationEvent::Terminal(_));
let frame = proto::GenerationFrame {
request_id: id.clone(),
epoch: epoch.clone(),
sequence,
payload: Some(event_to_proto(event)),
};
if frame.encoded_len() > FRAME_LIMIT {
let failed = proto::GenerationFrame {
request_id: id.clone(),
epoch: epoch.clone(),
sequence,
payload: Some(event_to_proto(api::GenerationEvent::Terminal(
api::GenerationTerminal::Failed {
code: api::ErrorCode::ResourceExhausted,
message: "output_frame_limit".into(),
retryable: false,
},
))),
};
let _ = sender.blocking_send(Ok(failed));
settle(&inner, &id, &mut source, terminal, confirmed);
return;
}
if sender.blocking_send(Ok(frame)).is_err() {
settle(&inner, &id, &mut source, terminal, confirmed);
return;
}
if terminal {
settle(&inner, &id, &mut source, terminal, confirmed);
break;
}
}
}
fn capabilities_to_proto(value: &api::BackendCapabilities) -> proto::Capabilities {
proto::Capabilities {
models: value
.supported_models
.iter()
.map(|m| proto::SupportedModelTuple {
family: m.family.clone(),
architecture: m.architecture.clone(),
weight_format: m.weight_format.clone(),
})
.collect(),
max_concurrent_generations: u32::try_from(value.max_concurrent_generations).unwrap_or(0),
cancellation: value.supports_cancellation,
tool_call_streaming: value.supports_tool_call_streaming,
}
}
fn usage_to_proto(value: api::Usage) -> proto::Usage {
proto::Usage {
input_tokens: value.input_tokens,
output_tokens: value.output_tokens,
reused_input_tokens: value.reused_input_tokens,
}
}
fn event_to_proto(value: api::GenerationEvent) -> proto::generation_frame::Payload {
use proto::generation_frame::Payload;
match value {
api::GenerationEvent::TextDelta { text } => Payload::Text(proto::TextDelta { text }),
api::GenerationEvent::ToolCallDelta {
index,
id,
name,
arguments_delta,
} => Payload::Tool(proto::ToolCallDelta {
index,
id,
name,
arguments_delta,
}),
api::GenerationEvent::Usage(usage) => Payload::Usage(usage_to_proto(usage)),
api::GenerationEvent::Terminal(terminal) => Payload::Terminal(match terminal {
api::GenerationTerminal::Completed { reason, usage } => proto::Terminal {
state: 1,
reason: match reason {
api::FinishReason::Stop => "stop",
api::FinishReason::Length => "length",
api::FinishReason::ToolCalls => "tool_calls",
}
.into(),
usage: Some(usage_to_proto(usage)),
error_code: String::new(),
retryable: false,
},
api::GenerationTerminal::Cancelled => proto::Terminal {
state: 3,
reason: "cancelled".into(),
usage: None,
error_code: String::new(),
retryable: false,
},
api::GenerationTerminal::Failed { code, .. } => proto::Terminal {
state: 2,
reason: "generation_failed".into(),
usage: None,
error_code: match code {
api::ErrorCode::InvalidRequest => "invalid_request",
api::ErrorCode::UnsupportedModel => "unsupported_model",
api::ErrorCode::ResourceExhausted => "resource_exhausted",
api::ErrorCode::BackendUnavailable => "backend_unavailable",
api::ErrorCode::Internal => "internal",
}
.into(),
retryable: false,
},
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime_client::RuntimeClient;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
const TOKEN: &str = "synthetic-runtime-test-token-00000000";
struct Mock {
loads: Arc<AtomicUsize>,
cancel: Arc<AtomicBool>,
}
fn model() -> api::ModelDescriptor {
api::ModelDescriptor {
family: "fixture".into(),
architecture: "fixture".into(),
weight_format: "fixture".into(),
artifact_digest: format!("sha256:{}", "a".repeat(64)),
}
}
fn config() -> api::RuntimeConfig {
api::RuntimeConfig {
load_config_version: 1,
inference_mode: api::InferenceMode::Native,
gpu_memory_limit_bytes: Some(1024),
allow_experimental: false,
}
}
fn loaded() -> api::LoadedModel {
api::LoadedModel {
handle: "fixture-handle".into(),
descriptor: model(),
load_config_version: 1,
effective_mode: api::InferenceMode::Native,
mode_identity_digest: format!("sha256:{}", "b".repeat(64)),
}
}
impl api::Backend for Mock {
fn identity(&self) -> api::BackendIdentity {
api::BackendIdentity {
name: "fixture".into(),
implementation_version: "1".into(),
api_version: 2,
}
}
fn capabilities(&self) -> api::BackendCapabilities {
api::BackendCapabilities {
supported_models: vec![api::SupportedModelTuple {
family: "fixture".into(),
architecture: "fixture".into(),
weight_format: "fixture".into(),
}],
max_concurrent_generations: 1,
supports_cancellation: true,
supports_tool_call_streaming: false,
}
}
fn load(
&mut self,
_model: api::ModelDescriptor,
config: api::RuntimeConfig,
) -> Result<api::LoadedModel, api::BackendError> {
self.loads.fetch_add(1, Ordering::SeqCst);
if config.inference_mode != api::InferenceMode::Native {
return Err(api::BackendError {
code: api::ErrorCode::UnsupportedModel,
message: "private-path-must-not-leak".into(),
retryable: false,
});
}
Ok(loaded())
}
fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> {
Ok(())
}
fn cancel(&mut self, _: &str) -> Result<(), api::BackendError> {
self.cancel.store(true, Ordering::SeqCst);
Ok(())
}
fn start_generation(
&mut self,
_: &api::LoadedModel,
request: api::GenerationRequest,
) -> Result<api::GenerationStream, api::BackendError> {
let (sink, stream) = api::GenerationSink::channel();
let cancelled = self.cancel.clone();
cancelled.store(false, Ordering::SeqCst);
std::thread::spawn(move || {
if request.prompt == "missing" {
return;
}
if request.prompt == "slow-missing" {
// Ends without a terminal, but only after the client is gone.
std::thread::sleep(std::time::Duration::from_millis(150));
return;
}
if request.prompt == "wait" {
while !cancelled.load(Ordering::SeqCst) {
std::thread::park_timeout(std::time::Duration::from_millis(2));
}
let _ = sink.cancel();
return;
}
let _ = sink.emit(api::GenerationEvent::TextDelta { text: "A".into() });
let usage = api::Usage {
input_tokens: 1,
output_tokens: 1,
reused_input_tokens: 0,
};
let _ = sink.emit(api::GenerationEvent::Usage(usage.clone()));
let _ = sink.complete(api::FinishReason::Stop, usage);
});
Ok(stream)
}
}
async fn fixture() -> (
RuntimeClient,
RuntimeServer,
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<()>,
Arc<AtomicUsize>,
Arc<AtomicBool>,
SocketAddr,
) {
let loads = Arc::new(AtomicUsize::new(0));
let cancel = Arc::new(AtomicBool::new(false));
let server = RuntimeServer::new(
Box::new(Mock {
loads: loads.clone(),
cancel: cancel.clone(),
}),
TOKEN.into(),
)
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (stop, stopped) = tokio::sync::oneshot::channel();
let owned = server.clone();
let task = tokio::spawn(async move {
owned
.serve(listener, async {
let _ = stopped.await;
})
.await
.unwrap();
});
let client = RuntimeClient::connect(address, TOKEN.into()).await.unwrap();
(client, server, stop, task, loads, cancel, address)
}
async fn load_fixture(client: &mut RuntimeClient) -> (String, String) {
let snapshot = client.snapshot().await.unwrap();
assert!(snapshot.transport_ready && !snapshot.model_ready);
assert!(snapshot.capabilities.unwrap().models.is_empty());
let id = Uuid::new_v4().to_string();
client
.load(proto::LoadRequest {
operation_id: id.clone(),
expected_epoch: snapshot.epoch.clone(),
model: Some(descriptor_to_proto(&model())),
config: Some(config_to_proto(&config())),
})
.await
.unwrap();
for _ in 0..100 {
let operation = client
.operation(proto::OperationQuery {
operation_id: id.clone(),
expected_epoch: snapshot.epoch.clone(),
})
.await
.unwrap();
if operation.state == 2 {
return (snapshot.epoch, operation.loaded.unwrap().handle);
}
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
}
panic!("fixture_load_timeout")
}
fn request(epoch: &str, handle: &str, prompt: &str) -> proto::GenerateRequest {
proto::GenerateRequest {
request_id: Uuid::new_v4().to_string(),
expected_epoch: epoch.into(),
handle: handle.into(),
prompt: prompt.into(),
max_output_tokens: 2,
temperature_milli: 0,
..Default::default()
}
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() {
let (mut client, server, stop, task, loads, _, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let command = {
let state = server.inner.state.lock().unwrap();
state
.operations
.values()
.next()
.unwrap()
.result
.operation_id
.clone()
};
let load = proto::LoadRequest {
operation_id: command.clone(),
expected_epoch: epoch.clone(),
model: Some(descriptor_to_proto(&model())),
config: Some(config_to_proto(&config())),
};
assert_eq!(client.load(load.clone()).await.unwrap().state, 2);
assert_eq!(loads.load(Ordering::SeqCst), 1);
let mut conflict = load;
conflict.config.as_mut().unwrap().gpu_memory_limit_bytes = Some(2048);
assert_eq!(
client.load(conflict).await.unwrap_err().code(),
tonic::Code::AlreadyExists
);
let mut stream = client
.generate(request(&epoch, &handle, "normal"))
.await
.unwrap();
let mut frames = Vec::new();
while let Some(frame) = stream.message().await.unwrap() {
frames.push(frame);
}
assert_eq!(
frames.iter().map(|f| f.sequence).collect::<Vec<_>>(),
vec![1, 2, 3, 4]
);
assert!(matches!(
frames[0].payload,
Some(proto::generation_frame::Payload::Accepted(_))
));
assert!(matches!(
frames[1].payload,
Some(proto::generation_frame::Payload::Text(_))
));
assert!(matches!(
frames[2].payload,
Some(proto::generation_frame::Payload::Usage(_))
));
assert!(matches!(
frames[3].payload,
Some(proto::generation_frame::Payload::Terminal(
proto::Terminal { state: 1, .. }
))
));
let mut ple = config();
ple.allow_experimental = true;
ple.inference_mode = api::InferenceMode::ExperimentalKarPle {
profile_id: "unqualified".into(),
};
let operation = Uuid::new_v4().to_string();
client
.load(proto::LoadRequest {
operation_id: operation.clone(),
expected_epoch: epoch.clone(),
model: Some(descriptor_to_proto(&model())),
config: Some(config_to_proto(&ple)),
})
.await
.unwrap();
for _ in 0..100 {
if client
.operation(proto::OperationQuery {
operation_id: operation.clone(),
expected_epoch: epoch.clone(),
})
.await
.unwrap()
.state
== 3
{
break;
}
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
}
let current = client.snapshot().await.unwrap();
assert!(current.model_ready);
assert_eq!(current.loaded.unwrap().handle, handle);
drop(stream);
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_unconfirmed_terminal_after_client_loss_keeps_slot_owned() {
let (mut client, server, stop, task, _, _, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let mut stream = client
.generate(request(&epoch, &handle, "slow-missing"))
.await
.unwrap();
assert!(stream.message().await.unwrap().is_some());
drop(stream);
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
let snapshot = client.snapshot().await.unwrap();
// A synthesized terminal is no completion proof: the slot stays owned
// and model admission is closed rather than reopened.
assert!(!snapshot.active_request_id.is_empty());
assert!(!snapshot.model_ready);
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
fn operation_entry(id: &str, state: proto::operation_result::State) -> Operation {
Operation {
digest: [0; 32],
result: proto::OperationResult {
operation_id: id.into(),
epoch: String::new(),
state: state as i32,
reason: String::new(),
loaded: None,
},
}
}
#[tokio::test(flavor = "current_thread")]
async fn lifecycle_guard_ends_only_its_own_unresolved_operation() {
let (client, server, stop, task, _, _, _) = fixture().await;
let (first, second) = (Uuid::new_v4().to_string(), Uuid::new_v4().to_string());
{
// The first worker already published its completion and disarmed
// nothing yet; a second operation then took the lifecycle gate.
let mut state = server.inner.state.lock().unwrap();
state.operations.insert(
first.clone(),
operation_entry(&first, proto::operation_result::State::Completed),
);
state.operations.insert(
second.clone(),
operation_entry(&second, proto::operation_result::State::Accepted),
);
state.lifecycle_busy = true;
state.loaded = Some(loaded());
}
// A stale armed guard of the finished first operation must be inert.
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: first.clone(),
armed: true,
});
{
let state = server.inner.state.lock().unwrap();
assert!(state.lifecycle_busy && state.loaded.is_some());
assert_eq!(
state.operations[&second].result.state,
proto::operation_result::State::Accepted as i32
);
}
// A disarmed guard is inert even for its own unresolved operation.
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: second.clone(),
armed: false,
});
assert!(server.inner.state.lock().unwrap().lifecycle_busy);
// The failed worker's own unresolved operation ends as indeterminate.
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: second.clone(),
armed: true,
});
{
let state = server.inner.state.lock().unwrap();
assert!(!state.lifecycle_busy && state.loaded.is_none());
assert_eq!(
state.operations[&second].result.state,
proto::operation_result::State::Indeterminate as i32
);
assert_eq!(
state.operations[&second].result.reason,
"lifecycle_worker_failed"
);
assert_eq!(
state.operations[&first].result.state,
proto::operation_result::State::Completed as i32
);
}
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission() {
let (mut client, server, stop, task, _, cancelled, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let command = request(&epoch, &handle, "wait");
let mut stream = client.generate(command.clone()).await.unwrap();
assert!(stream.message().await.unwrap().is_some());
drop(stream);
for _ in 0..100 {
if client
.snapshot()
.await
.unwrap()
.active_request_id
.is_empty()
{
break;
}
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
}
assert!(cancelled.load(Ordering::SeqCst));
assert!(
client
.snapshot()
.await
.unwrap()
.active_request_id
.is_empty()
);
assert_eq!(
client.generate(command).await.err().unwrap().code(),
tonic::Code::AlreadyExists
);
let mut missing = client
.generate(request(&epoch, &handle, "missing"))
.await
.unwrap();
missing.message().await.unwrap();
let terminal = missing.message().await.unwrap().unwrap();
assert!(matches!(
terminal.payload,
Some(proto::generation_frame::Payload::Terminal(
proto::Terminal {
state: 2,
retryable: false,
..
}
))
));
assert!(missing.message().await.unwrap().is_none());
let closed = client.snapshot().await.unwrap();
assert!(!closed.model_ready);
assert!(!closed.active_request_id.is_empty());
drop(missing);
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_accepted_identity_stays_fenced_while_a_full_ledger_rolls_over() {
let (mut client, server, stop, task, _, _, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let accepted = request(&epoch, &handle, "A");
let other_active = Uuid::new_v4().to_string();
{
let mut state = server.inner.state.lock().unwrap();
let capacity = state.requests.capacity();
// The accepted identity is the newest of a full ledger.
for _ in 1..capacity {
state.requests.insert(&Uuid::new_v4().to_string());
}
state.requests.insert(&accepted.request_id);
assert_eq!(state.requests.len(), capacity);
}
// A busy slot or a repeated identity is refused, whatever the ledger holds.
for active in [None, Some(accepted.request_id.clone()), Some(other_active)] {
server.inner.state.lock().unwrap().active = active.clone();
let duplicate = client.generate(accepted.clone()).await.err().unwrap();
assert_eq!(duplicate.code(), tonic::Code::AlreadyExists);
assert_eq!(duplicate.message(), "generation_not_replayed");
assert!(duplicate.metadata().get("x-leleka-accepted").is_none());
if active.is_some() {
// A new identity meets the busy slot, not a full ledger, and is proven unaccepted.
let fresh = client
.generate(request(&epoch, &handle, "A"))
.await
.err()
.unwrap();
assert_eq!(fresh.code(), tonic::Code::ResourceExhausted);
assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false");
}
let state = server.inner.state.lock().unwrap();
assert_eq!(state.active, active);
assert_eq!(state.requests.len(), state.requests.capacity());
assert!(state.requests.contains(&accepted.request_id));
}
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() {
for code in [api::ErrorCode::BackendUnavailable, api::ErrorCode::Internal] {
assert!(
backend_status(&api::BackendError {
code,
message: "private".into(),
retryable: true
})
.metadata()
.get("x-leleka-accepted")
.is_none()
);
}
for code in [
api::ErrorCode::InvalidRequest,
api::ErrorCode::UnsupportedModel,
api::ErrorCode::ResourceExhausted,
] {
assert_eq!(
backend_status(&api::BackendError {
code,
message: "private".into(),
retryable: true
})
.metadata()
.get("x-leleka-accepted")
.unwrap(),
"false"
);
}
let (mut client, server, stop, task, _, _, local_address) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let mut wrong = client.clone();
assert_eq!(
RuntimeClient::connect(local_address, "wrong-synthetic-runtime-token-000000".into())
.await
.err()
.unwrap()
.code(),
tonic::Code::Unauthenticated
);
let mut watches = Vec::new();
for _ in 0..16 {
let mut watch = client
.watch(proto::Cursor {
epoch: epoch.clone(),
sequence: 0,
})
.await
.unwrap();
assert_eq!(watch.message().await.unwrap().unwrap().epoch, epoch);
watches.push(watch);
}
assert_eq!(
client
.watch(proto::Cursor {
epoch: epoch.clone(),
sequence: 0
})
.await
.err()
.unwrap()
.code(),
tonic::Code::ResourceExhausted
);
drop(watches);
// The client rejects direct nonloopback endpoints before connecting.
let address = SocketAddr::from(([192, 0, 2, 1], 1));
assert_eq!(
RuntimeClient::connect(address, TOKEN.into())
.await
.err()
.unwrap()
.code(),
tonic::Code::PermissionDenied
);
let old = Uuid::new_v4().to_string();
assert_eq!(
wrong
.generate(request(&old, &handle, "normal"))
.await
.err()
.unwrap()
.message(),
"epoch_mismatch"
);
let mut huge = request(&epoch, &handle, "normal");
huge.max_output_tokens = api::MAX_OUTPUT_TOKENS + 1;
let rejected = client.generate(huge).await.err().unwrap();
assert_eq!(
rejected.metadata().get("x-leleka-accepted").unwrap(),
"false"
);
let unknown = client
.operation(proto::OperationQuery {
operation_id: Uuid::new_v4().to_string(),
expected_epoch: old,
})
.await
.unwrap();
assert_eq!(unknown.state, 4);
{
let mut state = server.inner.state.lock().unwrap();
for _ in state.operations.len()..MAX_IDS {
let id = Uuid::new_v4().to_string();
state.operations.insert(
id.clone(),
Operation {
digest: [0; 32],
result: proto::OperationResult {
operation_id: id,
epoch: epoch.clone(),
state: 2,
reason: "fixture".into(),
loaded: None,
},
},
);
}
}
assert_eq!(
server
.reserve(&Uuid::new_v4().to_string(), &epoch, [1; 32])
.unwrap_err()
.code(),
tonic::Code::ResourceExhausted
);
let (id, digest) = {
let state = server.inner.state.lock().unwrap();
let (id, op) = state.operations.iter().next().unwrap();
(id.clone(), op.digest)
};
assert!(!server.reserve(&id, &epoch, digest).unwrap().1);
drop(wrong);
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
}