Skip to main content

vitrify_cli/run/
pool.rs

1//! A counting pool of tokens: how a run bounds the commands it runs at once.
2//!
3//! `run.gate_jobs` is one pool for the whole process. Every ยง5 command and
4//! Verification row โ€” from any lane's gate, re-check or preflight โ€” holds a
5//! token while it runs, so however many lanes gate at once, the machine
6//! runs at most that many commands. How a command parallelizes inside
7//! itself is its project's business: the pool bounds the commands vitrify
8//! runs, and nothing more.
9//!
10//! Waiters are served by priority (higher first), then in the order they
11//! arrived: only the first in line takes a token. A token goes back when
12//! it is dropped โ€” on every path out of the code that took it, a panic
13//! included.
14
15use std::cmp::Reverse;
16use std::collections::BTreeSet;
17use std::sync::{Condvar, Mutex, MutexGuard};
18use std::time::Duration;
19
20/// How often a waiter that can be stopped looks at its stop condition.
21const POLL: Duration = Duration::from_millis(50);
22
23pub struct Pool {
24    size: usize,
25    state: Mutex<State>,
26    turn: Condvar,
27}
28
29#[derive(Default)]
30struct State {
31    /// Tokens out now.
32    held: usize,
33    /// The next arrival's ticket.
34    next: u64,
35    /// Who waits, in the order they are to be served.
36    waiting: BTreeSet<(Reverse<i64>, u64)>,
37}
38
39/// One token, held until it is dropped.
40pub struct Token<'a> {
41    pool: &'a Pool,
42}
43
44impl Drop for Token<'_> {
45    fn drop(&mut self) {
46        let mut s = self.pool.lock();
47        s.held = s.held.saturating_sub(1);
48        drop(s);
49        self.pool.turn.notify_all();
50    }
51}
52
53impl Pool {
54    /// A pool of `size` tokens (at least one), counted in memory.
55    pub fn new(size: usize) -> Pool {
56        Pool {
57            size: size.max(1),
58            state: Mutex::new(State::default()),
59            turn: Condvar::new(),
60        }
61    }
62
63    pub fn size(&self) -> usize {
64        self.size
65    }
66
67    /// Tokens out now.
68    pub fn held(&self) -> usize {
69        self.lock().held
70    }
71
72    /// Callers waiting for a token now.
73    pub fn waiting(&self) -> usize {
74        self.lock().waiting.len()
75    }
76
77    /// The state, even if a thread panicked holding the lock: the counts are
78    /// only ever changed whole, so what it holds is consistent.
79    fn lock(&self) -> MutexGuard<'_, State> {
80        self.state.lock().unwrap_or_else(|e| e.into_inner())
81    }
82
83    /// Wait for a token at `priority`.
84    pub fn take(&self, priority: i64) -> Token<'_> {
85        loop {
86            if let Some(token) = self.take_unless(priority, &|| false) {
87                return token;
88            }
89        }
90    }
91
92    /// Wait for a token at `priority`, giving up when `stop` says so (an
93    /// interrupted run does not queue for work it will not do).
94    pub fn take_unless(&self, priority: i64, stop: &dyn Fn() -> bool) -> Option<Token<'_>> {
95        let mut s = self.lock();
96        let me = (Reverse(priority), s.next);
97        s.next += 1;
98        s.waiting.insert(me);
99        // whoever was first in line may not be any more
100        self.turn.notify_all();
101        loop {
102            let first = s.waiting.first() == Some(&me);
103            if first && s.held < self.size {
104                s.waiting.remove(&me);
105                s.held += 1;
106                drop(s);
107                // the next in line may find a token free too
108                self.turn.notify_all();
109                return Some(Token { pool: self });
110            }
111            if stop() {
112                s.waiting.remove(&me);
113                drop(s);
114                // whoever was behind this waiter may now be first
115                self.turn.notify_all();
116                return None;
117            }
118            s = self
119                .turn
120                .wait_timeout(s, POLL)
121                .unwrap_or_else(|e| e.into_inner())
122                .0;
123        }
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use std::sync::Arc;
131    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
132    use std::time::Instant;
133
134    fn wait_until(what: &str, cond: impl Fn() -> bool) {
135        let deadline = Instant::now() + Duration::from_secs(10);
136        while !cond() {
137            assert!(Instant::now() < deadline, "timed out waiting for {what}");
138            std::thread::sleep(Duration::from_millis(1));
139        }
140    }
141
142    /// The tokens free now, counted by taking them all.
143    fn free(pool: &Pool) -> usize {
144        let mut taken = Vec::new();
145        while let Some(t) = pool.take_unless(0, &|| true) {
146            taken.push(t);
147        }
148        taken.len()
149    }
150
151    #[test]
152    fn never_more_than_its_size_at_once() {
153        let pool = Pool::new(3);
154        let now = AtomicUsize::new(0);
155        let most = AtomicUsize::new(0);
156        std::thread::scope(|s| {
157            for t in 0..8 {
158                let (pool, now, most) = (&pool, &now, &most);
159                s.spawn(move || {
160                    for _ in 0..40 {
161                        let _token = pool.take(t % 3);
162                        let n = now.fetch_add(1, Ordering::SeqCst) + 1;
163                        most.fetch_max(n, Ordering::SeqCst);
164                        std::thread::sleep(Duration::from_micros(200));
165                        now.fetch_sub(1, Ordering::SeqCst);
166                    }
167                });
168            }
169        });
170        assert_eq!(
171            most.load(Ordering::SeqCst),
172            3,
173            "the pool was filled, never overfilled"
174        );
175        assert_eq!(pool.held(), 0);
176        assert_eq!(pool.waiting(), 0);
177        assert_eq!(free(&pool), 3);
178    }
179
180    #[test]
181    fn served_by_priority_then_arrival() {
182        let pool = Pool::new(1);
183        let pool = Arc::new(pool);
184        let order = Arc::new(Mutex::new(Vec::new()));
185        let first = pool.take(0);
186        let mut threads = Vec::new();
187        // arrivals, in this order: who, priority
188        for (n, (who, priority)) in [("a", 0), ("b", 5), ("c", 0), ("d", 5), ("e", -1)]
189            .into_iter()
190            .enumerate()
191        {
192            let (pool2, order) = (Arc::clone(&pool), Arc::clone(&order));
193            threads.push(std::thread::spawn(move || {
194                let _token = pool2.take(priority);
195                order.lock().unwrap().push(who);
196            }));
197            // the next arrives only once this one is queued
198            wait_until("a waiter to queue", || pool.waiting() == n + 1);
199        }
200        drop(first);
201        for t in threads {
202            t.join().unwrap();
203        }
204        assert_eq!(*order.lock().unwrap(), ["b", "d", "a", "c", "e"]);
205    }
206
207    #[test]
208    fn a_token_goes_back_when_its_holder_panics() {
209        let pool = Pool::new(1);
210        let pool = Arc::new(pool);
211        let p = Arc::clone(&pool);
212        let died = std::thread::spawn(move || {
213            let _token = p.take(0);
214            panic!("a command runner fell over");
215        })
216        .join();
217        assert!(died.is_err());
218        assert_eq!(pool.held(), 0);
219        // and the pool still works: its lock is not left poisoned for good
220        let _again = pool.take(0);
221        assert_eq!(pool.held(), 1);
222    }
223
224    #[test]
225    fn a_waiter_told_to_stop_leaves_the_queue() {
226        let pool = Pool::new(1);
227        let held = pool.take(0);
228        assert!(pool.take_unless(0, &|| true).is_none());
229        assert_eq!(pool.waiting(), 0);
230        drop(held);
231        assert!(
232            pool.take_unless(0, &|| true).is_some(),
233            "a free token is taken at once"
234        );
235        assert_eq!(pool.held(), 0, "and given back when dropped");
236    }
237
238    #[test]
239    fn a_size_of_zero_is_one() {
240        let pool = Pool::new(0);
241        assert_eq!(pool.size(), 1);
242        let _one = pool.take(0);
243        assert!(pool.take_unless(0, &|| true).is_none());
244    }
245
246    #[test]
247    fn waiters_that_give_up_leave_no_token_behind() {
248        let pool = Pool::new(2);
249        // one waiter stopped while it waits in line, behind a full pool
250        let (a, b) = (pool.take(0), pool.take(0));
251        let stop = AtomicBool::new(false);
252        std::thread::scope(|s| {
253            let waiter = s.spawn(|| {
254                pool.take_unless(0, &|| stop.load(Ordering::SeqCst))
255                    .is_none()
256            });
257            wait_until("the waiter to queue", || pool.waiting() == 1);
258            stop.store(true, Ordering::SeqCst);
259            assert!(waiter.join().unwrap());
260        });
261        drop((a, b));
262        assert_eq!(free(&pool), 2);
263        // many, giving up at random while the tokens go round
264        std::thread::scope(|s| {
265            for t in 0..6u64 {
266                let pool = &pool;
267                s.spawn(move || {
268                    for i in 0..60u64 {
269                        let deadline =
270                            Instant::now() + Duration::from_micros((t * 7 + i) % 5 * 150);
271                        if let Some(_token) = pool.take_unless(0, &|| Instant::now() > deadline) {
272                            std::thread::sleep(Duration::from_micros(300));
273                        }
274                    }
275                });
276            }
277        });
278        assert_eq!(pool.waiting(), 0);
279        assert_eq!(free(&pool), 2, "every token back");
280    }
281}