Skip to main content

weirdnet_agent/remote/infer/
queue.rs

1//! Admission: how many requests a node runs at once, and a priority queue for the rest.
2
3use std::collections::BTreeSet;
4use std::sync::{Arc, Mutex, MutexGuard};
5use std::time::Duration;
6
7use tokio::sync::watch;
8
9use super::v2::Priority;
10use crate::remote::RemoteError;
11
12/// How many requests a node serves at once, and how many more may wait their turn.
13///
14/// Infer/1 never waits: with every slot taken it answers `Busy` so the asker moves on. Infer/2
15/// requests wait in a priority queue (`interactive` before `batch` before `background`, first
16/// come first served within a class) and are told their place with `Queued` frames; only when
17/// the queue is full too is the answer `Busy`. Both protocols share the same slots.
18#[derive(Clone)]
19pub struct Admission {
20    inner: Arc<Inner>,
21}
22
23struct Inner {
24    state: Mutex<State>,
25    changed: watch::Sender<u64>,
26}
27
28struct State {
29    free: usize,
30    max_waiting: usize,
31    waiting: BTreeSet<(u8, u64)>,
32    next_seq: u64,
33    generation: u64,
34}
35
36fn rank(p: Priority) -> u8 {
37    match p {
38        Priority::Interactive => 0,
39        Priority::Batch => 1,
40        Priority::Background => 2,
41    }
42}
43
44impl Admission {
45    /// `max_concurrent` slots and no queue.
46    pub fn new(max_concurrent: usize) -> Self {
47        Self::with_queue(max_concurrent, 0)
48    }
49
50    /// `max_concurrent` slots and up to `max_waiting` infer/2 requests waiting for one.
51    pub fn with_queue(max_concurrent: usize, max_waiting: usize) -> Self {
52        let state = State { free: max_concurrent, max_waiting, waiting: BTreeSet::new(), next_seq: 0, generation: 0 };
53        Self { inner: Arc::new(Inner { state: Mutex::new(state), changed: watch::channel(0).0 }) }
54    }
55
56    fn lock(&self) -> MutexGuard<'_, State> {
57        self.inner.state.lock().unwrap_or_else(|e| e.into_inner())
58    }
59
60    /// Infer/2 requests waiting for a slot now.
61    pub fn waiting(&self) -> usize {
62        self.lock().waiting.len()
63    }
64
65    /// Free slots now.
66    pub fn free(&self) -> usize {
67        self.lock().free
68    }
69
70    /// A slot now, without queueing (infer/1). Never jumps ahead of waiting requests.
71    pub(crate) fn try_take(&self) -> Option<Permit> {
72        let mut s = self.lock();
73        if s.free == 0 || !s.waiting.is_empty() {
74            return None;
75        }
76        s.free -= 1;
77        Some(Permit { inner: self.inner.clone() })
78    }
79
80    /// Joins the queue (infer/2). `Busy` when every slot is taken and the queue is full.
81    pub fn enter(&self, priority: Priority) -> Result<Ticket, RemoteError> {
82        let mut s = self.lock();
83        if s.free == 0 && s.waiting.len() >= s.max_waiting {
84            return Err(RemoteError::Busy);
85        }
86        let key = (rank(priority), s.next_seq);
87        s.next_seq += 1;
88        s.waiting.insert(key);
89        s.generation += 1;
90        drop(s);
91        self.inner.changed.send_replace(0);
92        Ok(Ticket { inner: self.inner.clone(), key, done: false })
93    }
94}
95
96impl Inner {
97    fn bump(&self, s: &mut State) {
98        s.generation += 1;
99        let g = s.generation;
100        self.changed.send_replace(g);
101    }
102}
103
104/// A running request's slot; dropping it frees the slot for the next one in the queue.
105pub struct Permit {
106    inner: Arc<Inner>,
107}
108
109impl Drop for Permit {
110    fn drop(&mut self) {
111        let mut s = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
112        s.free += 1;
113        self.inner.bump(&mut s);
114    }
115}
116
117/// A place in the queue. Dropping it leaves the queue.
118pub struct Ticket {
119    inner: Arc<Inner>,
120    key: (u8, u64),
121    done: bool,
122}
123
124/// What [`Ticket::turn`] found.
125pub enum Turn {
126    /// A slot is ours.
127    Go(Permit),
128    /// Still waiting, at this place (1 = next).
129    Waiting(u32),
130}
131
132impl Ticket {
133    /// The place in the queue (1 = next).
134    pub fn position(&self) -> u32 {
135        let s = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
136        s.waiting.range(..self.key).count() as u32 + 1
137    }
138
139    /// Waits until a slot is ours or the place changes from `last`; after `keepalive` with no
140    /// change it reports the same place again (each `Queued` frame resets the asker's timer).
141    pub async fn turn(&mut self, last: Option<u32>, keepalive: Duration) -> Turn {
142        loop {
143            let mut rx = {
144                let mut s = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
145                if s.free > 0 && s.waiting.first() == Some(&self.key) {
146                    s.waiting.remove(&self.key);
147                    s.free -= 1;
148                    self.done = true;
149                    self.inner.bump(&mut s);
150                    return Turn::Go(Permit { inner: self.inner.clone() });
151                }
152                let pos = s.waiting.range(..self.key).count() as u32 + 1;
153                if last != Some(pos) {
154                    return Turn::Waiting(pos);
155                }
156                self.inner.changed.subscribe()
157            };
158            tokio::select! {
159                _ = rx.changed() => {}
160                _ = tokio::time::sleep(keepalive) => return Turn::Waiting(self.position()),
161            }
162        }
163    }
164}
165
166impl Drop for Ticket {
167    fn drop(&mut self) {
168        if !self.done {
169            let mut s = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
170            s.waiting.remove(&self.key);
171            self.inner.bump(&mut s);
172        }
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    const K: Duration = Duration::from_secs(60);
181
182    #[tokio::test]
183    async fn interactive_goes_before_batch_and_places_move_up() {
184        let a = Admission::with_queue(1, 8);
185        let mut first = a.enter(Priority::Batch).unwrap();
186        let Turn::Go(running) = first.turn(None, K).await else { panic!("a free slot") };
187        let mut batch = a.enter(Priority::Batch).unwrap();
188        let mut background = a.enter(Priority::Background).unwrap();
189        let mut chat = a.enter(Priority::Interactive).unwrap();
190        assert_eq!((chat.position(), batch.position(), background.position()), (1, 2, 3));
191        assert!(matches!(batch.turn(None, K).await, Turn::Waiting(2)));
192        drop(running);
193        let Turn::Go(p) = chat.turn(None, K).await else { panic!("chat is next") };
194        assert!(matches!(batch.turn(Some(2), K).await, Turn::Waiting(1)));
195        drop(p);
196        assert!(matches!(batch.turn(Some(1), K).await, Turn::Go(_)));
197        assert!(matches!(background.turn(None, K).await, Turn::Go(_)));
198    }
199
200    #[tokio::test]
201    async fn a_full_queue_is_busy_and_leaving_frees_the_place() {
202        let a = Admission::with_queue(1, 1);
203        let _running = a.try_take().unwrap();
204        let waiter = a.enter(Priority::Interactive).unwrap();
205        assert!(matches!(a.enter(Priority::Interactive), Err(RemoteError::Busy)));
206        assert!(a.try_take().is_none());
207        drop(waiter);
208        assert_eq!(a.waiting(), 0);
209        assert!(a.enter(Priority::Interactive).is_ok());
210    }
211
212    #[tokio::test(start_paused = true)]
213    async fn the_same_place_is_repeated_after_the_keepalive() {
214        let a = Admission::with_queue(1, 4);
215        let _running = a.try_take().unwrap();
216        let mut t = a.enter(Priority::Batch).unwrap();
217        assert!(matches!(t.turn(None, Duration::from_secs(3)).await, Turn::Waiting(1)));
218        assert!(matches!(t.turn(Some(1), Duration::from_secs(3)).await, Turn::Waiting(1)));
219    }
220}