Skip to main content

schedr_master/
parse_jobs.rs

1//! Parse jobs: each (root, content hash, schedr version) is parsed once, by one worker that
2//! reported it. A parse whose files failed **transiently** (a timeout, a runner that died) is
3//! parsed again (decision 72.2), after a delay that doubles with each retry up to
4//! [`MAX_RETRY_DELAY`], preferring another worker: without a limit, since the code may be fine.
5//!
6//! Jobs live in the master's memory: after a restart, workers report their hashes again and a
7//! hash with no stored parse gets a new job. A job whose worker is lost, or that isn't
8//! finished within the job timeout, goes to another worker that reported the same hash (see
9//! archive/PROJECT.md, DAG ID conflicts: no duplicate parsing).
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::time::{Duration, Instant};
13
14use jiff::Timestamp;
15use uuid::Uuid;
16
17use crate::metrics::MasterMetrics;
18
19#[cfg(test)]
20mod tests;
21
22/// How long a worker has for a parse job before it goes to another worker (or the same one
23/// again, if no other reported the hash).
24pub const PARSE_JOB_TIMEOUT: Duration = Duration::from_mins(10);
25
26/// The delay before the first retry of a parse that failed transiently.
27pub const FIRST_RETRY_DELAY: Duration = Duration::from_secs(30);
28
29/// The longest delay between two retries of a parse that keeps failing transiently.
30pub const MAX_RETRY_DELAY: Duration = Duration::from_mins(10);
31
32/// What a parse job parses.
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct ParseKey {
35    /// The root's kind: DAG files imported, or `schedr.toml` files read (M4.9).
36    pub kind: schedr_proto::pb::RootKind,
37    /// The root's name.
38    pub root: String,
39    /// The content hash.
40    pub content_hash: String,
41    /// The schedr version of the workers that reported it.
42    pub schedr_version: String,
43}
44
45/// A parse job given to a worker: what `AssignParse` sends.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct ParseAssignment {
48    /// The job's ID.
49    pub job_id: String,
50    /// The worker that parses it.
51    pub worker_id: String,
52    /// What it parses.
53    pub key: ParseKey,
54}
55
56#[derive(Debug, Clone)]
57struct Job {
58    id: String,
59    worker: Option<(String, Timestamp)>,
60    candidates: BTreeSet<String>,
61    /// When it was created (for its duration).
62    created: Instant,
63    /// A retry: not handed out before this time.
64    not_before: Option<Timestamp>,
65    /// A retry: the worker whose parse failed, the last one to get it if others can.
66    failed_on: Option<String>,
67    /// How many times the parse was retried (for the delay).
68    retries: u32,
69}
70
71/// The parse jobs not finished yet.
72#[derive(Debug, Clone)]
73pub struct ParseJobs {
74    timeout: Duration,
75    retry_first: Duration,
76    retry_max: Duration,
77    jobs: BTreeMap<ParseKey, Job>,
78    metrics: MasterMetrics,
79    /// Master time, which its timers count on (B228; see [`crate::clock`]).
80    steady: crate::clock::Steady,
81}
82
83impl ParseJobs {
84    /// No jobs, with the given job timeout.
85    #[must_use]
86    pub fn new(timeout: Duration) -> Self {
87        Self {
88            timeout,
89            retry_first: FIRST_RETRY_DELAY,
90            retry_max: MAX_RETRY_DELAY,
91            jobs: BTreeMap::new(),
92            metrics: MasterMetrics::default(),
93            steady: crate::clock::as_given,
94        }
95    }
96
97    /// Times these jobs on `steady` (production: [`crate::clock::monotonic`]).
98    pub fn set_steady(&mut self, steady: crate::clock::Steady) {
99        self.steady = steady;
100    }
101
102    /// These jobs, a failed one tried again after `first`, doubling up to `max`.
103    #[must_use]
104    pub const fn with_retry(mut self, first: Duration, max: Duration) -> Self {
105        self.retry_first = first;
106        self.retry_max = max;
107        self
108    }
109
110    /// Counts jobs and their durations in `metrics`.
111    pub fn set_metrics(&mut self, metrics: MasterMetrics) {
112        self.metrics = metrics;
113    }
114
115    /// A worker reported a hash with no stored parse: the job is created and given to it,
116    /// unless a job for the hash exists (the worker can then take it over later).
117    pub fn request(
118        &mut self,
119        key: ParseKey,
120        worker_id: &str,
121        now: Timestamp,
122    ) -> Option<ParseAssignment> {
123        let now = (self.steady)(now);
124        let metrics = &self.metrics;
125        let job = self
126            .jobs
127            .entry(key.clone())
128            .or_insert_with(|| new_job(metrics));
129        job.candidates.insert(worker_id.to_owned());
130        if job.worker.is_some() || job.not_before.is_some_and(|at| at > now) {
131            return None;
132        }
133        // A retry goes to another candidate than the worker that failed, if there is one: the
134        // round's expiry hands it out.
135        if job.failed_on.as_deref() == Some(worker_id) && job.candidates.len() > 1 {
136            return None;
137        }
138        job.worker = Some((worker_id.to_owned(), now));
139        Some(ParseAssignment {
140            job_id: job.id.clone(),
141            worker_id: worker_id.to_owned(),
142            key,
143        })
144    }
145
146    /// A worker that takes no parse jobs (draining) reported a hash with no stored parse: the
147    /// job exists, for the next worker that reports the hash to take.
148    pub fn wait(&mut self, key: ParseKey) {
149        let metrics = &self.metrics;
150        self.jobs.entry(key).or_insert_with(|| new_job(metrics));
151    }
152
153    /// The parse of `key` was stored (by any worker, under any job): its job is done.
154    /// Returns the finished job's ID, if there was one.
155    pub fn finish(&mut self, key: &ParseKey) -> Option<String> {
156        let job = self.jobs.remove(key)?;
157        self.metrics.parse_jobs_finished.inc();
158        self.metrics
159            .parse_duration
160            .observe(job.created.elapsed().as_secs_f64());
161        Some(job.id)
162    }
163
164    /// The stored parse of `key` has files that failed transiently (on `failed_on`, if known):
165    /// a retry is planned, for the `candidates` (the workers reporting the key), handed out by
166    /// [`Self::expire`] once its delay is over. A job of `key` is finished first.
167    pub fn retry(
168        &mut self,
169        key: ParseKey,
170        candidates: BTreeSet<String>,
171        failed_on: Option<&str>,
172        now: Timestamp,
173    ) {
174        let now = (self.steady)(now);
175        // The first retry when the job failing wasn't one itself.
176        let retries = self
177            .jobs
178            .get(&key)
179            .filter(|job| job.not_before.is_some())
180            .map_or(0, |job| job.retries + 1);
181        self.finish(&key);
182        let delay = self
183            .retry_first
184            .saturating_mul(2_u32.saturating_pow(retries.min(16)))
185            .min(self.retry_max);
186        let delay = jiff::SignedDuration::try_from(delay).unwrap_or(jiff::SignedDuration::MAX);
187        let mut job = new_job(&self.metrics);
188        job.candidates = candidates;
189        job.not_before = Some(now.saturating_add(delay).unwrap_or(Timestamp::MAX));
190        job.failed_on = failed_on.map(str::to_owned);
191        job.retries = retries;
192        self.jobs.insert(key, job);
193    }
194
195    /// A worker reports other code than `key` now: it can't parse `key` any more.
196    /// If the job was its, it is handed out again at the next round ([`Self::expire`]); the
197    /// agent drops a job for code it no longer has, without an answer.
198    pub fn moved_away(&mut self, key: &ParseKey, worker_id: &str, now: Timestamp) {
199        let now = (self.steady)(now);
200        let Some(job) = self.jobs.get_mut(key) else {
201            return;
202        };
203        job.candidates.remove(worker_id);
204        // A first parse nobody reports any more isn't needed; a retry waits for a reporter.
205        if job.candidates.is_empty() && job.not_before.is_none() {
206            self.jobs.remove(key);
207            return;
208        }
209        if job.worker.as_ref().is_some_and(|(w, _)| w == worker_id) {
210            job.worker = None;
211            job.not_before = Some(job.not_before.map_or(now, |at| at.min(now)));
212        }
213    }
214
215    /// A worker opened a new stream: the agent drops a result its old one can't carry, so
216    /// none of its jobs is its any more (B235: they waited for the timeout). Returns their
217    /// keys, for [`Self::hand_out`] once its reports on the new stream are in.
218    pub fn release(&mut self, worker_id: &str) -> Vec<ParseKey> {
219        let mut released = Vec::new();
220        for (key, job) in &mut self.jobs {
221            if job.worker.as_ref().is_some_and(|(w, _)| w == worker_id) {
222                job.worker = None;
223                released.push(key.clone());
224            }
225        }
226        released
227    }
228
229    /// Released jobs no report took back (the worker drained, or reporting other code): each
230    /// goes to its next candidate; a first parse nobody reports any more is dropped.
231    pub fn hand_out(&mut self, keys: &[ParseKey], now: Timestamp) -> Vec<ParseAssignment> {
232        let now = (self.steady)(now);
233        let mut assignments = Vec::new();
234        for key in keys {
235            let Some(job) = self.jobs.get_mut(key) else {
236                continue;
237            };
238            if job.worker.is_some() || job.not_before.is_some_and(|at| at > now) {
239                continue;
240            }
241            match next_candidate(job) {
242                Some(next) => assignments.push(assign(key, job, next, now)),
243                None if job.not_before.is_none() => {
244                    self.jobs.remove(key);
245                }
246                None => {}
247            }
248        }
249        assignments
250    }
251
252    /// Whether `key` has a job (a retry included).
253    #[must_use]
254    pub fn has(&self, key: &ParseKey) -> bool {
255        self.jobs.contains_key(key)
256    }
257
258    /// A worker is gone: it is no longer a candidate, and its jobs go to other candidates
259    /// (or wait for one).
260    pub fn worker_lost(&mut self, worker_id: &str, now: Timestamp) -> Vec<ParseAssignment> {
261        let now = (self.steady)(now);
262        let mut assignments = Vec::new();
263        for (key, job) in &mut self.jobs {
264            job.candidates.remove(worker_id);
265            if job.worker.as_ref().is_some_and(|(w, _)| w == worker_id) {
266                job.worker = None;
267                if let Some(next) = next_candidate(job) {
268                    assignments.push(assign(key, job, next, now));
269                }
270            }
271        }
272        // A retry waits for a worker reporting its hash (one resumed, or registered again).
273        self.jobs
274            .retain(|_, job| !job.candidates.is_empty() || job.not_before.is_some());
275        assignments
276    }
277
278    /// Jobs not finished within the timeout go to the next candidate after their worker (the
279    /// same worker if it is the only one); retries whose delay is over go to a candidate other
280    /// than the worker that failed, if there is one.
281    pub fn expire(&mut self, now: Timestamp) -> Vec<ParseAssignment> {
282        let now = (self.steady)(now);
283        let mut assignments = Vec::new();
284        for (key, job) in &mut self.jobs {
285            let Some((worker, since)) = &job.worker else {
286                if job.not_before.is_some_and(|at| at <= now)
287                    && let Some(next) = next_candidate(job)
288                {
289                    assignments.push(assign(key, job, next, now));
290                }
291                continue;
292            };
293            if now.duration_since(*since).unsigned_abs() < self.timeout {
294                continue;
295            }
296            // The candidates after its worker in turn; a retry passes over the worker whose
297            // parse failed while another can take it.
298            let in_turn: Vec<&String> = job
299                .candidates
300                .range::<String, _>((
301                    std::ops::Bound::Excluded(worker),
302                    std::ops::Bound::Unbounded,
303                ))
304                .chain(job.candidates.iter())
305                .collect();
306            let next = in_turn
307                .iter()
308                .find(|c| job.failed_on.as_ref() != Some(**c))
309                .or_else(|| in_turn.first())
310                .map_or_else(|| worker.clone(), |c| (*c).clone());
311            assignments.push(assign(key, job, next, now));
312        }
313        assignments
314    }
315
316    /// The number of jobs not finished.
317    #[must_use]
318    pub fn len(&self) -> usize {
319        self.jobs.len()
320    }
321
322    /// Whether every job is finished.
323    #[must_use]
324    pub fn is_empty(&self) -> bool {
325        self.jobs.is_empty()
326    }
327}
328
329fn assign(key: &ParseKey, job: &mut Job, worker: String, now: Timestamp) -> ParseAssignment {
330    job.worker = Some((worker.clone(), now));
331    ParseAssignment {
332        job_id: job.id.clone(),
333        worker_id: worker,
334        key: key.clone(),
335    }
336}
337
338/// The candidate a job goes to: one other than the worker whose parse failed, if there is one.
339fn next_candidate(job: &Job) -> Option<String> {
340    job.candidates
341        .iter()
342        .find(|c| job.failed_on.as_ref() != Some(*c))
343        .or_else(|| job.candidates.iter().next())
344        .cloned()
345}
346
347/// A new job, counted in `metrics`.
348fn new_job(metrics: &MasterMetrics) -> Job {
349    metrics.parse_jobs_started.inc();
350    Job {
351        id: Uuid::now_v7().to_string(),
352        worker: None,
353        candidates: BTreeSet::new(),
354        created: Instant::now(),
355        not_before: None,
356        failed_on: None,
357        retries: 0,
358    }
359}