Each helper does one action and is named verb+object (sample_host, add_nvidia_accelerators, check_pool_bounds, index_groups, subscribe, publish_ready, follow_updates, respond_request, refusal_status, read_headers, relay_body, build_response, publish_text, publish_call, terminal_status, total_tokens, call_size ...). New modules: node/respond.rs, runtime_tool_response/preflight.rs. Behaviour unchanged (same error texts and order). The remote probe script wraps its nvidia-smi line with a shell line continuation (same command).
274 lines
7.9 KiB
Rust
274 lines
7.9 KiB
Rust
//! In-memory admission only: a lease covers the entire upstream request/stream.
|
|
use serde::Serialize;
|
|
use std::{
|
|
collections::{HashMap, VecDeque},
|
|
sync::{Arc, Mutex},
|
|
time::Duration,
|
|
};
|
|
use tokio::{sync::oneshot, time::Instant};
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Worker {
|
|
pub id: String,
|
|
pub group: String,
|
|
pub slots: usize,
|
|
/// Adapter-supplied upper bound on incremental memory per active request.
|
|
pub request_bytes: u64,
|
|
}
|
|
#[derive(Clone, Debug)]
|
|
pub struct ResourceGroup {
|
|
pub id: String,
|
|
pub slots: usize,
|
|
/// Available budget AFTER resident model weights and safety reserve.
|
|
pub available_bytes: u64,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum AdmissionError {
|
|
Invalid,
|
|
Full,
|
|
Expired,
|
|
Closed,
|
|
}
|
|
#[derive(Clone)]
|
|
pub struct Pool(Arc<Mutex<State>>);
|
|
struct State {
|
|
workers: Vec<Worker>,
|
|
groups: HashMap<String, ResourceGroup>,
|
|
ready: Vec<bool>,
|
|
pending: VecDeque<Pending>,
|
|
active: HashMap<u64, usize>,
|
|
next_id: u64,
|
|
queue_limit: usize,
|
|
}
|
|
struct Pending {
|
|
id: u64,
|
|
eligible: Vec<usize>,
|
|
deadline: Instant,
|
|
tx: oneshot::Sender<Result<usize, AdmissionError>>,
|
|
}
|
|
/// Dropping an acquisition future OR its successful lease releases its reservation.
|
|
pub struct Lease {
|
|
pool: Pool,
|
|
id: u64,
|
|
worker: usize,
|
|
}
|
|
impl Lease {
|
|
pub fn worker(&self) -> usize {
|
|
self.worker
|
|
}
|
|
}
|
|
impl Drop for Lease {
|
|
fn drop(&mut self) {
|
|
let mut s = self.pool.0.lock().unwrap();
|
|
s.pending.retain(|p| p.id != self.id);
|
|
s.active.remove(&self.id);
|
|
s.dispatch();
|
|
}
|
|
}
|
|
#[derive(Debug, Serialize)]
|
|
pub struct Snapshot {
|
|
pub queued: usize,
|
|
pub active: usize,
|
|
pub workers: Vec<WorkerStatus>,
|
|
}
|
|
#[derive(Debug, Serialize)]
|
|
pub struct WorkerStatus {
|
|
pub id: String,
|
|
pub ready: bool,
|
|
pub active: usize,
|
|
pub slots: usize,
|
|
}
|
|
|
|
impl Pool {
|
|
pub fn new(
|
|
workers: Vec<Worker>,
|
|
groups: Vec<ResourceGroup>,
|
|
queue_limit: usize,
|
|
) -> Result<Self, AdmissionError> {
|
|
check_pool_bounds(&workers, &groups, queue_limit)?;
|
|
let groups = index_groups(groups)?;
|
|
check_workers_fit_their_group(&workers, &groups)?;
|
|
Ok(Self(Arc::new(Mutex::new(State {
|
|
ready: vec![true; workers.len()],
|
|
workers,
|
|
groups,
|
|
pending: VecDeque::new(),
|
|
active: HashMap::new(),
|
|
next_id: 0,
|
|
queue_limit,
|
|
}))))
|
|
}
|
|
|
|
/// Queue a request for one of the `eligible` workers and return its lease (worker not yet assigned).
|
|
fn enqueue(
|
|
&self,
|
|
eligible: Vec<usize>,
|
|
deadline: Instant,
|
|
tx: oneshot::Sender<Result<usize, AdmissionError>>,
|
|
) -> Result<Lease, AdmissionError> {
|
|
let mut s = self.0.lock().unwrap();
|
|
if eligible.is_empty() || eligible.iter().any(|i| *i >= s.workers.len()) {
|
|
return Err(AdmissionError::Invalid);
|
|
}
|
|
s.dispatch();
|
|
if s.pending.len() >= s.queue_limit {
|
|
return Err(AdmissionError::Full);
|
|
}
|
|
let id = s.next_id.checked_add(1).ok_or(AdmissionError::Closed)?;
|
|
s.next_id = id;
|
|
s.pending.push_back(Pending {
|
|
id,
|
|
eligible,
|
|
deadline,
|
|
tx,
|
|
});
|
|
s.dispatch();
|
|
Ok(Lease {
|
|
pool: self.clone(),
|
|
id,
|
|
worker: 0,
|
|
})
|
|
}
|
|
|
|
pub async fn acquire(
|
|
&self,
|
|
eligible: Vec<usize>,
|
|
wait: Duration,
|
|
) -> Result<Lease, AdmissionError> {
|
|
let deadline = Instant::now()
|
|
.checked_add(wait)
|
|
.ok_or(AdmissionError::Invalid)?;
|
|
let (tx, rx) = oneshot::channel();
|
|
let mut lease = self.enqueue(eligible, deadline, tx)?;
|
|
// The guard exists before the first await, including the dispatch/cancel race.
|
|
let worker = tokio::time::timeout_at(deadline, rx)
|
|
.await
|
|
.map_err(|_| AdmissionError::Expired)?
|
|
.map_err(|_| AdmissionError::Closed)??;
|
|
lease.worker = worker;
|
|
Ok(lease)
|
|
}
|
|
|
|
pub fn set_ready(&self, worker: usize, ready: bool) -> Result<(), AdmissionError> {
|
|
let mut s = self.0.lock().unwrap();
|
|
*s.ready.get_mut(worker).ok_or(AdmissionError::Invalid)? = ready;
|
|
s.dispatch();
|
|
Ok(())
|
|
}
|
|
pub fn snapshot(&self) -> Snapshot {
|
|
let s = self.0.lock().unwrap();
|
|
Snapshot {
|
|
queued: s.pending.len(),
|
|
active: s.active.len(),
|
|
workers: s
|
|
.workers
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, w)| WorkerStatus {
|
|
id: w.id.clone(),
|
|
ready: s.ready[i],
|
|
slots: w.slots,
|
|
active: s.active.values().filter(|v| **v == i).count(),
|
|
})
|
|
.collect(),
|
|
}
|
|
}
|
|
}
|
|
impl State {
|
|
fn available(&self, i: usize) -> bool {
|
|
let w = &self.workers[i];
|
|
if !self.ready[i] || self.active.values().filter(|v| **v == i).count() >= w.slots {
|
|
return false;
|
|
}
|
|
let group = &self.groups[&w.group];
|
|
let active: Vec<_> = self
|
|
.active
|
|
.values()
|
|
.map(|j| &self.workers[*j])
|
|
.filter(|v| v.group == w.group)
|
|
.collect();
|
|
let bytes: u128 = active.iter().map(|v| u128::from(v.request_bytes)).sum();
|
|
active.len() < group.slots
|
|
&& bytes + u128::from(w.request_bytes) <= u128::from(group.available_bytes)
|
|
}
|
|
fn dispatch(&mut self) {
|
|
let mut i = 0;
|
|
while i < self.pending.len() {
|
|
let p = &self.pending[i];
|
|
if p.tx.is_closed() || p.deadline <= Instant::now() {
|
|
let p = self.pending.remove(i).unwrap();
|
|
let _ = p.tx.send(Err(AdmissionError::Expired));
|
|
continue;
|
|
}
|
|
// Oldest eligible request first; unrelated blocked requests do not stall free workers.
|
|
let worker = p
|
|
.eligible
|
|
.iter()
|
|
.copied()
|
|
.filter(|j| self.available(*j))
|
|
.min_by_key(|j| self.active.values().filter(|v| **v == *j).count());
|
|
if let Some(worker) = worker {
|
|
let p = self.pending.remove(i).unwrap();
|
|
self.active.insert(p.id, worker);
|
|
if p.tx.send(Ok(worker)).is_err() {
|
|
self.active.remove(&p.id);
|
|
}
|
|
} else {
|
|
i += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn check_pool_bounds(
|
|
workers: &[Worker],
|
|
groups: &[ResourceGroup],
|
|
queue_limit: usize,
|
|
) -> Result<(), AdmissionError> {
|
|
if workers.is_empty()
|
|
|| workers.len() > 256
|
|
|| groups.is_empty()
|
|
|| queue_limit == 0
|
|
|| queue_limit > 4096
|
|
{
|
|
return Err(AdmissionError::Invalid);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The groups by id; a repeated id or an out-of-range slot count is invalid.
|
|
fn index_groups(
|
|
groups: Vec<ResourceGroup>,
|
|
) -> Result<HashMap<String, ResourceGroup>, AdmissionError> {
|
|
let count = groups.len();
|
|
let groups: HashMap<_, _> = groups.into_iter().map(|g| (g.id.clone(), g)).collect();
|
|
if groups.len() != count
|
|
|| groups
|
|
.values()
|
|
.any(|g| g.id.is_empty() || g.slots == 0 || g.slots > 4096)
|
|
{
|
|
return Err(AdmissionError::Invalid);
|
|
}
|
|
Ok(groups)
|
|
}
|
|
|
|
fn check_workers_fit_their_group(
|
|
workers: &[Worker],
|
|
groups: &HashMap<String, ResourceGroup>,
|
|
) -> Result<(), AdmissionError> {
|
|
let mut ids = std::collections::HashSet::new();
|
|
for w in workers {
|
|
if w.id.is_empty()
|
|
|| !ids.insert(&w.id)
|
|
|| w.slots == 0
|
|
|| w.slots > 4096
|
|
|| !groups
|
|
.get(&w.group)
|
|
.is_some_and(|g| w.request_bytes <= g.available_bytes)
|
|
{
|
|
return Err(AdmissionError::Invalid);
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|