Files
leleka/control-plane/src/models_api.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 392037d83e feat(serving): port the operational HTTP surface of the Python server
control-plane serves /props, /slots, /v1/status, /api/health, /settings, /load, /unload,
/v1/load, /v1/unload, model aliases, CORS with the preflight ahead of authentication and the
own-page guard; replayed scenario by scenario against the real Python handlers. The worker
supervisor gains load/unload, lazy start, idle unload, reload gates (before_load, min free VRAM),
an outside stall watchdog and the reasoning-budget wrap-up (budget tracker golden-tested against
the Python Detokenizer/OutputParser loop). leleka-serving-policy adds CORS, idle, stall watchdog,
logits stride (golden vs the C++ header), request timings and alias rules.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:35:08 +02:00

150 lines
5.2 KiB
Rust

//! Configured deployment discovery; does not acquire a worker or imply readiness.
use axum::{
Json,
extract::{Path, RawQuery, State},
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::{Value, json};
use crate::app::AppState;
fn record(id: &str) -> Value {
// No upstream creation/ownership metadata is supplied by the local config.
// Zero is an explicit unknown timestamp sentinel; local names the deployment.
json!({"id":id,"object":"model","created":0,"owned_by":"local"})
}
/// The model and each configured alias (`alias_of` names the model), like the Original; an engine
/// that is unloaded on purpose says so (`status`) and still lists: it loads on use.
async fn records(state: &AppState) -> Vec<Value> {
let unloaded = state.worker.read().await.state == crate::worker::WorkerState::Unloaded;
let mark = |mut value: Value| {
if unloaded {
value["status"] = json!({"value": "unloaded"});
}
value
};
let Some(model) = state.model.as_deref() else {
return Vec::new();
};
let mut out = vec![mark(record(model))];
if !state.aliases.is_empty() {
out[0]["aliases"] = json!(*state.aliases);
}
for alias in state.aliases.iter() {
let mut value = mark(record(alias));
value["alias_of"] = json!(model);
out.push(value);
}
out
}
fn query_error(query: Option<String>) -> Option<Response> {
query.filter(|q| !q.is_empty()).map(|_| {
(
StatusCode::BAD_REQUEST,
Json(json!({"error":{
"type":"invalid_request_error","code":"unsupported_query","param":null,
"message":"model discovery does not support query parameters"
}})),
)
.into_response()
})
}
pub async fn list(State(state): State<AppState>, RawQuery(query): RawQuery) -> Response {
if let Some(error) = query_error(query) {
return error;
}
let data = records(&state).await;
Json(json!({"object":"list","data":data})).into_response()
}
pub async fn retrieve(
State(state): State<AppState>,
Path(id): Path<String>,
RawQuery(query): RawQuery,
) -> Response {
if let Some(error) = query_error(query) {
return error;
}
if let Some(found) = records(&state)
.await
.into_iter()
.find(|value| value["id"] == id.as_str())
{
return Json(found).into_response();
}
(
StatusCode::NOT_FOUND,
Json(json!({"error":{
"type":"invalid_request_error","code":"model_not_found","param":"model",
"message":"the requested model is not configured on this runtime"
}})),
)
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn discovery_during_worker_outage_and_drain_never_schedules_generation() {
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
let state = AppState {
model: Some("org/model : v1".into()),
generation: Some(sender),
..Default::default()
};
state.lifecycle.set_draining(true);
state.worker.write().await.state = crate::worker::WorkerState::Restarting;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let router = crate::app::router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let client = reqwest::Client::new();
for (path, expected) in [
(
"/v1/models",
json!({"object":"list","data":[{"id":"org/model : v1","object":"model","created":0,"owned_by":"local"}]}),
),
(
"/v1/models/org%2Fmodel%20%3A%20v1",
json!({"id":"org/model : v1","object":"model","created":0,"owned_by":"local"}),
),
] {
let response = client.get(format!("{url}{path}")).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(body, expected);
}
for (path, code) in [
("/v1/models/unknown", 404),
("/v1/models?limit=1", 400),
("/v1/models/unknown?x=1", 400),
] {
let response = client.get(format!("{url}{path}")).send().await.unwrap();
assert_eq!(response.status().as_u16(), code);
}
assert!(receiver.try_recv().is_err());
assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0);
assert_eq!(state.lifecycle.snapshot().generation_jobs, 0);
assert_eq!(
state.worker.read().await.state,
crate::worker::WorkerState::Restarting
);
server.abort();
let _ = server.await;
let response = list(State(AppState::default()), RawQuery(None)).await;
let body = axum::body::to_bytes(response.into_body(), 4096)
.await
.unwrap();
assert_eq!(
serde_json::from_slice::<Value>(&body).unwrap(),
json!({"object":"list","data":[]})
);
}
}