Skip to main content

schedr_master/
limits.rs

1//! Concurrency limits (see archive/PROJECT.md, Native API: Concurrency limits, decisions 87-91):
2//! `max_active_tasks` on a DAG, `max_active` and `max_active_per_run` on a task.
3//!
4//! The master counts the open attempts (assigned and not yet started, running, cleaning up) in
5//! memory, by DAG, by task and by a run's task (88A): read from the database once when it
6//! starts dispatching (one master holds the lease, its writes fenced), then kept as it assigns
7//! and as attempts end. Each instance of a mapped task counts (89). A task is checked as it
8//! is assigned; one whose limit is reached stays `queued`, saying which limit and its value.
9//!
10//! The limits across runs (`max_active_tasks`, `max_active`) are the DAG's current version's,
11//! `max_active_per_run` the run's own version's (87A).
12
13use std::collections::BTreeMap;
14
15use schedr_db::attempts::{ActiveAttempt, ReadyInstance};
16use schedr_model::{Dag, DagId, Task, TaskId};
17
18#[cfg(test)]
19mod tests;
20
21/// The open attempts, counted for the limits.
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct Active {
24    /// Whether they were read from the database (until then nothing is counted).
25    loaded: bool,
26    /// Each open attempt and what it counts toward.
27    attempts: BTreeMap<String, Holder>,
28    /// Open attempts per DAG, and per task of it.
29    dags: BTreeMap<DagId, Counted>,
30    /// Open attempts per run, by task.
31    runs: BTreeMap<String, BTreeMap<TaskId, u32>>,
32}
33
34/// What an open attempt counts toward.
35#[derive(Debug, Clone, PartialEq, Eq)]
36struct Holder {
37    dag: DagId,
38    run: String,
39    task: TaskId,
40}
41
42/// A DAG's open attempts: all of them, and by task.
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
44struct Counted {
45    all: u32,
46    tasks: BTreeMap<TaskId, u32>,
47}
48
49/// A limit reached: which one and its value.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Reached {
52    /// The limit's name, also the waiting metric's reason (decision 91).
53    pub name: &'static str,
54    /// Its value.
55    pub value: u32,
56}
57
58impl Reached {
59    /// The reason shown with the waiting task: "waiting: `max_active_per_run` (10) reached".
60    #[must_use]
61    pub fn reason(&self) -> String {
62        format!("waiting: `{}` ({}) reached", self.name, self.value)
63    }
64}
65
66impl Active {
67    /// Nothing counted, not read yet.
68    #[must_use]
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    /// Whether the open attempts were read (see [`Self::load`]).
74    #[must_use]
75    pub const fn is_loaded(&self) -> bool {
76        self.loaded
77    }
78
79    /// Counts exactly `attempts` (the database's open attempts), replacing what was counted.
80    pub fn load(&mut self, attempts: Vec<ActiveAttempt>) {
81        *self = Self::default();
82        for a in attempts {
83            self.add(&a.attempt_id, a.dag_id, a.run_id, a.task_id);
84        }
85        self.loaded = true;
86    }
87
88    /// Counts an attempt just assigned (once: again changes nothing).
89    pub fn add(&mut self, attempt_id: &str, dag_id: DagId, run_id: String, task_id: TaskId) {
90        if self.attempts.contains_key(attempt_id) {
91            return;
92        }
93        let dag = self.dags.entry(dag_id.clone()).or_default();
94        dag.all += 1;
95        *dag.tasks.entry(task_id.clone()).or_default() += 1;
96        *self
97            .runs
98            .entry(run_id.clone())
99            .or_default()
100            .entry(task_id.clone())
101            .or_default() += 1;
102        self.attempts.insert(
103            attempt_id.to_owned(),
104            Holder {
105                dag: dag_id,
106                run: run_id,
107                task: task_id,
108            },
109        );
110    }
111
112    /// Counts `attempt_id`, just assigned for `ready` (see [`Self::add`]).
113    pub fn assigned(&mut self, attempt_id: &str, ready: &ReadyInstance) {
114        let (dag, run, task) = (&ready.dag.id, &ready.run_id, &ready.task_id);
115        self.add(attempt_id, dag.clone(), run.clone(), task.clone());
116    }
117
118    /// An attempt ended or was taken back: it no longer counts (one not counted: nothing).
119    pub fn remove(&mut self, attempt_id: &str) {
120        let Some(holder) = self.attempts.remove(attempt_id) else {
121            return;
122        };
123        if let Some(dag) = self.dags.get_mut(&holder.dag) {
124            dag.all = dag.all.saturating_sub(1);
125            decrement(&mut dag.tasks, &holder.task);
126            if dag.all == 0 {
127                self.dags.remove(&holder.dag);
128            }
129        }
130        if let Some(run) = self.runs.get_mut(&holder.run) {
131            decrement(run, &holder.task);
132            if run.is_empty() {
133                self.runs.remove(&holder.run);
134            }
135        }
136    }
137
138    /// The DAG's open attempts.
139    #[must_use]
140    pub fn of_dag(&self, dag_id: &DagId) -> u32 {
141        self.dags.get(dag_id).map_or(0, |d| d.all)
142    }
143
144    /// The task's open attempts across the DAG's runs.
145    #[must_use]
146    pub fn of_task(&self, dag_id: &DagId, task_id: &TaskId) -> u32 {
147        self.dags
148            .get(dag_id)
149            .and_then(|d| d.tasks.get(task_id))
150            .copied()
151            .unwrap_or(0)
152    }
153
154    /// The task's open attempts within one run.
155    #[must_use]
156    pub fn of_run_task(&self, run_id: &str, task_id: &TaskId) -> u32 {
157        self.runs
158            .get(run_id)
159            .and_then(|r| r.get(task_id))
160            .copied()
161            .unwrap_or(0)
162    }
163
164    /// The open attempts counted, by ID (for the fault-injection harness's check).
165    #[cfg(test)]
166    pub(crate) fn attempt_ids(&self) -> std::collections::BTreeSet<&str> {
167        self.attempts.keys().map(String::as_str).collect()
168    }
169
170    /// The first limit that one more instance of `task_id` in run `run_id` would go over, if
171    /// any: `max_active_tasks` and `max_active` from `current` (the DAG's current version),
172    /// `max_active_per_run` from `own` (the run's). A task the current version no longer has
173    /// keeps its own version's `max_active`.
174    #[must_use]
175    pub fn reached(
176        &self,
177        (current, own): (&Dag, &Dag),
178        run_id: &str,
179        task_id: &TaskId,
180    ) -> Option<Reached> {
181        self.reached_with(
182            (current, own),
183            (current.task(task_id), own.task(task_id)),
184            run_id,
185            task_id,
186        )
187    }
188
189    /// [`Self::reached`], with the task already looked up in each version (`None`: that
190    /// version doesn't have it): a round looks each task up once, not by searching the DAG's
191    /// list for every ready task (B148).
192    #[must_use]
193    pub fn reached_with(
194        &self,
195        (current, own): (&Dag, &Dag),
196        (in_current, in_own): (Option<&Task>, Option<&Task>),
197        run_id: &str,
198        task_id: &TaskId,
199    ) -> Option<Reached> {
200        let dag_id = &own.id;
201        let reached = |name, limit: Option<u32>, count: u32| {
202            limit
203                .filter(|&value| count >= value)
204                .map(|value| Reached { name, value })
205        };
206        // The DAG's cap first, without looking the task up: with it reached, every ready task
207        // of the DAG is held back at once (Codex's review of M4.4: two searches of the DAG's
208        // tasks for each of them, every round).
209        if let Some(cap) = reached(
210            "max_active_tasks",
211            current.max_active_tasks,
212            self.of_dag(dag_id),
213        ) {
214            return Some(cap);
215        }
216        let task_limit = in_current.or(in_own).and_then(|t| t.settings.max_active);
217        if let Some(task) = reached("max_active", task_limit, self.of_task(dag_id, task_id)) {
218            return Some(task);
219        }
220        let per_run = in_own.and_then(|t| t.settings.max_active_per_run);
221        reached(
222            "max_active_per_run",
223            per_run,
224            self.of_run_task(run_id, task_id),
225        )
226    }
227}
228
229/// One fewer for `key`, gone at zero.
230fn decrement(counts: &mut BTreeMap<TaskId, u32>, key: &TaskId) {
231    if let Some(n) = counts.get_mut(key) {
232        *n = n.saturating_sub(1);
233        if *n == 0 {
234            counts.remove(key);
235        }
236    }
237}