Skip to main content

schedr_master/
workers.rs

1//! The workers the master knows, their queues and slots, and the choice of a worker for a
2//! task (see archive/PROJECT.md, Task assignment).
3//!
4//! **Spread:** among the active workers serving the task's queue with a free slot, the one
5//! with the most free slots; ties go to the least recently assigned, then the worker ID. A
6//! worker with no queues configured serves the `default` queue. Slots count the attempts
7//! assigned to the worker and not yet finished.
8//!
9//! **Eligible** workers also have the task's root at its current hash (only the newest code
10//! runs) and a schedr version at least that of the parse the task's DAG version came from
11//! (see archive/PROJECT.md, Code versions and change detection, and Upgrades and compatibility).
12
13use std::collections::{BTreeMap, BTreeSet};
14
15use jiff::Timestamp;
16use schedr_model::SchedrVersion;
17
18#[cfg(test)]
19mod tests;
20
21/// The queue of tasks with no queue, served by workers with no queues configured.
22pub const DEFAULT_QUEUE: &str = "default";
23
24/// A worker's watcher slots until it says (`[watchers] slots`).
25pub const DEFAULT_WATCHER_SLOTS: u32 = 500;
26
27/// A worker's state as the master sees it.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum WorkerState {
30    /// Takes new tasks.
31    Active,
32    /// Finishing its tasks; takes no new ones.
33    Draining,
34}
35
36/// A registered worker.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Worker {
39    /// Its ID.
40    pub id: String,
41    /// The incarnation of its agent process.
42    pub incarnation: String,
43    /// The queues it serves.
44    pub queues: BTreeSet<String>,
45    /// Its task slots.
46    pub slots: u32,
47    /// Its slots for wait steps.
48    pub watcher_slots: u32,
49    /// Its state.
50    pub state: WorkerState,
51    /// The attempts assigned to it and not finished, on its task slots.
52    pub attempts: BTreeSet<String>,
53    /// The wait steps assigned to it and not finished, on its watcher slots.
54    pub wait_steps: BTreeSet<String>,
55    /// Those of them that are pokes: a drain moves them at once.
56    pub pokes: BTreeSet<String>,
57    /// When it was last given a task.
58    pub last_assigned: Option<Timestamp>,
59    /// Its schedr version, when known.
60    pub version: Option<SchedrVersion>,
61    /// The content hash it last reported for each root.
62    pub roots: BTreeMap<String, String>,
63    /// Drained for maintenance (`schedr workers drain`): no new tasks until resumed.
64    pub drained: bool,
65    /// Whether its stream is up: a connections job goes only to a worker that is.
66    pub connected: bool,
67}
68
69/// What a task needs of a worker.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct Needs<'a> {
72    /// Its queue.
73    pub queue: &'a str,
74    /// Its root and the hashes the worker must have it at (the root's current code, or newer
75    /// code whose parse is on its way), when known.
76    pub code: Option<(&'a str, &'a BTreeSet<String>)>,
77    /// The lowest schedr version that runs it, when known.
78    pub version: Option<SchedrVersion>,
79    /// A wait step: it takes a watcher slot.
80    pub wait_step: bool,
81}
82
83impl<'a> Needs<'a> {
84    /// Only a worker serving `queue`.
85    #[must_use]
86    pub const fn queue(queue: &'a str) -> Self {
87        Self {
88            queue,
89            code: None,
90            version: None,
91            wait_step: false,
92        }
93    }
94}
95
96impl Worker {
97    /// Whether its schedr version runs a task of a parse of `version` (an unknown version on
98    /// either side does).
99    #[must_use]
100    pub fn runs(&self, version: Option<SchedrVersion>) -> bool {
101        match (self.version, version) {
102            (Some(mine), Some(needed)) => mine >= needed,
103            _ => true,
104        }
105    }
106
107    /// Whether it has `root` at one of `hashes` (anything, when no code is asked for).
108    #[must_use]
109    pub fn has_code(&self, code: Option<(&str, &BTreeSet<String>)>) -> bool {
110        code.is_none_or(|(root, hashes)| self.roots.get(root).is_some_and(|h| hashes.contains(h)))
111    }
112
113    /// Whether it serves `queue`.
114    #[must_use]
115    pub fn serves(&self, queue: &str) -> bool {
116        self.queues.contains(queue)
117    }
118
119    /// Its free slots.
120    #[must_use]
121    pub fn free_slots(&self) -> u32 {
122        self.slots
123            .saturating_sub(u32::try_from(self.attempts.len()).unwrap_or(u32::MAX))
124    }
125
126    /// Its free watcher slots.
127    #[must_use]
128    pub fn free_watcher_slots(&self) -> u32 {
129        self.watcher_slots
130            .saturating_sub(u32::try_from(self.wait_steps.len()).unwrap_or(u32::MAX))
131    }
132
133    fn free_for(&self, needs: Needs<'_>) -> u32 {
134        if needs.wait_step {
135            self.free_watcher_slots()
136        } else {
137            self.free_slots()
138        }
139    }
140}
141
142/// The registered workers.
143#[derive(Debug, Clone, Default)]
144pub struct Workers {
145    workers: BTreeMap<String, Worker>,
146}
147
148impl Workers {
149    /// No workers.
150    #[must_use]
151    pub fn new() -> Self {
152        Self::default()
153    }
154
155    /// Registers a worker (or its new incarnation, which starts with no attempts). Returns
156    /// whether the set of workers changed (a new worker or a restart), which gives
157    /// `unschedulable` tasks another chance.
158    pub fn register(&mut self, id: &str, incarnation: &str, queues: &[String], slots: u32) -> bool {
159        let queues: BTreeSet<String> = if queues.is_empty() {
160            BTreeSet::from([DEFAULT_QUEUE.to_owned()])
161        } else {
162            queues.iter().cloned().collect()
163        };
164        if let Some(known) = self.workers.get_mut(id)
165            && known.incarnation == incarnation
166        {
167            known.queues = queues;
168            known.slots = slots;
169            known.state = WorkerState::Active;
170            known.connected = true;
171            // It reports its roots again right after.
172            known.roots.clear();
173            return false;
174        }
175        self.workers.insert(
176            id.to_owned(),
177            Worker {
178                id: id.to_owned(),
179                incarnation: incarnation.to_owned(),
180                queues,
181                slots,
182                watcher_slots: DEFAULT_WATCHER_SLOTS,
183                state: WorkerState::Active,
184                attempts: BTreeSet::new(),
185                wait_steps: BTreeSet::new(),
186                pokes: BTreeSet::new(),
187                last_assigned: None,
188                version: None,
189                roots: BTreeMap::new(),
190                drained: false,
191                connected: true,
192            },
193        );
194        true
195    }
196
197    /// Drains a worker for maintenance, or resumes it.
198    pub fn set_drained(&mut self, id: &str, drained: bool) {
199        if let Some(worker) = self.workers.get_mut(id) {
200            worker.drained = drained;
201        }
202    }
203
204    /// A worker's stream ended (it may come back, see [`Self::register`]).
205    pub fn disconnected(&mut self, id: &str) {
206        if let Some(worker) = self.workers.get_mut(id) {
207            worker.connected = false;
208        }
209    }
210
211    /// Records a worker's schedr version.
212    pub fn set_version(&mut self, id: &str, version: Option<SchedrVersion>) {
213        if let Some(worker) = self.workers.get_mut(id) {
214            worker.version = version;
215        }
216    }
217
218    /// Records the content hash a worker reported for a root.
219    pub fn report_root(&mut self, id: &str, root: &str, hash: &str) {
220        if let Some(worker) = self.workers.get_mut(id) {
221            worker.roots.insert(root.to_owned(), hash.to_owned());
222        }
223    }
224
225    /// A worker withdrew a root (decision 303): it no longer has it.
226    pub fn withdraw_root(&mut self, id: &str, root: &str) {
227        if let Some(worker) = self.workers.get_mut(id) {
228            worker.roots.remove(root);
229        }
230    }
231
232    /// The worker stops taking new tasks.
233    pub fn draining(&mut self, id: &str) {
234        if let Some(worker) = self.workers.get_mut(id) {
235            worker.state = WorkerState::Draining;
236        }
237    }
238
239    /// Forgets a worker (deregistered or lost); returns it.
240    pub fn remove(&mut self, id: &str) -> Option<Worker> {
241        self.workers.remove(id)
242    }
243
244    /// A worker by ID.
245    #[must_use]
246    pub fn get(&self, id: &str) -> Option<&Worker> {
247        self.workers.get(id)
248    }
249
250    /// The active workers serving `queue` (not draining, not drained).
251    pub fn serving<'a>(&'a self, queue: &'a str) -> impl Iterator<Item = &'a Worker> + 'a {
252        self.workers
253            .values()
254            .filter(move |w| w.state == WorkerState::Active && !w.drained && w.serves(queue))
255    }
256
257    /// Whether an active worker drained for maintenance serves `queue`.
258    #[must_use]
259    pub fn drained_serving(&self, queue: &str) -> bool {
260        self.workers
261            .values()
262            .any(|w| w.state == WorkerState::Active && w.drained && w.serves(queue))
263    }
264
265    /// The active workers that can run a task with `needs`: serving its queue, with its code
266    /// and a recent enough version.
267    pub fn eligible<'a>(&'a self, needs: Needs<'a>) -> impl Iterator<Item = &'a Worker> + 'a {
268        self.serving(needs.queue)
269            .filter(move |w| w.runs(needs.version) && w.has_code(needs.code))
270    }
271
272    /// The worker to give a task with `needs` to, leaving out `excluded`; `None` when no
273    /// eligible worker has a free slot. Only a connected one: an assignment to a worker without
274    /// a stream would be dropped and wait for its return or loss (Grok's review of B240); one
275    /// disconnected still counts as eligible, so the task waits rather than being unschedulable.
276    #[must_use]
277    pub fn pick<'a>(&'a self, needs: Needs<'a>, excluded: &BTreeSet<String>) -> Option<&'a str> {
278        self.eligible(needs)
279            .filter(|w| w.connected && w.free_for(needs) > 0 && !excluded.contains(&w.id))
280            .min_by(|a, b| {
281                b.free_for(needs)
282                    .cmp(&a.free_for(needs))
283                    .then(a.last_assigned.cmp(&b.last_assigned))
284                    .then(a.id.cmp(&b.id))
285            })
286            .map(|w| w.id.as_str())
287    }
288
289    /// Every registered worker.
290    pub fn all(&self) -> impl Iterator<Item = &Worker> {
291        self.workers.values()
292    }
293
294    /// Takes a slot of `worker` for `attempt`.
295    pub fn reserve(&mut self, worker: &str, attempt: &str, now: Timestamp) {
296        if let Some(w) = self.workers.get_mut(worker) {
297            w.attempts.insert(attempt.to_owned());
298            w.last_assigned = Some(now);
299        }
300    }
301
302    /// Takes a watcher slot of `worker` for `attempt`.
303    pub fn reserve_wait_step(&mut self, worker: &str, attempt: &str, poke: bool, now: Timestamp) {
304        if let Some(w) = self.workers.get_mut(worker) {
305            w.wait_steps.insert(attempt.to_owned());
306            if poke {
307                w.pokes.insert(attempt.to_owned());
308            }
309            w.last_assigned = Some(now);
310        }
311    }
312
313    /// Sets a worker's watcher slots.
314    pub fn set_watcher_slots(&mut self, id: &str, slots: u32) {
315        if let Some(worker) = self.workers.get_mut(id) {
316            worker.watcher_slots = slots;
317        }
318    }
319
320    /// Frees the slot of `attempt`, wherever it is.
321    pub fn release(&mut self, attempt: &str) {
322        for worker in self.workers.values_mut() {
323            worker.attempts.remove(attempt);
324            worker.wait_steps.remove(attempt);
325            worker.pokes.remove(attempt);
326        }
327    }
328}