Skip to main content

schedr_master/
quiet.rs

1//! Which DAGs a scheduler round visits (decision 485; first "Quiet DAGs", archive/PROJECT.md).
2//!
3//! A round visits the scheduled DAGs whose stored next fire time (`dag_triggers.next_fire_at`)
4//! has come or isn't known, the DAGs with queued runs, and those a mark woke (a command, a run
5//! queued or ended, a new version): the database says which, through the round's probe, and
6//! nothing about a DAG is kept in memory to decide it. The rest are **quiet**: not visited.
7//! A term's first round visits every DAG, and every round does with `[master] quiet_dags` off.
8//! Visiting a DAG that didn't need it creates nothing (a scheduled run is unique per
9//! `planned_for`), so a needless visit costs time, never runs.
10
11use std::collections::{HashMap, HashSet};
12use std::sync::{Arc, Mutex, PoisonError};
13
14use schedr_model::DagId;
15
16use crate::metrics::MasterMetrics;
17
18#[cfg(test)]
19mod tests;
20
21/// The `[master] quiet_dags` setting.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct QuietSettings {
24    /// Whether rounds visit only the DAGs with something due; `false` visits every DAG every
25    /// round.
26    pub enabled: bool,
27}
28
29impl Default for QuietSettings {
30    /// On.
31    fn default() -> Self {
32        Self { enabled: true }
33    }
34}
35
36/// Why a DAG was visited.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum WakeReason {
39    /// Its stored next fire time has come.
40    Timer,
41    /// Its next fire time isn't known yet (a new version, a switch changed).
42    Unknown,
43    /// A command about it (trigger, pause, unpause).
44    Command,
45    /// A run of it is queued (manual, chained, event, backfill).
46    RunQueued,
47    /// A run of it ended (a queued one may take its place).
48    RunEnded,
49    /// A new version of it, or it came back.
50    NewVersion,
51}
52
53impl WakeReason {
54    /// The name in metrics.
55    #[must_use]
56    pub const fn as_str(self) -> &'static str {
57        match self {
58            Self::Timer => "timer",
59            Self::Unknown => "unknown",
60            Self::Command => "command",
61            Self::RunQueued => "run_queued",
62            Self::RunEnded => "run_ended",
63            Self::NewVersion => "new_version",
64        }
65    }
66}
67
68/// The marks from what changes a DAG, taken by the next round (shared by clones).
69#[derive(Debug, Clone, Default)]
70pub struct Wakes(Arc<Mutex<HashMap<DagId, WakeReason>>>);
71
72impl Wakes {
73    /// Marks `dag` for the next round (the first reason kept).
74    pub fn wake(&self, dag: &DagId, reason: WakeReason) {
75        self.0
76            .lock()
77            .unwrap_or_else(PoisonError::into_inner)
78            .entry(dag.clone())
79            .or_insert(reason);
80    }
81
82    /// The marks so far, cleared.
83    pub(crate) fn take(&self) -> HashMap<DagId, WakeReason> {
84        std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner))
85    }
86}
87
88/// What a round visits.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum Visit {
91    /// Every DAG.
92    All,
93    /// These DAGs only (sorted).
94    Some(Vec<DagId>),
95}
96
97/// What a visit found of a DAG.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub struct Visited<'a> {
100    /// Why it is held, when its file failed (decision 72): [`schedr_db::runs::Held::reason`].
101    pub held: Option<&'a str>,
102}
103
104/// The DAGs a round visits, and what is logged and counted of them.
105#[derive(Debug)]
106pub struct QuietDags {
107    settings: QuietSettings,
108    /// The DAGs that can run, as last seen: for the count of quiet ones.
109    known: HashSet<DagId>,
110    /// The DAGs held now (decision 72), to log a hold when it starts and when it lifts.
111    held: HashSet<DagId>,
112    /// Why each DAG of the current round was visited.
113    woken: HashMap<DagId, WakeReason>,
114    /// Whether this term's first round (every DAG) is done.
115    first_done: bool,
116    /// The current round's marks: put back if it fails.
117    marks: Option<HashMap<DagId, WakeReason>>,
118    wakes: Wakes,
119    metrics: MasterMetrics,
120}
121
122impl QuietDags {
123    /// No round done yet: the first visits every DAG.
124    #[must_use]
125    pub fn new(settings: QuietSettings, wakes: Wakes) -> Self {
126        Self {
127            settings,
128            known: HashSet::new(),
129            held: HashSet::new(),
130            woken: HashMap::new(),
131            first_done: false,
132            marks: None,
133            wakes,
134            metrics: MasterMetrics::default(),
135        }
136    }
137
138    /// Counts busy and quiet DAGs, and wakes, in `metrics`.
139    pub fn set_metrics(&mut self, metrics: MasterMetrics) {
140        self.metrics = metrics;
141    }
142
143    /// Whether rounds visit only the DAGs with something due (`[master] quiet_dags`).
144    #[must_use]
145    pub const fn enabled(&self) -> bool {
146        self.settings.enabled
147    }
148
149    /// What the round visits: every DAG when off or in a term's first round; else `due` (the
150    /// DAGs the database found due, with why) and the marked ones.
151    pub fn round(&mut self, due: Vec<(DagId, WakeReason)>) -> Visit {
152        let marks = self.wakes.take();
153        self.woken.clear();
154        if !self.settings.enabled || !self.first_done {
155            self.marks = Some(marks);
156            return Visit::All;
157        }
158        for (dag, reason) in due {
159            self.woken.entry(dag).or_insert(reason);
160        }
161        for (dag, reason) in &marks {
162            self.woken.entry(dag.clone()).or_insert(*reason);
163        }
164        self.marks = Some(marks);
165        let mut visit: Vec<DagId> = self.woken.keys().cloned().collect();
166        visit.sort();
167        Visit::Some(visit)
168    }
169
170    /// The round failed (the database): its marks are put back, so the next round is as this
171    /// one would have been (a term's first round again visits every DAG).
172    pub fn round_failed(&mut self) {
173        if let Some(marks) = self.marks.take() {
174            for (dag, reason) in marks {
175                self.wakes.wake(&dag, reason);
176            }
177        }
178        self.woken.clear();
179    }
180
181    /// Notes what the round found of `dag`.
182    pub fn visited(&mut self, dag: &DagId, found: Visited<'_>) {
183        self.note_held(dag, found.held);
184        self.known.insert(dag.clone());
185        if let Some(reason) = self.woken.get(dag) {
186            self.metrics.dag_woken(reason.as_str());
187        }
188    }
189
190    /// Logs a DAG's hold when it starts and when it lifts (not every round).
191    fn note_held(&mut self, dag: &DagId, held: Option<&str>) {
192        match held {
193            Some(why) if self.held.insert(dag.clone()) => tracing::warn!(
194                dag_id = dag.as_str(),
195                why,
196                "DAG held (its file failed); no run is created or started until the file is fixed"
197            ),
198            None if self.held.remove(dag) => tracing::info!(
199                dag_id = dag.as_str(),
200                "DAG no longer held: its file imports again; missed fire times follow its \
201                 catchup setting"
202            ),
203            _ => {}
204        }
205    }
206
207    /// After a round: forgets the visited DAGs that can't run any more (removed, in
208    /// conflict), `seen` being those that can, and counts the visited (busy), the others
209    /// (quiet) and the held DAGs.
210    pub fn round_done(&mut self, visited: &Visit, seen: &HashSet<DagId>) {
211        self.marks = None;
212        self.first_done = true;
213        let busy = match visited {
214            Visit::All => {
215                self.known.retain(|dag| seen.contains(dag));
216                self.held.retain(|dag| seen.contains(dag));
217                seen.len()
218            }
219            Visit::Some(dags) => {
220                for dag in dags.iter().filter(|dag| !seen.contains(*dag)) {
221                    self.known.remove(dag);
222                    self.held.remove(dag);
223                }
224                seen.len()
225            }
226        };
227        let quiet = if self.settings.enabled {
228            self.known.len().saturating_sub(busy)
229        } else {
230            0
231        };
232        self.metrics.set_dags(busy, quiet, self.held.len());
233    }
234}