Files
leleka/control-plane/src/lifecycle.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

323 lines
10 KiB
Rust

//! Process-local admission drain. A request remains admitted until its body is
//! consumed/dropped; commands remain tracked through worker protocol cleanup.
use std::{
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use axum::{
Json,
body::{Body, Bytes},
extract::{Request, State},
http::{StatusCode, header::RETRY_AFTER},
middleware::Next,
response::{IntoResponse, Response},
};
use http_body::{Body as HttpBody, Frame, SizeHint};
use serde::Serialize;
use serde_json::json;
pub const DEFAULT_MAX_IN_FLIGHT_REQUESTS: usize = 17;
pub fn validate_capacity(value: usize) -> Result<(), &'static str> {
if (1..=256).contains(&value) {
Ok(())
} else {
Err("max_in_flight_requests must be between 1 and 256")
}
}
#[derive(Clone)]
pub struct Lifecycle(Arc<Mutex<Snapshot>>);
impl Default for Lifecycle {
fn default() -> Self {
Self::new(DEFAULT_MAX_IN_FLIGHT_REQUESTS).expect("valid default capacity")
}
}
#[derive(Debug, PartialEq, Eq)]
enum AdmissionError {
Draining,
Overloaded,
}
#[derive(Clone, Copy, Default, Serialize)]
pub struct Snapshot {
pub max_in_flight_requests: usize,
pub draining: bool,
pub shutting_down: bool,
pub requests_in_flight: usize,
pub generation_jobs: usize,
}
pub struct Guard {
lifecycle: Lifecycle,
generation: bool,
}
impl Lifecycle {
pub fn new(max_in_flight_requests: usize) -> Result<Self, &'static str> {
validate_capacity(max_in_flight_requests)?;
Ok(Self(Arc::new(Mutex::new(Snapshot {
max_in_flight_requests,
..Snapshot::default()
}))))
}
pub fn snapshot(&self) -> Snapshot {
*self.0.lock().expect("admission mutex")
}
pub fn set_draining(&self, draining: bool) {
let mut state = self.0.lock().expect("admission mutex");
state.draining = draining || state.shutting_down;
}
/// Signal shutdown cannot be undone by an administrative resume.
pub fn begin_shutdown(&self) {
let mut state = self.0.lock().expect("admission mutex");
state.shutting_down = true;
state.draining = true;
}
/// Wait for admitted HTTP bodies and queued/active worker commands. This
/// bounds only the drain phase; process/connection cleanup happens later.
pub async fn wait_drained(&self, grace: std::time::Duration) -> bool {
tokio::time::timeout(grace, async {
loop {
let state = self.snapshot();
if state.requests_in_flight == 0 && state.generation_jobs == 0 {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
}
})
.await
.is_ok()
}
fn admit(&self) -> Result<Guard, AdmissionError> {
let mut state = self.0.lock().expect("admission mutex");
if state.draining {
return Err(AdmissionError::Draining);
}
if state.requests_in_flight >= state.max_in_flight_requests {
return Err(AdmissionError::Overloaded);
}
state.requests_in_flight += 1;
Ok(Guard {
lifecycle: self.clone(),
generation: false,
})
}
// Called only for requests that already passed admission. Drain must not
// prevent those requests from entering the command queue later.
pub fn generation(&self) -> Guard {
self.0.lock().expect("admission mutex").generation_jobs += 1;
Guard {
lifecycle: self.clone(),
generation: true,
}
}
}
impl Drop for Guard {
fn drop(&mut self) {
let mut state = self.lifecycle.0.lock().expect("admission mutex");
if self.generation {
state.generation_jobs -= 1;
} else {
state.requests_in_flight -= 1;
}
}
}
pub async fn admit(State(lifecycle): State<Lifecycle>, request: Request, next: Next) -> Response {
let guard = match lifecycle.admit() {
Ok(guard) => guard,
Err(AdmissionError::Draining) => {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"error":{
"type":"server_error", "code":"runtime_draining",
"message":"Runtime is draining; new inference requests are not accepted"
}})),
)
.into_response();
}
Err(AdmissionError::Overloaded) => {
return (
StatusCode::TOO_MANY_REQUESTS,
[(RETRY_AFTER, "1")],
Json(json!({"error":{
"type":"server_error", "code":"runtime_overloaded",
"message":"Runtime request capacity is full; retry later"
}})),
)
.into_response();
}
};
let response = next.run(request).await;
let (parts, body) = response.into_parts();
Response::from_parts(
parts,
Body::new(TrackedBody {
body,
guard: Some(guard),
}),
)
}
struct TrackedBody {
body: Body,
guard: Option<Guard>,
}
impl HttpBody for TrackedBody {
type Data = Bytes;
type Error = axum::Error;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
let frame = Pin::new(&mut self.body).poll_frame(cx);
if matches!(frame, Poll::Ready(None | Some(Err(_)))) {
self.guard.take();
}
frame
}
fn is_end_stream(&self) -> bool {
self.body.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.body.size_hint()
}
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::{BodyExt, StreamBody};
use std::{collections::VecDeque, convert::Infallible};
struct Frames(VecDeque<Frame<Bytes>>);
#[tokio::test]
async fn signal_drain_cannot_resume_and_waits_for_both_lifetimes() {
use std::time::Duration;
let lifecycle = Lifecycle::default();
let request = lifecycle.admit().unwrap();
lifecycle.begin_shutdown();
lifecycle.set_draining(false);
assert!(lifecycle.snapshot().shutting_down);
assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining)));
// An admitted request can still enqueue after signal arrival.
let command = lifecycle.generation();
assert!(!lifecycle.wait_drained(Duration::ZERO).await);
drop(request);
assert!(!lifecycle.wait_drained(Duration::from_millis(5)).await);
let cloned = lifecycle.clone();
let waiter = tokio::spawn(async move { cloned.wait_drained(Duration::from_secs(1)).await });
drop(command);
assert!(waiter.await.unwrap());
assert!(lifecycle.wait_drained(Duration::ZERO).await);
lifecycle.set_draining(false);
assert!(lifecycle.snapshot().draining);
}
#[test]
fn concurrent_admission_reserves_capacity_and_releases_on_drop() {
use std::{sync::Barrier, thread};
assert!(Lifecycle::new(0).is_err());
assert!(Lifecycle::new(257).is_err());
assert!(Lifecycle::new(256).is_ok());
let lifecycle = Lifecycle::new(3).unwrap();
let start = Arc::new(Barrier::new(32));
let reserved = Arc::new(Barrier::new(32));
let results = thread::scope(|scope| {
let handles: Vec<_> = (0..32)
.map(|_| {
let lifecycle = lifecycle.clone();
let start = start.clone();
let reserved = reserved.clone();
scope.spawn(move || {
start.wait();
let admission = lifecycle.admit();
reserved.wait(); // Keep every admitted guard until all attempts finish.
let count = lifecycle.snapshot().requests_in_flight;
reserved.wait();
assert_eq!(count, 3);
admission.is_ok()
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().unwrap())
.filter(|ok| *ok)
.count()
});
assert_eq!(results, 3);
assert_eq!(lifecycle.snapshot().requests_in_flight, 0);
let _request = lifecycle.admit().unwrap();
lifecycle.set_draining(true);
assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining)));
}
impl futures_core::Stream for Frames {
type Item = Result<Frame<Bytes>, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Poll::Ready(self.0.pop_front().map(Ok))
}
}
#[tokio::test]
async fn drain_tracks_body_frames_trailers_and_command_lifetimes_independently() {
let lifecycle = Lifecycle::default();
let request = lifecycle.admit().unwrap();
lifecycle.set_draining(true);
assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining)));
// Already admitted work can enqueue after drain was requested.
let command = lifecycle.generation();
let mut trailers = axum::http::HeaderMap::new();
trailers.insert("x-fixture", "kept".parse().unwrap());
let frames = Frames(VecDeque::from([
Frame::data(Bytes::from_static(b"data: terminal\n\n")),
Frame::trailers(trailers.clone()),
]));
let mut body = TrackedBody {
body: Body::new(StreamBody::new(frames)),
guard: Some(request),
};
assert_eq!(
body.frame().await.unwrap().unwrap().into_data().unwrap(),
"data: terminal\n\n"
);
assert_eq!(lifecycle.snapshot().requests_in_flight, 1);
assert_eq!(
body.frame()
.await
.unwrap()
.unwrap()
.into_trailers()
.unwrap(),
trailers
);
assert!(body.frame().await.is_none());
assert_eq!(lifecycle.snapshot().requests_in_flight, 0);
assert_eq!(lifecycle.snapshot().generation_jobs, 1);
drop(command);
assert_eq!(lifecycle.snapshot().generation_jobs, 0);
lifecycle.set_draining(false);
let guard = lifecycle.admit().unwrap();
drop(TrackedBody {
body: Body::empty(),
guard: Some(guard),
});
assert_eq!(lifecycle.snapshot().requests_in_flight, 0);
}
}