Skip to main content

schedr_master/
discovery.rs

1//! DAG discovery on the master: reported hashes, parse jobs, uploaded parses and the DAG list.
2//!
3//! A worker reports each root's content hash (at registration and on every change); a hash
4//! with no stored parse for the worker's schedr version gets a parse job. Workers can report
5//! different hashes for a root (git-sync not everywhere yet): its **current** parse is that of
6//! the **newest code** an alive worker reports, newest meaning the hash workers **switched to
7//! most recently** (recorded in the database, so a master restart decides the same). A switch
8//! is a worker moving to **new code** (a hash not recorded yet) or **reverting** (to a hash
9//! recorded before the one it left), judged by its own move, not by the current hash (decision
10//! 113): a lagging worker catching up to a hash recorded later isn't one, and changes nothing.
11//! A hash never seen before is newest when first reported. Workers on a hash newer than the current one (its parse on its way) may run the
12//! root's tasks too: they have newer code still. Of that hash's parses, the one of the newest schedr version an alive worker
13//! reporting it has is used (so after an upgrade the new parse takes over once stored). A
14//! root no alive worker reports keeps its current parse.
15//!
16//! Each time a root's current parse changes, the DAG list is worked out again from every
17//! root's current parse ([`catalog::plan`]) and the changes are stored. Only the newest code
18//! runs (tasks go to workers on the current hash), so a worker on older code can't put a DAG
19//! in conflict (see archive/PROJECT.md, DAG ID conflicts).
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::sync::Arc;
23
24use jiff::Timestamp;
25use schedr_db::dags::{DagChange, NewParse, StoredParse};
26use schedr_db::{Database, DbError};
27use schedr_model::SchedrVersion;
28use schedr_model::connection::Registry;
29use schedr_model::runner::{ErrorSummary, ParsedFile};
30
31use crate::catalog::{self, Source};
32use crate::metrics::MasterMetrics;
33use crate::parse_jobs::{ParseAssignment, ParseJobs, ParseKey};
34use crate::quiet::{WakeReason, Wakes};
35use crate::validate::{Checks, validate_files};
36
37#[cfg(test)]
38mod tests;
39
40/// A parse result uploaded by a worker.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ParseUpload {
43    /// The worker that parsed it.
44    pub worker_id: String,
45    /// What was parsed.
46    pub key: ParseKey,
47    /// Its files.
48    pub files: Vec<ParsedFile>,
49    /// The secret storages the worker has configured; none when unknown (nothing checked).
50    pub secret_storages: Option<BTreeSet<String>>,
51}
52
53/// The master's view of DAG discovery.
54#[derive(Debug)]
55pub struct Discovery {
56    db: Database,
57    /// Marks waking the DAGs it defines anew.
58    wakes: Wakes,
59    master: SchedrVersion,
60    /// The master's message limit: a task whose output can't fit it is refused (B33).
61    max_message_size: usize,
62    /// `[notifications]`: DAGs' `notify=` is checked against it.
63    notifications: std::sync::Arc<crate::notifications::Notifications>,
64    jobs: ParseJobs,
65    /// What each alive worker last reported for each root.
66    reports: BTreeMap<String, BTreeMap<String, ParseKey>>,
67    /// Each root's current parse.
68    current: BTreeMap<String, Current>,
69    /// The hashes reported for each root when it was last decided (for the mixed-code
70    /// warning).
71    hashes: BTreeMap<String, BTreeSet<String>>,
72    /// When workers last switched to each hash of a root (read once per root, then kept).
73    switches: BTreeMap<String, BTreeMap<String, Timestamp>>,
74    /// The stored parses of each (root, hash) (read once, dropped when one is stored or no
75    /// worker reports the hash any more).
76    parses: BTreeMap<(String, String), Vec<StoredParse>>,
77    /// Each root's hashes whose workers may run its tasks: the current one, and newer ones
78    /// whose parse is on its way.
79    accepted: BTreeMap<String, BTreeSet<String>>,
80    /// Workers that take no parse jobs (draining or drained).
81    no_parse: BTreeSet<String>,
82    /// Each root's connections from its current parse (decision 174); a task's assignment
83    /// carries those it declares.
84    registries: BTreeMap<String, Arc<Registry>>,
85    /// The script roots each DAG root's current parse asked about (decision 304); a root
86    /// asking none isn't in it.
87    script_uses: ScriptUses,
88}
89
90/// The script roots each DAG root uses (decision 304), by DAG root.
91pub type ScriptUses = BTreeMap<String, BTreeSet<String>>;
92
93/// What discovery keeps in memory, copied by [`Discovery::memory`] to put back when the
94/// transaction its changes were part of rolls back (B91).
95#[derive(Debug, Clone)]
96pub struct Memory {
97    jobs: ParseJobs,
98    reports: BTreeMap<String, BTreeMap<String, ParseKey>>,
99    current: BTreeMap<String, Current>,
100    hashes: BTreeMap<String, BTreeSet<String>>,
101    switches: BTreeMap<String, BTreeMap<String, Timestamp>>,
102    parses: BTreeMap<(String, String), Vec<StoredParse>>,
103    accepted: BTreeMap<String, BTreeSet<String>>,
104    no_parse: BTreeSet<String>,
105    registries: BTreeMap<String, Arc<Registry>>,
106    script_uses: ScriptUses,
107}
108
109/// A root's current parse.
110#[derive(Debug, Clone, PartialEq, Eq)]
111struct Current {
112    parse_id: String,
113    content_hash: String,
114    schedr_version: Option<SchedrVersion>,
115}
116
117impl Discovery {
118    /// Counts parse jobs in `metrics`.
119    pub fn set_metrics(&mut self, metrics: MasterMetrics) {
120        self.jobs.set_metrics(metrics);
121    }
122
123    /// Wakes the DAGs it defines anew (a new version, or back) through `wakes`.
124    pub fn set_wakes(&mut self, wakes: Wakes) {
125        self.wakes = wakes;
126    }
127
128    /// Checks DAGs' `notify=` against `notifications`.
129    pub fn set_notifications(
130        &mut self,
131        notifications: std::sync::Arc<crate::notifications::Notifications>,
132    ) {
133        self.notifications = notifications;
134    }
135
136    /// Discovery refusing tasks whose output can't fit `bytes`, the master's message limit.
137    #[must_use]
138    pub const fn with_max_message_size(mut self, bytes: usize) -> Self {
139        self.max_message_size = bytes;
140        self
141    }
142
143    /// Discovery over a database, checking DAG JSON for a master of version `master`.
144    #[must_use]
145    pub fn new(db: Database, master: SchedrVersion, jobs: ParseJobs) -> Self {
146        Self {
147            db,
148            master,
149            max_message_size: crate::service::DEFAULT_MAX_MESSAGE_SIZE,
150            notifications: std::sync::Arc::default(),
151            jobs,
152            reports: BTreeMap::new(),
153            current: BTreeMap::new(),
154            hashes: BTreeMap::new(),
155            switches: BTreeMap::new(),
156            parses: BTreeMap::new(),
157            accepted: BTreeMap::new(),
158            no_parse: BTreeSet::new(),
159            registries: BTreeMap::new(),
160            script_uses: ScriptUses::new(),
161            wakes: Wakes::default(),
162        }
163    }
164
165    /// A copy of what discovery keeps in memory, for [`Self::restore`].
166    #[must_use]
167    pub fn memory(&self) -> Memory {
168        Memory {
169            jobs: self.jobs.clone(),
170            reports: self.reports.clone(),
171            current: self.current.clone(),
172            hashes: self.hashes.clone(),
173            switches: self.switches.clone(),
174            parses: self.parses.clone(),
175            accepted: self.accepted.clone(),
176            no_parse: self.no_parse.clone(),
177            registries: self.registries.clone(),
178            script_uses: self.script_uses.clone(),
179        }
180    }
181
182    /// Puts back a copy taken by [`Self::memory`]: the work since was rolled back.
183    pub fn restore(&mut self, memory: Memory) {
184        let Memory {
185            jobs,
186            reports,
187            current,
188            hashes,
189            switches,
190            parses,
191            accepted,
192            no_parse,
193            registries,
194            script_uses,
195        } = memory;
196        self.jobs = jobs;
197        self.reports = reports;
198        self.current = current;
199        self.hashes = hashes;
200        self.switches = switches;
201        self.parses = parses;
202        self.accepted = accepted;
203        self.no_parse = no_parse;
204        self.registries = registries;
205        self.script_uses = script_uses;
206    }
207
208    /// A worker drains (or is drained): it gets no parse jobs, and its unfinished ones go to
209    /// other workers that reported the same hash. Returns those assignments.
210    pub fn stop_parsing(&mut self, worker_id: &str, now: Timestamp) -> Vec<ParseAssignment> {
211        self.no_parse.insert(worker_id.to_owned());
212        self.jobs.worker_lost(worker_id, now)
213    }
214
215    /// A worker registers anew: its parse jobs are released ([`ParseJobs::release`]).
216    pub fn release_jobs(&mut self, worker_id: &str) -> Vec<ParseKey> {
217        self.jobs.release(worker_id)
218    }
219
220    /// The released jobs its registration didn't take back ([`ParseJobs::hand_out`]).
221    pub fn hand_out(&mut self, keys: &[ParseKey], now: Timestamp) -> Vec<ParseAssignment> {
222        self.jobs.hand_out(keys, now)
223    }
224
225    /// A worker takes parse jobs again (resumed, or registered anew): the hashes it reports
226    /// that have no parse yet are requested again. Returns the jobs it gets.
227    ///
228    /// # Errors
229    ///
230    /// [`DbError`] if reading fails.
231    pub async fn allow_parsing(
232        &mut self,
233        worker_id: &str,
234        now: Timestamp,
235    ) -> Result<Vec<ParseAssignment>, DbError> {
236        if !self.no_parse.remove(worker_id) {
237            return Ok(Vec::new());
238        }
239        let resumed = self.resume_parsing(worker_id, now).await;
240        if resumed.is_err() {
241            // Still drained, so a retry resumes it (B96); a job requested before the error
242            // expires and goes out again.
243            self.no_parse.insert(worker_id.to_owned());
244        }
245        resumed
246    }
247
248    /// The parse jobs of what `worker_id` reports, now that it takes them again.
249    async fn resume_parsing(
250        &mut self,
251        worker_id: &str,
252        now: Timestamp,
253    ) -> Result<Vec<ParseAssignment>, DbError> {
254        let keys: Vec<ParseKey> = self
255            .reports
256            .get(worker_id)
257            .map(|roots| roots.values().cloned().collect())
258            .unwrap_or_default();
259        let mut jobs = Vec::new();
260        for key in keys {
261            let found = self
262                .db
263                .find_parse(&key.root, &key.content_hash, &key.schedr_version)
264                .await?;
265            match found {
266                // No parse yet, or a retry planned (decision 72.2).
267                None => jobs.extend(self.jobs.request(key, worker_id, now)),
268                Some(_) if self.jobs.has(&key) => {
269                    jobs.extend(self.jobs.request(key, worker_id, now));
270                }
271                // A parse that failed transiently, its retry unknown to a master restarted
272                // while the worker was drained.
273                Some(parse_id) => self.plan_stored_retry(key, &parse_id, now).await?,
274            }
275        }
276        Ok(jobs)
277    }
278
279    /// Each root's current content hash, the hashes whose workers may run its tasks (the
280    /// current one and newer ones whose parse is on its way), and the schedr version of the
281    /// current parse (workers older than that don't get its tasks).
282    pub fn current_code(
283        &self,
284    ) -> impl Iterator<Item = (&str, &str, &BTreeSet<String>, Option<SchedrVersion>)> {
285        self.current.iter().filter_map(|(root, c)| {
286            let accepted = self.accepted.get(root)?;
287            Some((
288                root.as_str(),
289                c.content_hash.as_str(),
290                accepted,
291                c.schedr_version,
292            ))
293        })
294    }
295
296    /// The parse jobs not finished.
297    #[must_use]
298    pub const fn jobs(&self) -> &ParseJobs {
299        &self.jobs
300    }
301
302    /// The parse jobs, to hand out again when a worker is lost or a job times out.
303    pub const fn jobs_mut(&mut self) -> &mut ParseJobs {
304        &mut self.jobs
305    }
306
307    /// A worker registered and reported its roots: they replace what it reported before (a
308    /// root it no longer has stops counting), a change against its previous report can be a
309    /// switch. Returns the parse jobs to send it.
310    ///
311    /// # Errors
312    ///
313    /// [`DbError`] if reading or storing fails.
314    pub async fn registered(
315        &mut self,
316        worker_id: &str,
317        keys: Vec<ParseKey>,
318        now: Timestamp,
319    ) -> Result<Vec<ParseAssignment>, DbError> {
320        let previous = self.reports.remove(worker_id).unwrap_or_default();
321        let mut roots: BTreeSet<String> = previous.keys().cloned().collect();
322        // A root it no longer has: it can't parse its code any more (B97).
323        for (root, key) in &previous {
324            if !keys.iter().any(|k| &k.root == root) {
325                self.jobs.moved_away(key, worker_id, now);
326            }
327        }
328        let mut jobs = Vec::new();
329        for key in keys {
330            roots.insert(key.root.clone());
331            jobs.extend(
332                self.report(worker_id, previous.get(&key.root), key, now)
333                    .await?,
334            );
335        }
336        for root in &roots {
337            self.decide(root, now).await?;
338        }
339        Ok(jobs)
340    }
341
342    /// A worker withdrew a root (decision 303: a DAG root using a script root it lacks): it
343    /// neither parses it nor counts for its code any more, as if it had registered without it.
344    ///
345    /// # Errors
346    ///
347    /// [`DbError`] if reading or storing fails.
348    pub async fn root_withdrawn(
349        &mut self,
350        worker_id: &str,
351        root: &str,
352        now: Timestamp,
353    ) -> Result<(), DbError> {
354        let Some(key) = self
355            .reports
356            .get_mut(worker_id)
357            .and_then(|roots| roots.remove(root))
358        else {
359            return Ok(());
360        };
361        self.jobs.moved_away(&key, worker_id, now);
362        self.decide(root, now).await
363    }
364
365    /// A worker reported a root's content hash. Returns the parse job to send it, if the hash
366    /// needs one.
367    ///
368    /// # Errors
369    ///
370    /// [`DbError`] if reading or storing fails.
371    pub async fn root_reported(
372        &mut self,
373        worker_id: &str,
374        key: ParseKey,
375        now: Timestamp,
376    ) -> Result<Option<ParseAssignment>, DbError> {
377        let previous = self
378            .reports
379            .get(worker_id)
380            .and_then(|roots| roots.get(&key.root))
381            .cloned();
382        let root = key.root.clone();
383        let job = self.report(worker_id, previous.as_ref(), key, now).await?;
384        self.decide(&root, now).await?;
385        Ok(job)
386    }
387
388    /// Records a worker's report of a root (`previous`: what it reported before); returns the
389    /// parse job it needs, if any.
390    async fn report(
391        &mut self,
392        worker_id: &str,
393        previous: Option<&ParseKey>,
394        key: ParseKey,
395        now: Timestamp,
396    ) -> Result<Option<ParseAssignment>, DbError> {
397        // A switch: new code (a hash not recorded yet) or a revert (to a hash recorded before
398        // the one left). Moving to a hash recorded later is catching up, not a switch: after a
399        // restart a lagging worker reporting first would make its catch-up rank above the
400        // newest code (B102). Decided by the move itself, not by the current or the newest
401        // hash, which a worker leaving changes (decision 113).
402        let switch_times = self.switches_of(&key.root).await?;
403        let recorded = |hash: &String| switch_times.get(hash).map(|at| (*at, hash.clone()));
404        let switched = previous.is_some_and(|p| {
405            p.content_hash != key.content_hash
406                && match (recorded(&key.content_hash), recorded(&p.content_hash)) {
407                    (None, _) => true,
408                    (Some(to), Some(from)) => to < from,
409                    (Some(_), None) => false,
410                }
411        });
412        self.record_switch(&key.root, &key.content_hash, switched, now)
413            .await?;
414        // Its earlier code's job (a retry) can't be parsed by it any more.
415        if let Some(previous) = previous.filter(|p| **p != key) {
416            self.jobs.moved_away(previous, worker_id, now);
417        }
418        self.reports
419            .entry(worker_id.to_owned())
420            .or_default()
421            .insert(key.root.clone(), key.clone());
422        let found = self
423            .db
424            .find_parse(&key.root, &key.content_hash, &key.schedr_version)
425            .await?;
426        Ok(match found {
427            Some(_) if self.no_parse.contains(worker_id) => None,
428            // A retry planned (decision 72.2): one more worker that can take it.
429            Some(_) if self.jobs.has(&key) => self.jobs.request(key, worker_id, now),
430            Some(parse_id) => {
431                // After a master restart, a parse that failed transiently isn't planned again
432                // yet.
433                self.plan_stored_retry(key, &parse_id, now).await?;
434                None
435            }
436            None if self.no_parse.contains(worker_id) => {
437                self.jobs.wait(key);
438                None
439            }
440            None => self.jobs.request(key, worker_id, now),
441        })
442    }
443
444    /// A worker is gone (deregistered or lost): its reports no longer count.
445    ///
446    /// # Errors
447    ///
448    /// [`DbError`] if reading or storing fails.
449    pub async fn worker_gone(&mut self, worker_id: &str, now: Timestamp) -> Result<(), DbError> {
450        let Some(roots) = self.reports.remove(worker_id) else {
451            return Ok(());
452        };
453        for root in roots.keys() {
454            if let Err(error) = self.decide(root, now).await {
455                // Its reports back, so a retry (the next lease check) decides again (B42).
456                self.reports.insert(worker_id.to_owned(), roots);
457                return Err(error);
458            }
459        }
460        Ok(())
461    }
462
463    /// Plans the retry of a stored parse with files that failed transiently, unknown to this
464    /// master (it restarted): it avoids the worker that parsed such a file, as stored with it
465    /// (decision 93), while another can take it.
466    async fn plan_stored_retry(
467        &mut self,
468        key: ParseKey,
469        parse_id: &str,
470        now: Timestamp,
471    ) -> Result<(), DbError> {
472        let files = self.db.parse_files(parse_id).await?;
473        let Some(failed) = files
474            .iter()
475            .find(|f| f.error.as_ref().is_some_and(ErrorSummary::is_transient))
476        else {
477            return Ok(());
478        };
479        let workers = self.db.parse_file_workers(parse_id).await?;
480        let candidates = self.candidates(&key);
481        let failed_on = workers.get(&failed.path).map(String::as_str);
482        self.jobs.retry(key, candidates, failed_on, now);
483        Ok(())
484    }
485
486    /// The workers that report `key` and take parse jobs.
487    fn candidates(&self, key: &ParseKey) -> BTreeSet<String> {
488        self.reports
489            .iter()
490            .filter(|(worker, roots)| {
491                !self.no_parse.contains(*worker) && roots.get(&key.root) == Some(key)
492            })
493            .map(|(worker, _)| worker.clone())
494            .collect()
495    }
496
497    /// Stores an uploaded parse (after validation) and finishes its job. If it is the parse of
498    /// the root's reported hash, it becomes current and the DAG list is updated. Returns the
499    /// stored parse's ID.
500    ///
501    /// When `key` has a stored parse, the upload is a **retry** (decision 72.2): it replaces
502    /// only the stored files that failed transiently, so a file that loaded once keeps its
503    /// result. Files that (still) failed transiently get another retry, after a delay.
504    ///
505    /// # Errors
506    ///
507    /// [`DbError`] if storing fails.
508    pub async fn parse_uploaded(
509        &mut self,
510        upload: ParseUpload,
511        now: Timestamp,
512    ) -> Result<String, DbError> {
513        let files = validate_files(
514            &upload.key.root,
515            upload.files,
516            &Checks {
517                master: self.master,
518                max_message_size: self.max_message_size,
519                secret_storages: upload.secret_storages.as_ref(),
520                notifications: Some(&self.notifications),
521            },
522        );
523        let key = &upload.key;
524        let stored = self
525            .db
526            .find_parse(&key.root, &key.content_hash, &key.schedr_version)
527            .await?;
528        let (parse_id, files, retry) = if let Some(parse_id) = stored {
529            let before = self.db.parse_files(&parse_id).await?;
530            let replaced = retried_files(&before, files);
531            self.db
532                .replace_parse_files(&parse_id, &replaced, &upload.worker_id, now)
533                .await?;
534            // A retry: the catalog is refreshed even when it replaced nothing, as a store
535            // that committed but reported an error (its acknowledgement lost) left it behind,
536            // and the same retry again finds nothing to replace (B100).
537            (parse_id, None, true)
538        } else {
539            let parse_id = self
540                .db
541                .insert_parse(&NewParse {
542                    root: &key.root,
543                    content_hash: &key.content_hash,
544                    schedr_version: &key.schedr_version,
545                    worker_id: &upload.worker_id,
546                    parsed_at: now,
547                    files: &files,
548                })
549                .await?;
550            (parse_id, Some(files), false)
551        };
552        let published = self
553            .publish(&upload.key, &upload.worker_id, &parse_id, files, retry, now)
554            .await;
555        if published.is_err() {
556            // Stored, but not taken into the catalog: the same upload again finds nothing
557            // new to store, so the root is decided afresh then, as when a refresh fails
558            // (B100).
559            self.current.remove(&upload.key.root);
560        }
561        published.map(|()| parse_id)
562    }
563
564    /// Takes a stored upload into the catalog: plans retries of what failed transiently,
565    /// decides the root and refreshes the DAG list, and finishes the job. `files` are the
566    /// parse's files, `None` to read them back (a retry's, merged with the stored ones).
567    async fn publish(
568        &mut self,
569        key: &ParseKey,
570        worker_id: &str,
571        parse_id: &str,
572        files: Option<Vec<ParsedFile>>,
573        retry: bool,
574        now: Timestamp,
575    ) -> Result<(), DbError> {
576        let files = match files {
577            Some(files) => files,
578            None => self.db.parse_files(parse_id).await?,
579        };
580        let failed: Vec<&str> = files
581            .iter()
582            .filter(|f| f.error.as_ref().is_some_and(ErrorSummary::is_transient))
583            .map(|f| f.path.as_str())
584            .collect();
585        if !failed.is_empty() {
586            let candidates = self.candidates(key);
587            self.jobs
588                .retry(key.clone(), candidates, Some(worker_id), now);
589            tracing::warn!(
590                root = key.root.as_str(),
591                content_hash = key.content_hash.as_str(),
592                worker_id,
593                files = failed.join(", "),
594                "files failed to import transiently (a timeout or a runner that died): parsed \
595                 again later; their DAGs keep their last good version meanwhile, so a file \
596                 that keeps failing doesn't take effect (see the import errors)"
597            );
598        }
599        self.parses
600            .remove(&(key.root.clone(), key.content_hash.clone()));
601        self.decide(&key.root, now).await?;
602        // A retry changes the files of a parse that may already be current: `decide` sees no
603        // new parse then.
604        if retry
605            && self
606                .current
607                .get(&key.root)
608                .is_some_and(|c| c.parse_id == parse_id)
609        {
610            self.refresh_or_forget(&key.root, now).await?;
611        }
612        // Only now: a catalog that couldn't be updated leaves the job to expire and the code
613        // to be parsed again (B94).
614        if failed.is_empty() {
615            self.jobs.finish(key);
616        }
617        Ok(())
618    }
619
620    /// Works out the DAG list from every root's current parse and stores the changes.
621    /// Returns them.
622    ///
623    /// # Errors
624    ///
625    /// [`DbError`] if reading or storing fails.
626    pub async fn refresh(&mut self, now: Timestamp) -> Result<Vec<DagChange>, DbError> {
627        // Every root's current parse: a root no worker reported since this master started
628        // keeps its stored one, so its DAGs still count (a conflict with them stays, B92).
629        let mut current = self.db.current_parses().await?;
630        for (root, c) in &self.current {
631            current.insert(root.clone(), c.parse_id.clone());
632        }
633        let mut sources = Vec::with_capacity(current.len());
634        for (root, parse_id) in current {
635            sources.push(Source {
636                root,
637                files: self.db.parse_files(&parse_id).await?,
638                parse_id,
639            });
640        }
641        let changes = catalog::plan(&sources, &self.db.stored_dags().await?);
642        self.registries = sources
643            .iter()
644            .map(|source| (source.root.clone(), Arc::new(Registry::of(&source.files))))
645            .collect();
646        self.script_uses = sources
647            .iter()
648            .filter_map(|source| {
649                let used: BTreeSet<String> = source
650                    .files
651                    .iter()
652                    .flat_map(|file| file.script_roots.iter().cloned())
653                    .collect();
654                (!used.is_empty()).then(|| (source.root.clone(), used))
655            })
656            .collect();
657        if !changes.is_empty() {
658            self.db.apply_dag_changes(&changes, now).await?;
659            for change in &changes {
660                if let DagChange::Define { dag, .. } = change {
661                    self.wakes.wake(&dag.id, WakeReason::NewVersion);
662                }
663            }
664        }
665        Ok(changes)
666    }
667
668    /// Records a report of `root` at `hash` (a switch, or a first report).
669    async fn record_switch(
670        &mut self,
671        root: &str,
672        hash: &str,
673        switched: bool,
674        now: Timestamp,
675    ) -> Result<(), DbError> {
676        let recorded = self.switches_of(root).await?;
677        let known = recorded.contains_key(hash);
678        if switched || !known {
679            // Never before the root's latest switch, whatever the clock did (B93): the order
680            // of switches is the order the master saw them in.
681            let latest = recorded.values().max().copied();
682            let at = latest
683                .and_then(|t| t.checked_add(jiff::SignedDuration::from_micros(1)).ok())
684                .map_or(now, |after| after.max(now));
685            self.db.record_root_hash(root, hash, switched, at).await?;
686            self.switches
687                .entry(root.to_owned())
688                .or_default()
689                .insert(hash.to_owned(), at);
690        }
691        Ok(())
692    }
693
694    /// When workers last switched to each hash of `root`.
695    async fn switches_of(&mut self, root: &str) -> Result<&BTreeMap<String, Timestamp>, DbError> {
696        if !self.switches.contains_key(root) {
697            let stored = self.db.root_hash_switches(root).await?;
698            self.switches.insert(root.to_owned(), stored);
699        }
700        Ok(&self.switches[root])
701    }
702
703    /// The stored parses of (root, hash).
704    async fn parses_of(&mut self, root: &str, hash: &str) -> Result<&Vec<StoredParse>, DbError> {
705        let key = (root.to_owned(), hash.to_owned());
706        if !self.parses.contains_key(&key) {
707            let stored = self.db.parses_of(root, hash).await?;
708            self.parses.insert(key.clone(), stored);
709        }
710        Ok(&self.parses[&key])
711    }
712
713    /// Decides a root's current parse from what alive workers report (see the module's
714    /// documentation) and refreshes the DAG list if it changed.
715    async fn decide(&mut self, root: &str, now: Timestamp) -> Result<(), DbError> {
716        // Each reported hash, with the schedr versions of the workers reporting it.
717        let mut reported: BTreeMap<&str, BTreeSet<Option<SchedrVersion>>> = BTreeMap::new();
718        let mut by_hash: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
719        for (worker, roots) in &self.reports {
720            if let Some(key) = roots.get(root) {
721                reported
722                    .entry(&key.content_hash)
723                    .or_default()
724                    .insert(key.schedr_version.parse().ok());
725                by_hash.entry(&key.content_hash).or_default().push(worker);
726            }
727        }
728        if reported.is_empty() {
729            return Ok(());
730        }
731        let hashes: BTreeSet<String> = reported.keys().map(|h| (*h).to_owned()).collect();
732        if hashes.len() > 1 && self.hashes.get(root) != Some(&hashes) {
733            let detail: Vec<String> = by_hash
734                .iter()
735                .map(|(hash, workers)| format!("{hash} on {}", workers.join(", ")))
736                .collect();
737            tracing::warn!(
738                root,
739                "workers report {} code versions of the root ({}): its tasks go to the workers \
740                 with the newest",
741                hashes.len(),
742                detail.join("; ")
743            );
744        }
745        self.hashes.insert(root.to_owned(), hashes);
746        let reported: Vec<(String, BTreeSet<Option<SchedrVersion>>)> = reported
747            .into_iter()
748            .map(|(h, v)| (h.to_owned(), v))
749            .collect();
750        let switches = self.switches_of(root).await?.clone();
751        let mut newest: Option<(Option<Timestamp>, String, &StoredParse)> = None;
752        let mut parses = Vec::with_capacity(reported.len());
753        for (hash, _) in &reported {
754            parses.push(self.parses_of(root, hash).await?.clone());
755        }
756        for ((hash, versions), parses) in reported.iter().zip(&parses) {
757            let Some(parse) = usable(parses, versions) else {
758                continue;
759            };
760            let at = switches.get(hash).copied();
761            if newest.as_ref().is_none_or(|(t, h, _)| (at, hash) > (*t, h)) {
762                newest = Some((at, hash.clone(), parse));
763            }
764        }
765        // Parses of hashes nobody reports any more aren't needed.
766        self.parses
767            .retain(|(r, h), _| r != root || reported.iter().any(|(reported, _)| reported == h));
768        let Some((at, hash, parse)) = newest else {
769            return Ok(());
770        };
771        let accepted: BTreeSet<String> = reported
772            .iter()
773            .map(|(h, _)| h)
774            .filter(|h| **h == hash || switches.get(*h).copied() > at)
775            .cloned()
776            .collect();
777        self.accepted.insert(root.to_owned(), accepted);
778        let current = Current {
779            parse_id: parse.id.clone(),
780            content_hash: hash,
781            schedr_version: parse.schedr_version.parse().ok(),
782        };
783        if self.current.get(root) != Some(&current) {
784            // Written down for the API's import errors (decision 66).
785            self.db
786                .set_current_parse(root, &current.parse_id, now)
787                .await?;
788            self.current.insert(root.to_owned(), current);
789            self.refresh_or_forget(root, now).await?;
790        }
791        Ok(())
792    }
793
794    /// Each root's connections from its current parse, as Registry JSON (decision 174).
795    #[must_use]
796    pub const fn registries(&self) -> &BTreeMap<String, Arc<Registry>> {
797        &self.registries
798    }
799
800    /// The script roots each DAG root's current parse asked about (decision 304).
801    #[must_use]
802    pub const fn script_uses(&self) -> &ScriptUses {
803        &self.script_uses
804    }
805
806    /// The script roots alive workers report now.
807    #[must_use]
808    pub fn reported_script_roots(&self) -> BTreeSet<String> {
809        self.reports
810            .values()
811            .flat_map(BTreeMap::values)
812            .filter(|key| key.kind == schedr_proto::pb::RootKind::Script)
813            .map(|key| key.root.clone())
814            .collect()
815    }
816
817    /// Refreshes the catalog; if that fails, forgets `root`'s current parse, so the next
818    /// report of its code decides (and refreshes) again instead of finding nothing new.
819    async fn refresh_or_forget(&mut self, root: &str, now: Timestamp) -> Result<(), DbError> {
820        let refreshed = self.refresh(now).await;
821        if refreshed.is_err() {
822            self.current.remove(root);
823        }
824        refreshed.map(drop)
825    }
826}
827
828/// Of a retry's `files`, those that replace the stored ones (`before`): where the stored file
829/// failed transiently (or is missing), and the retry's result differs.
830fn retried_files(before: &[ParsedFile], files: Vec<ParsedFile>) -> Vec<ParsedFile> {
831    let before: BTreeMap<&str, &ParsedFile> = before.iter().map(|f| (f.path.as_str(), f)).collect();
832    files
833        .into_iter()
834        .filter(|file| match before.get(file.path.as_str()) {
835            None => true,
836            Some(old) => {
837                old.error.as_ref().is_some_and(ErrorSummary::is_transient)
838                    && (old.dags != file.dags
839                        || old.error != file.error
840                        || old.connections != file.connections)
841            }
842        })
843        .collect()
844}
845
846/// The parse to use of a hash's `parses`: the one of the newest schedr version among
847/// `versions` (those of the workers reporting the hash), else the newest one no newer than
848/// all of them; `None` when every parse is newer (the reporters' own parse is on its way).
849fn usable<'a>(
850    parses: &'a [StoredParse],
851    versions: &BTreeSet<Option<SchedrVersion>>,
852) -> Option<&'a StoredParse> {
853    let highest = versions.iter().flatten().max().copied();
854    let version = |p: &StoredParse| p.schedr_version.parse::<SchedrVersion>().ok();
855    let reported = parses
856        .iter()
857        .filter(|p| versions.contains(&version(p)))
858        .max_by_key(|p| version(p));
859    let older = || {
860        parses
861            .iter()
862            .filter(|p| version(p).is_some_and(|v| highest.is_none_or(|h| v <= h)))
863            .max_by_key(|p| version(p))
864    };
865    reported.or_else(older)
866}