Skip to main content

schedr_master/
progress.rs

1//! How a run's tasks move forward: readiness (`NoneFailed`), retries, cancelling and the run
2//! result (see archive/PROJECT.md, Outcomes, failures and joins, and Task assignment).
3//!
4//! Pure rules over task instance states; [`crate::execution`] stores what they decide.
5//!
6//! - Trigger rules count **edges**: an edge counts as its upstream task's state, except one
7//!   whose upstream succeeded with an outcome the edge isn't taken on (`.on(...)`), which
8//!   counts as skipped.
9//! - `NoneFailed` (the default): a task is **ready** when every edge that wasn't skipped
10//!   succeeded and at least one did (or it has none); **skipped** when all its edges were
11//!   skipped; **upstream failed** as soon as one failed. `AllSucceeded`: ready when every edge
12//!   succeeded; upstream failed as soon as one failed; otherwise skipped when one was skipped,
13//!   once none can fail any more.
14//! - An attempt that failed **uses a retry**; with retries left the task waits `retry_delay`
15//!   (`up_for_retry`), otherwise it fails. Failures certain to repeat are never retried. An
16//!   attempt interrupted by draining or never started runs again without using a retry.
17//! - A run is **`failed`** if a task failed after its last retry, else **`cancelled`** if a
18//!   user cancelled it (and something was cancelled), else **`success`**; decided once every
19//!   task (and every instance of a mapped one) has finished.
20//! - A **mapped task** (decisions 70, 74, 75): its `-1` state is the task as a whole. Once
21//!   its upstream allows (a lane counting as ready once its upstream has expanded) it is
22//!   **expanded**: its instances are created (or it fails, or succeeds with none), and it is
23//!   `running`. Each instance waits for the whole-task edges and for its lanes' instances; an
24//!   instance whose lane isn't taken is skipped. An instance that fails (or whose lane
25//!   failed) fails the step at once: the others are cancelled, running ones stopped. Once
26//!   every instance has finished, the task applies its own `run_if` to them as to edges.
27
28use std::collections::{BTreeMap, BTreeSet, HashMap};
29
30use jiff::{SignedDuration, Timestamp};
31use schedr_model::{
32    AttemptStatus, DEFAULT_OUTCOME, Dag, Edge, EdgeKind, RetryRule, RunIf, RunState, Task, TaskId,
33    TaskInstanceState, TaskKind, TaskSettings,
34};
35
36use crate::mapping::{self, Dim};
37
38#[cfg(test)]
39mod tests;
40
41/// Error kinds of failures certain to repeat: never retried. A secret that doesn't exist or
42/// isn't permitted, and what the same inputs always do again. (`secret_unavailable`, a secret
43/// storage that is down, and `import_failed` / `task_not_found`, which new code can fix, are
44/// retried.) A `TriggerDagOperator`'s parameters refused, or a target that takes no such run
45/// (decisions 379, 398); a missing, held or paused target is retried.
46pub const NOT_RETRIED_ERRORS: [&str; 13] = [
47    schedr_model::runner::SWITCHED_OFF,
48    schedr_model::runner::BLOCKED_EVENT_LOOP,
49    "secret_not_found",
50    "secret_denied",
51    "connection_denied",
52    "inputs_too_large",
53    "render_failed",
54    "input_mismatch",
55    "output_not_serializable",
56    "output_too_large",
57    "result_not_stored",
58    crate::dispatch::chained::PARAMS_REFUSED,
59    crate::dispatch::chained::TARGET_REFUSED,
60];
61
62/// What a task's upstream tasks decide for it.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Readiness {
65    /// Some upstream task hasn't finished.
66    Wait,
67    /// It can run.
68    Ready,
69    /// The edges' skips decide it is skipped (all of them with `NoneFailed`, any with
70    /// `AllSucceeded`).
71    Skip,
72    /// An upstream task failed.
73    UpstreamFailed,
74    /// An upstream task was cancelled.
75    Cancel,
76}
77
78/// What the states of a `first_of`'s edges decide, `need` of them having to be taken (decision
79/// 347): ready as soon as they are; waiting while they still can be; otherwise what stopped them.
80#[must_use]
81pub fn first_of_readiness(edges: &[TaskInstanceState], need: usize) -> Readiness {
82    use TaskInstanceState as S;
83    let taken = edges.iter().filter(|s| **s == S::Success).count();
84    if taken >= need {
85        return Readiness::Ready;
86    }
87    if taken + edges.iter().filter(|s| !s.is_final()).count() >= need {
88        return Readiness::Wait;
89    }
90    if edges
91        .iter()
92        .any(|s| matches!(s, S::Failed | S::UpstreamFailed))
93    {
94        return Readiness::UpstreamFailed;
95    }
96    if edges.contains(&S::Cancelled) {
97        return Readiness::Cancel;
98    }
99    Readiness::Skip
100}
101
102/// How many edges a `first_of` needs taken.
103pub(crate) fn need_of(at_least: Option<u32>) -> usize {
104    at_least.map_or(1, |n| usize::try_from(n).unwrap_or(usize::MAX))
105}
106
107/// The trigger rule `rule` over the states of a task's edges (an edge not taken counts as
108/// skipped).
109#[must_use]
110pub fn readiness(edges: &[TaskInstanceState], rule: RunIf) -> Readiness {
111    use TaskInstanceState as S;
112    if edges
113        .iter()
114        .any(|s| matches!(s, S::Failed | S::UpstreamFailed))
115    {
116        return Readiness::UpstreamFailed;
117    }
118    if edges.contains(&S::Cancelled) {
119        return Readiness::Cancel;
120    }
121    if edges.iter().any(|s| !s.is_final()) {
122        return Readiness::Wait;
123    }
124    let skipped = match rule {
125        RunIf::NoneFailed => !edges.is_empty() && edges.iter().all(|s| *s == S::Skipped),
126        RunIf::AllSucceeded => edges.contains(&S::Skipped),
127    };
128    if skipped {
129        return Readiness::Skip;
130    }
131    Readiness::Ready
132}
133
134/// Of two verdicts on a task, the one that decides: a failure, then a cancel, then waiting,
135/// then a skip; ready only when both are.
136const fn strongest(a: Readiness, b: Readiness) -> Readiness {
137    const fn rank(r: Readiness) -> u8 {
138        match r {
139            Readiness::UpstreamFailed => 4,
140            Readiness::Cancel => 3,
141            Readiness::Wait => 2,
142            Readiness::Skip => 1,
143            Readiness::Ready => 0,
144        }
145    }
146    if rank(a) >= rank(b) { a } else { b }
147}
148
149/// The reason an empty cleanup gets, where its log would be (decision 276).
150pub const EMPTY_CLEANUP: &str = "no cleanup declared: nothing to clean";
151
152/// What happens to a task after one of its attempts ended.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum AfterAttempt {
155    /// It succeeded.
156    Succeeded,
157    /// It runs again at this moment (`up_for_retry` until then); the attempt used a retry.
158    RetryAt(Timestamp),
159    /// It failed after its last retry (or with a failure certain to repeat).
160    Failed,
161    /// It runs again now, without using a retry.
162    Requeue,
163    /// It was cancelled.
164    Cancelled,
165}
166
167impl AfterAttempt {
168    /// Whether the attempt used one of the task's retries.
169    #[must_use]
170    pub const fn uses_retry(self) -> bool {
171        matches!(self, Self::RetryAt(_) | Self::Failed)
172    }
173}
174
175/// Decides what follows an attempt with `status` (and the error kind schedr recognised, if
176/// any), given how many retries the task used before it and whether the task or its run is
177/// being cancelled (then nothing runs again, a failure stays a failure, and an attempt lost
178/// with its worker is cancelled).
179#[must_use]
180pub fn after_attempt(
181    status: AttemptStatus,
182    error_kind: Option<&str>,
183    retries_used: u32,
184    settings: &TaskSettings,
185    cancelling: bool,
186    now: Timestamp,
187) -> AfterAttempt {
188    match status.retry_rule() {
189        RetryRule::NotNeeded => AfterAttempt::Succeeded,
190        RetryRule::Never => AfterAttempt::Cancelled,
191        RetryRule::RequeueWithoutRetry if cancelling => AfterAttempt::Cancelled,
192        RetryRule::RequeueWithoutRetry => AfterAttempt::Requeue,
193        // The worker went while the task was being stopped: stopped, as asked.
194        RetryRule::UsesRetry if cancelling && status == AttemptStatus::Lost => {
195            AfterAttempt::Cancelled
196        }
197        RetryRule::UsesRetry => {
198            let repeats = error_kind.is_some_and(|kind| NOT_RETRIED_ERRORS.contains(&kind));
199            if cancelling || repeats || retries_used >= settings.retries {
200                return AfterAttempt::Failed;
201            }
202            let delay = SignedDuration::from_millis(
203                i64::try_from(settings.retry_delay_ms).unwrap_or(i64::MAX),
204            );
205            AfterAttempt::RetryAt(now.checked_add(delay).unwrap_or(Timestamp::MAX))
206        }
207    }
208}
209
210/// The run's result once every task has finished; `None` while some task hasn't.
211#[must_use]
212pub fn run_result(states: &[TaskInstanceState]) -> Option<RunState> {
213    use TaskInstanceState as S;
214    if states.iter().any(|s| !s.is_final()) {
215        return None;
216    }
217    Some(if states.contains(&S::Failed) {
218        RunState::Failed
219    } else if states.contains(&S::Cancelled) {
220        RunState::Cancelled
221    } else {
222        RunState::Success
223    })
224}
225
226/// A task instance: its task and `map_index` (-1: an unmapped task, or a mapped one as a
227/// whole).
228pub type InstanceKey = (TaskId, i32);
229
230/// The instances of a mapped task that expanded.
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub struct Instances {
233    /// The size of each dimension (the first varying slowest).
234    pub sizes: Vec<usize>,
235    /// Each instance's state, by `map_index`.
236    pub states: Vec<TaskInstanceState>,
237    /// Each instance's outcome, once it succeeded.
238    pub outcomes: Vec<Option<String>>,
239}
240
241/// How a mapped task expands, as the master resolved what it is mapped over.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub enum Expansion {
244    /// Instances over these dimensions' sizes (none of them: a success with `[]`).
245    Sizes(Vec<usize>),
246    /// It can't: it fails, for this reason (decision 78).
247    Fail(String),
248}
249
250/// The states of a run's tasks and instances at one moment, to tell what changed since.
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct Snapshot {
253    tasks: BTreeMap<TaskId, TaskInstanceState>,
254    instances: BTreeMap<TaskId, Vec<TaskInstanceState>>,
255}
256
257/// What changed since a [`Snapshot`]: (task, `map_index`, new state).
258#[derive(Debug, Clone, Default, PartialEq, Eq)]
259pub struct Changes {
260    /// Rows that existed and changed.
261    pub updated: Vec<(TaskId, i32, TaskInstanceState)>,
262    /// Instances created by an expansion, in their current state.
263    pub created: Vec<(TaskId, i32, TaskInstanceState)>,
264}
265
266/// A run's task states, moved forward by the DAG's structure.
267#[derive(Debug, Clone)]
268pub struct RunProgress<'a> {
269    dag: &'a Dag,
270    /// Each task's state (a mapped task's as a whole: its `-1` row).
271    states: BTreeMap<TaskId, TaskInstanceState>,
272    /// The outcomes of the tasks that succeeded (`SUCCESS` where none is known).
273    outcomes: BTreeMap<TaskId, String>,
274    /// What each `@branch` task that succeeded chose (its output).
275    chosen: BTreeMap<TaskId, Vec<TaskId>>,
276    /// The instances of the mapped tasks that expanded.
277    instances: BTreeMap<TaskId, Instances>,
278    /// Mapped tasks ready to expand: the master resolves what they map over, then
279    /// [`Self::expand`].
280    to_expand: BTreeSet<TaskId>,
281    /// Whether a cleanup of the run failed.
282    failed_cleanup: bool,
283    /// Whether the run is being cancelled: it ends `cancelled` even if nothing was left to
284    /// cancel but its resources' cleanups (decision 277).
285    cancelling: bool,
286    /// Running instances to stop: their step failed (decision 75a).
287    stops: Vec<(TaskId, usize)>,
288    /// Why mapped tasks failed without an attempt.
289    reasons: BTreeMap<TaskId, String>,
290    /// Whether settling a mapped task moved one of its instances (a step of [`Self::settle`]).
291    instance_moved: bool,
292    /// The `first_of` tasks that ended now, with the upstream tasks that can have ended them.
293    winners: BTreeMap<TaskId, Vec<TaskId>>,
294    /// The DAG's tasks (their places in `dag.tasks`) upstream before downstream: a pass in
295    /// this order moves a chain all the way, however it is listed (B82).
296    order: Vec<usize>,
297    /// Each task's edges in (their places in `dag.edges`), in order: looked up once,
298    /// not searched for each task each pass (B82).
299    incoming: HashMap<TaskId, Vec<usize>>,
300    /// Each task's place in `dag.tasks`.
301    places: HashMap<TaskId, usize>,
302    /// Passes [`Self::settle`] made over the tasks (for the tests).
303    passes: usize,
304}
305
306/// The places of `dag`'s tasks, upstream before downstream (Kahn's, ties in listing order);
307/// any a cycle would leave out come last, as listed.
308fn upstream_first(dag: &Dag, places: &HashMap<TaskId, usize>) -> Vec<usize> {
309    let mut waiting = vec![0_usize; dag.tasks.len()];
310    let mut downstream: Vec<Vec<usize>> = vec![Vec::new(); dag.tasks.len()];
311    for edge in &dag.edges {
312        if let (Some(&from), Some(&to)) = (places.get(&edge.from), places.get(&edge.to)) {
313            waiting[to] += 1;
314            downstream[from].push(to);
315        }
316    }
317    let mut ready: std::collections::VecDeque<usize> =
318        (0..dag.tasks.len()).filter(|&i| waiting[i] == 0).collect();
319    let mut order = Vec::with_capacity(dag.tasks.len());
320    while let Some(i) = ready.pop_front() {
321        order.push(i);
322        for &next in &downstream[i] {
323            waiting[next] -= 1;
324            if waiting[next] == 0 {
325                ready.push_back(next);
326            }
327        }
328    }
329    if order.len() < dag.tasks.len() {
330        let ordered: BTreeSet<usize> = order.iter().copied().collect();
331        order.extend((0..dag.tasks.len()).filter(|i| !ordered.contains(i)));
332    }
333    order
334}
335
336impl<'a> RunProgress<'a> {
337    /// The edges into `id`, in order (the DAG's `edges_into`, from the index).
338    fn edges_into(&self, id: &TaskId) -> impl Iterator<Item = &'a Edge> + use<'a, '_> {
339        let dag = self.dag;
340        self.incoming
341            .get(id)
342            .into_iter()
343            .flatten()
344            .map(move |&i| &dag.edges[i])
345    }
346
347    /// The task `id` (the DAG's `task`, from the index).
348    fn task_of(&self, id: &TaskId) -> Option<&'a Task> {
349        let dag = self.dag;
350        self.places.get(id).map(|&i| &dag.tasks[i])
351    }
352
353    /// The progress of a run of `dag` with the given task states (tasks not given are
354    /// `scheduled`).
355    #[must_use]
356    pub fn new(dag: &'a Dag, states: BTreeMap<TaskId, TaskInstanceState>) -> Self {
357        let mut all: BTreeMap<TaskId, TaskInstanceState> = dag
358            .tasks
359            .iter()
360            .map(|t| (t.id.clone(), TaskInstanceState::Scheduled))
361            .collect();
362        all.extend(states);
363        let places: HashMap<TaskId, usize> = dag
364            .tasks
365            .iter()
366            .enumerate()
367            .map(|(i, t)| (t.id.clone(), i))
368            .collect();
369        let mut incoming: HashMap<TaskId, Vec<usize>> = HashMap::new();
370        for (i, edge) in dag.edges.iter().enumerate() {
371            incoming.entry(edge.to.clone()).or_default().push(i);
372        }
373        let order = upstream_first(dag, &places);
374        Self {
375            dag,
376            order,
377            incoming,
378            places,
379            passes: 0,
380            states: all,
381            outcomes: BTreeMap::new(),
382            chosen: BTreeMap::new(),
383            instances: BTreeMap::new(),
384            to_expand: BTreeSet::new(),
385            stops: Vec::new(),
386            failed_cleanup: false,
387            cancelling: false,
388            reasons: BTreeMap::new(),
389            instance_moved: false,
390            winners: BTreeMap::new(),
391        }
392    }
393
394    /// The same, with the instances of mapped tasks that expanded.
395    #[must_use]
396    pub fn with_instances(mut self, instances: BTreeMap<TaskId, Instances>) -> Self {
397        self.instances = instances;
398        self
399    }
400
401    /// A mapped task's instances, once it expanded.
402    #[must_use]
403    pub fn instances(&self, task: &TaskId) -> Option<&Instances> {
404        self.instances.get(task)
405    }
406
407    /// Sets an instance's state (after one of its attempts).
408    pub fn set_instance(&mut self, task: &TaskId, index: usize, state: TaskInstanceState) {
409        if let Some(slot) = self
410            .instances
411            .get_mut(task)
412            .and_then(|i| i.states.get_mut(index))
413        {
414            *slot = state;
415        }
416    }
417
418    /// Records an instance's outcome (after an attempt that succeeded).
419    pub fn set_instance_outcome(&mut self, task: &TaskId, index: usize, outcome: &str) {
420        if let Some(slot) = self
421            .instances
422            .get_mut(task)
423            .and_then(|i| i.outcomes.get_mut(index))
424        {
425            *slot = Some(outcome.to_owned());
426        }
427    }
428
429    /// The mapped tasks ready to expand, taken (each comes back from [`Self::settle`] until
430    /// expanded).
431    pub fn take_expansions(&mut self) -> Vec<TaskId> {
432        std::mem::take(&mut self.to_expand).into_iter().collect()
433    }
434
435    /// Expands a mapped task as the master resolved it: its instances `scheduled` (none: a
436    /// success with `[]`), or failed with a reason.
437    pub fn expand(&mut self, task: &TaskId, expansion: Expansion) {
438        use TaskInstanceState as S;
439        self.to_expand.remove(task);
440        match expansion {
441            Expansion::Fail(reason) => {
442                self.states.insert(task.clone(), S::Failed);
443                self.reasons.insert(task.clone(), reason);
444            }
445            Expansion::Sizes(sizes) => {
446                let n = mapping::count(&sizes).unwrap_or(0);
447                if n == 0 {
448                    self.states.insert(task.clone(), S::Success);
449                    self.outcomes
450                        .insert(task.clone(), DEFAULT_OUTCOME.to_owned());
451                    return;
452                }
453                self.states.insert(task.clone(), S::Running);
454                // Instances already there (stored before their whole task's row was) keep
455                // their states: they may be running or done.
456                let instances = self
457                    .instances
458                    .entry(task.clone())
459                    .or_insert_with(|| Instances {
460                        sizes: Vec::new(),
461                        states: vec![S::Scheduled; n],
462                        outcomes: vec![None; n],
463                    });
464                instances.sizes = sizes;
465            }
466        }
467    }
468
469    /// Why a mapped task failed without an attempt, if it did.
470    #[must_use]
471    pub fn reason(&self, task: &TaskId) -> Option<&str> {
472        self.reasons.get(task).map(String::as_str)
473    }
474
475    /// Running instances to stop, taken: their step failed (decision 75a).
476    pub fn take_stops(&mut self) -> Vec<(TaskId, usize)> {
477        std::mem::take(&mut self.stops)
478    }
479
480    /// Every state now, to tell later what changed.
481    #[must_use]
482    pub fn snapshot(&self) -> Snapshot {
483        Snapshot {
484            tasks: self.states.clone(),
485            instances: self
486                .instances
487                .iter()
488                .map(|(task, i)| (task.clone(), i.states.clone()))
489                .collect(),
490        }
491    }
492
493    /// What changed since `before`: rows to update, and instances an expansion created.
494    #[must_use]
495    pub fn changes_since(&self, before: &Snapshot) -> Changes {
496        let mut changes = Changes::default();
497        for (task, state) in &self.states {
498            if before.tasks.get(task) != Some(state) {
499                changes.updated.push((task.clone(), -1, *state));
500            }
501        }
502        for (task, instances) in &self.instances {
503            let old = before.instances.get(task);
504            for (index, state) in instances.states.iter().enumerate() {
505                let map_index = i32::try_from(index).unwrap_or(i32::MAX);
506                match old.and_then(|o| o.get(index)) {
507                    None => changes.created.push((task.clone(), map_index, *state)),
508                    Some(was) if was != state => {
509                        changes.updated.push((task.clone(), map_index, *state));
510                    }
511                    Some(_) => {}
512                }
513            }
514        }
515        changes
516    }
517
518    /// The same, with what the `@branch` tasks that succeeded chose.
519    #[must_use]
520    pub fn with_chosen(mut self, chosen: BTreeMap<TaskId, Vec<TaskId>>) -> Self {
521        self.chosen = chosen;
522        self
523    }
524
525    /// The same, with the outcomes of the tasks that succeeded.
526    #[must_use]
527    pub fn with_outcomes(mut self, outcomes: BTreeMap<TaskId, String>) -> Self {
528        self.outcomes = outcomes;
529        self
530    }
531
532    /// A task's outcome, if it succeeded with one recorded.
533    #[must_use]
534    pub fn outcome(&self, task: &TaskId) -> Option<&str> {
535        self.outcomes.get(task).map(String::as_str)
536    }
537
538    /// Records a task's outcome (after an attempt that succeeded).
539    pub fn set_outcome(&mut self, task: &TaskId, outcome: &str) {
540        self.outcomes.insert(task.clone(), outcome.to_owned());
541    }
542
543    /// The state an edge into a task counts as: its upstream task's, or skipped when the
544    /// upstream succeeded with an outcome the edge isn't taken on.
545    fn edge_state(&self, edge: &schedr_model::Edge) -> TaskInstanceState {
546        let state = self
547            .states
548            .get(&edge.from)
549            .copied()
550            .unwrap_or(TaskInstanceState::Scheduled);
551        if state == TaskInstanceState::Success && edge.kind == schedr_model::EdgeKind::Selection {
552            // Taken when the branch chose its target (one it chose nothing for: not taken).
553            let chosen = self
554                .chosen
555                .get(&edge.from)
556                .is_some_and(|chosen| chosen.contains(&edge.to));
557            return if chosen {
558                state
559            } else {
560                TaskInstanceState::Skipped
561            };
562        }
563        // A mapped task's own outcome only says its instances ended: its `.on(...)` is
564        // decided per instance ([`Self::edge_states`]); with none, the edge is taken, as the
565        // task with an empty list succeeds.
566        let mapped = self.task_of(&edge.from).is_some_and(mapping::is_mapped);
567        if state == TaskInstanceState::Success && !mapped {
568            let outcome = self
569                .outcomes
570                .get(&edge.from)
571                .map_or(DEFAULT_OUTCOME, String::as_str);
572            if !edge.taken_on(outcome) {
573                return TaskInstanceState::Skipped;
574            }
575        }
576        state
577    }
578
579    /// The states an edge counts as in the downstream task's rule: one, or for an edge
580    /// narrowed with `.on(...)` from a mapped task that succeeded, one per instance, taken
581    /// when it ended with one of those outcomes, so `RunIf::AllSucceeded` needs every
582    /// instance to and `RunIf::NoneFailed` any (decision 120).
583    fn edge_states(&self, edge: &Edge) -> Vec<TaskInstanceState> {
584        use TaskInstanceState as S;
585        if edge.kind == EdgeKind::Requirement {
586            // Only stops a task ([`Self::required`]): never one of its rule's edges.
587            return Vec::new();
588        }
589        let state = self.edge_state(edge);
590        if state != S::Success
591            || edge.on.is_empty()
592            || edge.kind == schedr_model::EdgeKind::Selection
593        {
594            return vec![state];
595        }
596        match self.instances.get(&edge.from) {
597            Some(instances) if !instances.states.is_empty() => (0..instances.states.len())
598                .map(|place| {
599                    if self.instance_taken(&edge.from, place, &edge.on) {
600                        S::Success
601                    } else {
602                        S::Skipped
603                    }
604                })
605                .collect(),
606            _ => vec![state],
607        }
608    }
609
610    /// The DAG it follows.
611    #[must_use]
612    pub const fn dag(&self) -> &'a Dag {
613        self.dag
614    }
615
616    /// Every task's state.
617    #[must_use]
618    pub const fn states(&self) -> &BTreeMap<TaskId, TaskInstanceState> {
619        &self.states
620    }
621
622    /// Sets a task's state (after an attempt, or a retry delay that passed).
623    pub fn set(&mut self, task: &TaskId, state: TaskInstanceState) {
624        self.states.insert(task.clone(), state);
625    }
626
627    /// Moves `scheduled` tasks on as far as their upstream tasks allow: ready tasks become
628    /// `queued` (empty tasks `success`, completed by the master), others `skipped`,
629    /// `upstream_failed` or `cancelled`; mapped tasks ready to expand are listed for
630    /// [`Self::take_expansions`], and expanded ones move their instances on; repeated until
631    /// nothing changes, or until a `first_of` ends ([`Self::take_winners`]: its output is
632    /// made before what follows it moves). Returns the tasks (as a whole) whose state changed,
633    /// with their new state, in the order they changed.
634    pub fn settle(&mut self) -> Vec<(TaskId, TaskInstanceState)> {
635        let mut changes: Vec<(TaskId, TaskInstanceState)> = Vec::new();
636        let dag = self.dag;
637        loop {
638            self.passes += 1;
639            let mut progressed = false;
640            for k in 0..self.order.len() {
641                let task = &dag.tasks[self.order[k]];
642                if mapping::is_mapped(task) {
643                    if let Some(next) = self.settle_mapped(task) {
644                        self.states.insert(task.id.clone(), next);
645                        changes.retain(|(id, _)| id != &task.id);
646                        changes.push((task.id.clone(), next));
647                        progressed = true;
648                    }
649                    progressed |= std::mem::take(&mut self.instance_moved);
650                    continue;
651                }
652                if self.states[&task.id] != TaskInstanceState::Scheduled {
653                    continue;
654                }
655                let edges: Vec<TaskInstanceState> = self
656                    .edges_into(&task.id)
657                    .flat_map(|edge| self.edge_states(edge))
658                    .collect();
659                let rule = match task.kind {
660                    TaskKind::FirstOf { at_least } => first_of_readiness(&edges, need_of(at_least)),
661                    _ => readiness(&edges, task.settings.run_if),
662                };
663                let next = match self.gate(task, rule) {
664                    Readiness::Wait => continue,
665                    Readiness::Ready if matches!(task.kind, TaskKind::FirstOf { .. }) => {
666                        // One at a time, before anything after it moves: its output is made
667                        // from its winners' and may not fit ([`Self::fail_first_of`]).
668                        self.record_winners(task);
669                        self.states
670                            .insert(task.id.clone(), TaskInstanceState::Success);
671                        changes.retain(|(id, _)| id != &task.id);
672                        changes.push((task.id.clone(), TaskInstanceState::Success));
673                        return changes;
674                    }
675                    Readiness::Ready if task.kind == TaskKind::Empty => {
676                        if self.dag.resource_of_cleanup(&task.id).is_some() {
677                            self.reasons
678                                .insert(task.id.clone(), EMPTY_CLEANUP.to_owned());
679                        }
680                        TaskInstanceState::Success
681                    }
682                    Readiness::Ready => TaskInstanceState::Queued,
683                    Readiness::Skip => TaskInstanceState::Skipped,
684                    Readiness::UpstreamFailed => TaskInstanceState::UpstreamFailed,
685                    Readiness::Cancel => TaskInstanceState::Cancelled,
686                };
687                self.states.insert(task.id.clone(), next);
688                changes.retain(|(id, _)| id != &task.id);
689                changes.push((task.id.clone(), next));
690                progressed = true;
691            }
692            if !progressed {
693                return changes;
694            }
695        }
696    }
697
698    /// The upstream tasks a `first_of` that is ready can have ended with: those taken, in the
699    /// order of its edges. Which of them did is told by when they ended ([`Self::take_winners`]).
700    fn record_winners(&mut self, task: &Task) {
701        let candidates: Vec<TaskId> = self
702            .edges_into(&task.id)
703            .filter(|edge| edge.kind != EdgeKind::Requirement)
704            .filter(|edge| self.edge_state(edge) == TaskInstanceState::Success)
705            .map(|edge| edge.from.clone())
706            .collect();
707        self.winners.insert(task.id.clone(), candidates);
708    }
709
710    /// A `first_of` whose output can't be kept fails, with why.
711    pub fn fail_first_of(&mut self, task: &TaskId, reason: String) {
712        self.states.insert(task.clone(), TaskInstanceState::Failed);
713        self.outcomes.remove(task);
714        self.reasons.insert(task.clone(), reason);
715    }
716
717    /// The `first_of` tasks ended since this was last asked, each with what can have ended it.
718    pub fn take_winners(&mut self) -> BTreeMap<TaskId, Vec<TaskId>> {
719        std::mem::take(&mut self.winners)
720    }
721
722    /// Cancels the run: every task (and instance) that hasn't started becomes `cancelled`.
723    /// Returns the tasks' changes, and the tasks and instances still running, by `map_index`
724    /// (their attempts are to be cancelled; they finish on their own and their results
725    /// count). A mapped task as a whole ends once its instances have ([`Self::settle`]).
726    pub fn cancel(&mut self) -> (Vec<(TaskId, TaskInstanceState)>, Vec<InstanceKey>) {
727        use TaskInstanceState as S;
728        let mut changes = Vec::new();
729        let mut running = Vec::new();
730        self.cancelling = true;
731        let dag = self.dag;
732        for (id, state) in &mut self.states {
733            if dag.resource_of_cleanup(id).is_some() {
734                // A resource set up is freed all the same (decision 277); one that wasn't is
735                // `cancelled` by its setup's edge.
736                continue;
737            }
738            match state {
739                S::Scheduled | S::Queued | S::UpForRetry | S::Unschedulable => {
740                    *state = S::Cancelled;
741                    changes.push((id.clone(), S::Cancelled));
742                }
743                S::Running | S::CleaningUp if !self.instances.contains_key(id) => {
744                    running.push((id.clone(), -1));
745                }
746                _ => {}
747            }
748        }
749        for (id, instances) in &mut self.instances {
750            for (index, state) in instances.states.iter_mut().enumerate() {
751                match state {
752                    S::Scheduled | S::Queued | S::UpForRetry | S::Unschedulable => {
753                        *state = S::Cancelled;
754                    }
755                    S::Running | S::CleaningUp => {
756                        running.push((id.clone(), i32::try_from(index).unwrap_or(i32::MAX)));
757                    }
758                    _ => {}
759                }
760            }
761        }
762        (changes, running)
763    }
764
765    /// The run's result, once every task and instance has finished.
766    #[must_use]
767    pub fn result(&self) -> Option<RunState> {
768        let all: Vec<TaskInstanceState> = self
769            .states
770            .values()
771            .copied()
772            .chain(
773                self.instances
774                    .values()
775                    .flat_map(|i| i.states.iter().copied()),
776            )
777            .collect();
778        run_result(&all).map(|result| {
779            if self.failed_cleanup {
780                RunState::Failed
781            } else if self.cancelling && result == RunState::Success {
782                RunState::Cancelled
783            } else {
784                result
785            }
786        })
787    }
788
789    /// Notes that the run is being cancelled: it can't end `success`.
790    #[must_use]
791    pub const fn with_cancelling(mut self, cancelling: bool) -> Self {
792        self.cancelling = cancelling;
793        self
794    }
795
796    /// Notes that a cleanup failed: the run ends `failed` (see archive/PROJECT.md, Run result).
797    #[must_use]
798    pub const fn with_failed_cleanup(mut self, failed: bool) -> Self {
799        self.failed_cleanup = failed;
800        self
801    }
802
803    /// A mapped task's next state as a whole, if it changes: expansion asked for, instances
804    /// moved on (noted in `instance_moved`), a failed step, or the result of its instances.
805    fn settle_mapped(&mut self, task: &Task) -> Option<TaskInstanceState> {
806        use TaskInstanceState as S;
807        match self.states[&task.id] {
808            S::Scheduled => {
809                let edges: Vec<TaskInstanceState> = self
810                    .edges_into(&task.id)
811                    .flat_map(|edge| self.whole_edge_state(edge))
812                    .collect();
813                match self.gate(task, readiness(&edges, task.settings.run_if)) {
814                    Readiness::Wait => None,
815                    Readiness::Ready => {
816                        self.to_expand.insert(task.id.clone());
817                        None
818                    }
819                    Readiness::Skip => Some(S::Skipped),
820                    Readiness::UpstreamFailed => Some(S::UpstreamFailed),
821                    Readiness::Cancel => Some(S::Cancelled),
822                }
823            }
824            S::Running if self.instances.contains_key(&task.id) => self.settle_instances(task),
825            _ => None,
826        }
827    }
828
829    /// An edge into a mapped task that hasn't expanded: a lane counts as ready once its
830    /// upstream has expanded (its count is known), any other edge as usual.
831    fn whole_edge_state(&self, edge: &Edge) -> Vec<TaskInstanceState> {
832        use TaskInstanceState as S;
833        if edge.kind == EdgeKind::Requirement || !mapping::is_lane(self.dag, edge) {
834            return self.whole_edge(edge);
835        }
836        vec![
837            match self.states.get(&edge.from).copied().unwrap_or(S::Scheduled) {
838                S::Running if self.instances.contains_key(&edge.from) => S::Success,
839                state => state,
840            },
841        ]
842    }
843
844    /// Moves an expanded task's instances on; returns its new state as a whole, if any.
845    fn settle_instances(&mut self, task: &Task) -> Option<TaskInstanceState> {
846        use TaskInstanceState as S;
847        let dims = mapping::dims(self.dag, task);
848        let sizes = self.instances[&task.id].sizes.clone();
849        let count = self.instances[&task.id].states.len();
850        for index in 0..count {
851            if self.instances[&task.id].states[index] != S::Scheduled {
852                continue;
853            }
854            let place = mapping::coordinates(index, &sizes);
855            // An element narrowed with `.on(...)` that its upstream instance didn't end with
856            // (decision 119).
857            let mut lane_skipped = dims.iter().enumerate().any(|(d, (_, dim))| {
858                mapping::narrowed_whole(self.dag, dim)
859                    .is_some_and(|(upstream, on)| !self.instance_taken(upstream, place[d], on))
860            });
861            let mut edges = Vec::new();
862            let dag = self.dag;
863            for edge in self.edges_into(&task.id) {
864                if edge.kind == EdgeKind::Requirement || !mapping::is_lane(dag, edge) {
865                    edges.extend(self.whole_edge(edge));
866                    continue;
867                }
868                let state = dims
869                    .iter()
870                    .position(|(_, dim)| *dim == Dim::Lane(&edge.from))
871                    .map_or(S::Scheduled, |d| self.lane_state(edge, place[d]));
872                lane_skipped |= state == S::Skipped;
873                edges.push(state);
874            }
875            let next = match self.gate(task, readiness(&edges, task.settings.run_if)) {
876                Readiness::Wait => continue,
877                Readiness::Ready if lane_skipped => S::Skipped,
878                Readiness::Ready => S::Queued,
879                Readiness::Skip => S::Skipped,
880                Readiness::UpstreamFailed => S::UpstreamFailed,
881                Readiness::Cancel => S::Cancelled,
882            };
883            self.set_instance(&task.id, index, next);
884            self.instance_moved = true;
885        }
886        let states = self.instances[&task.id].states.clone();
887        let failed = states.contains(&S::Failed);
888        if failed || states.contains(&S::UpstreamFailed) {
889            // The step failed: the others are cancelled, running ones stopped (75a).
890            for (index, state) in states.iter().enumerate() {
891                match state {
892                    S::Scheduled | S::Queued | S::UpForRetry | S::Unschedulable => {
893                        self.set_instance(&task.id, index, S::Cancelled);
894                    }
895                    S::Running | S::CleaningUp => self.stops.push((task.id.clone(), index)),
896                    _ => {}
897                }
898            }
899            self.instance_moved = true;
900            return Some(if failed { S::Failed } else { S::UpstreamFailed });
901        }
902        if states.iter().any(|s| !s.is_final()) {
903            return None;
904        }
905        // Its own rule over its instances, as over edges (75b D).
906        let skipped = match task.settings.run_if {
907            RunIf::NoneFailed => states.iter().all(|s| *s == S::Skipped),
908            RunIf::AllSucceeded => states.contains(&S::Skipped),
909        };
910        let next = if states.contains(&S::Cancelled) {
911            S::Cancelled
912        } else if skipped {
913            S::Skipped
914        } else {
915            self.outcomes
916                .insert(task.id.clone(), DEFAULT_OUTCOME.to_owned());
917            S::Success
918        };
919        self.instance_moved = true;
920        Some(next)
921    }
922
923    /// What a task's requirement edges and, for a resource's cleanup, its users say on top of
924    /// `rule`, its trigger rule over its other edges. A requirement never lets a task run, it
925    /// can only stop it: its setup failed (`upstream_failed`), was cancelled, or was skipped
926    /// (skipped, whatever the rule). A cleanup that could run waits until every user is done
927    /// (decision 259): a task that will never run again counts, an `unschedulable` one doesn't.
928    fn gate(&self, task: &Task, rule: Readiness) -> Readiness {
929        use TaskInstanceState as S;
930        let state = |id: &TaskId| self.states.get(id).copied().unwrap_or(S::Scheduled);
931        let required: Vec<S> = self
932            .edges_into(&task.id)
933            .filter(|e| e.kind == EdgeKind::Requirement)
934            .map(|e| state(&e.from))
935            .collect();
936        let gated = if required
937            .iter()
938            .any(|s| matches!(s, S::Failed | S::UpstreamFailed))
939        {
940            Readiness::UpstreamFailed
941        } else if required.contains(&S::Cancelled) {
942            Readiness::Cancel
943        } else if required.iter().any(|s| !s.is_final()) {
944            Readiness::Wait
945        } else if required.contains(&S::Skipped) {
946            Readiness::Skip
947        } else {
948            Readiness::Ready
949        };
950        let decided = strongest(rule, gated);
951        if decided != Readiness::Ready {
952            return decided;
953        }
954        // A mapped user is done when its instances are too: one failing fails it as a whole
955        // while the others are still being stopped.
956        let done = |user: &TaskId| {
957            state(user).is_final()
958                && self
959                    .instances
960                    .get(user)
961                    .is_none_or(|i| i.states.iter().all(|s| s.is_final()))
962        };
963        match self.dag.resource_of_cleanup(&task.id) {
964            Some(resource) if !resource.users.iter().all(done) => Readiness::Wait,
965            _ => Readiness::Ready,
966        }
967    }
968
969    /// An edge that isn't a lane: as usual, except that one whose outcomes are taken per
970    /// element counts as its upstream task's state ([`mapping::narrows_per_element`]).
971    fn whole_edge(&self, edge: &Edge) -> Vec<TaskInstanceState> {
972        if edge.kind == EdgeKind::Requirement {
973            return Vec::new();
974        }
975        if mapping::narrows_per_element(self.dag, edge) {
976            return vec![self.edge_state(edge)];
977        }
978        self.edge_states(edge)
979    }
980
981    /// Whether instance `place` of the mapped task `upstream` succeeded with one of `on`.
982    fn instance_taken(&self, upstream: &TaskId, place: usize, on: &[String]) -> bool {
983        let Some(instances) = self.instances.get(upstream) else {
984            return false;
985        };
986        if instances.states.get(place) != Some(&TaskInstanceState::Success) {
987            return false;
988        }
989        let outcome = instances
990            .outcomes
991            .get(place)
992            .and_then(Option::as_deref)
993            .unwrap_or(DEFAULT_OUTCOME);
994        on.iter().any(|o| o == outcome)
995    }
996
997    /// The state a lane into an instance counts as: its upstream instance's, or skipped when
998    /// that one succeeded with an outcome the edge isn't taken on.
999    fn lane_state(&self, edge: &Edge, place: usize) -> TaskInstanceState {
1000        use TaskInstanceState as S;
1001        let Some(upstream) = self.instances.get(&edge.from) else {
1002            return S::Scheduled;
1003        };
1004        let state = upstream.states.get(place).copied().unwrap_or(S::Scheduled);
1005        if state != S::Success {
1006            return state;
1007        }
1008        let outcome = upstream
1009            .outcomes
1010            .get(place)
1011            .and_then(Option::as_deref)
1012            .unwrap_or(DEFAULT_OUTCOME);
1013        if edge.taken_on(outcome) {
1014            S::Success
1015        } else {
1016            S::Skipped
1017        }
1018    }
1019}