Files
leleka/desktop-core/src/pool.rs
T
Pavlo Ratushnyi 4013e0c9bd
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
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
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

241 lines
7.1 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> {
if workers.is_empty()
|| workers.len() > 256
|| groups.is_empty()
|| queue_limit == 0
|| queue_limit > 4096
{
return Err(AdmissionError::Invalid);
}
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);
}
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(Self(Arc::new(Mutex::new(State {
ready: vec![true; workers.len()],
workers,
groups,
pending: VecDeque::new(),
active: HashMap::new(),
next_id: 0,
queue_limit,
}))))
}
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 = {
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();
Lease {
pool: self.clone(),
id,
worker: 0,
}
};
// 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;
}
}
}
}