Skip to main content

schedr_model/
states.rs

1//! Run kinds and the states of runs, task instances and attempts.
2//!
3//! See archive/PROJECT.md: Task assignment (run states, task instance states, attempt statuses) and
4//! Runs: manual runs, backfill and pausing (run kinds).
5
6use std::fmt;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11#[cfg(test)]
12mod tests;
13
14/// Who or what created a run.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
16#[serde(rename_all = "snake_case")]
17pub enum RunKind {
18    /// Created by the scheduler for a fire time.
19    Scheduled,
20    /// Started by a person (UI, CLI, API).
21    Manual,
22    /// One of the runs of a backfill.
23    Backfill,
24    /// Created by another DAG's run (`TriggerDagOperator`).
25    Chained,
26    /// Created by an event from the DAG's trigger (an event trigger).
27    Event,
28}
29
30/// Where a run stands.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
32#[serde(rename_all = "snake_case")]
33pub enum RunState {
34    /// Created and waiting for `max_active_runs` (only manual, backfill, chained and event runs).
35    Queued,
36    /// Tasks are being scheduled or running.
37    Running,
38    /// Finished without anything unexpected going wrong.
39    Success,
40    /// Something unexpected went wrong in it (a task or cleanup failed after its last retry).
41    Failed,
42    /// Cancelled by a user, with no unexpected failure.
43    Cancelled,
44}
45
46impl RunState {
47    /// Whether the run has finished: its result never changes again.
48    #[must_use]
49    pub const fn is_final(self) -> bool {
50        matches!(self, Self::Success | Self::Failed | Self::Cancelled)
51    }
52}
53
54/// How a task's cleanup ended: an attribute beside its state, not a state.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
56#[serde(rename_all = "snake_case")]
57pub enum CleanupResult {
58    /// It ran and succeeded.
59    Ok,
60    /// It failed after its last retry: the run fails.
61    Failed,
62    /// It didn't run, its worker being lost: counts as failed.
63    WorkerLost,
64    /// The attempt's process never started (decision 216).
65    NotNeeded,
66}
67
68impl CleanupResult {
69    /// Whether it fails the run (see archive/PROJECT.md, Run result).
70    #[must_use]
71    pub const fn fails_the_run(self) -> bool {
72        matches!(self, Self::Failed | Self::WorkerLost)
73    }
74}
75
76/// Where a task stands in its run, decided by the master.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
78#[serde(rename_all = "snake_case")]
79pub enum TaskInstanceState {
80    /// Created; its upstream tasks haven't decided yet.
81    Scheduled,
82    /// Ready to run, waiting for a worker or a concurrency limit.
83    Queued,
84    /// Every eligible worker rejected it.
85    Unschedulable,
86    /// An attempt is running.
87    Running,
88    /// The attempt's process has ended and its per-task cleanup is running.
89    CleaningUp,
90    /// An attempt failed and the next one waits for `retry_delay`.
91    UpForRetry,
92    /// Succeeded (with an outcome).
93    Success,
94    /// Failed after its last retry.
95    Failed,
96    /// Cancelled by a user.
97    Cancelled,
98    /// Skipped (a branch, an outcome edge not taken, all upstream tasks skipped).
99    Skipped,
100    /// Will never run because an upstream task failed.
101    UpstreamFailed,
102}
103
104impl TaskInstanceState {
105    /// Whether the task will never change state again in this run.
106    #[must_use]
107    pub const fn is_final(self) -> bool {
108        matches!(
109            self,
110            Self::Success | Self::Failed | Self::Cancelled | Self::Skipped | Self::UpstreamFailed
111        )
112    }
113}
114
115/// How one attempt (one try) of a task ended.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
117#[serde(rename_all = "snake_case")]
118pub enum AttemptStatus {
119    /// Exit code 0, or the Python function returned normally.
120    Success,
121    /// A non-zero exit code or an unhandled exception.
122    Failed,
123    /// Exceeded its timeout and was killed by the worker.
124    TimedOut,
125    /// Killed by the memory watchdog for exceeding its budget.
126    OomKilled,
127    /// Cancelled by a user.
128    Cancelled,
129    /// Killed when a draining worker's grace period ended.
130    Interrupted,
131    /// The worker disappeared.
132    Lost,
133    /// No `Started` arrived in time after the assignment.
134    AssignmentExpired,
135}
136
137/// A worker's state as the master sees it (see archive/PROJECT.md, Worker lifecycle).
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
139#[serde(rename_all = "snake_case")]
140pub enum WorkerState {
141    /// Connected; takes new tasks.
142    Active,
143    /// Finishing its tasks; takes no new ones.
144    Draining,
145    /// Its stream dropped; its tasks may still run. Active again if it reconnects with the
146    /// same incarnation, lost when its lease runs out.
147    Disconnected,
148    /// It deregistered.
149    Offline,
150    /// No heartbeat within the lease: its attempts ended `lost`.
151    Lost,
152}
153
154impl WorkerState {
155    /// Whether the worker is gone (it is kept listed, so its logs can be found).
156    #[must_use]
157    pub const fn is_gone(self) -> bool {
158        matches!(self, Self::Offline | Self::Lost)
159    }
160}
161
162/// What the master does after an attempt ended with a given status.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164pub enum RetryRule {
165    /// Nothing to retry: the attempt succeeded.
166    NotNeeded,
167    /// Retry if the task has retries left; the attempt uses one of them.
168    UsesRetry,
169    /// Run again without using a retry (the attempt wasn't the task's fault).
170    RequeueWithoutRetry,
171    /// Never retried.
172    Never,
173}
174
175impl AttemptStatus {
176    /// What happens after an attempt with this status (see archive/PROJECT.md, Task assignment:
177    /// retries are decided by the master).
178    #[must_use]
179    pub const fn retry_rule(self) -> RetryRule {
180        match self {
181            Self::Success => RetryRule::NotNeeded,
182            Self::Failed | Self::TimedOut | Self::OomKilled | Self::Lost => RetryRule::UsesRetry,
183            Self::Interrupted | Self::AssignmentExpired => RetryRule::RequeueWithoutRetry,
184            Self::Cancelled => RetryRule::Never,
185        }
186    }
187}
188
189/// Implements `Display` as the serialized (snake case) name.
190macro_rules! display_as_serialized {
191    ($($ty:ty),+) => {$(
192        impl fmt::Display for $ty {
193            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194                let value = serde_json::to_value(self).map_err(|_| fmt::Error)?;
195                f.write_str(value.as_str().ok_or(fmt::Error)?)
196            }
197        }
198    )+};
199}
200
201display_as_serialized!(
202    RunKind,
203    RunState,
204    TaskInstanceState,
205    CleanupResult,
206    AttemptStatus,
207    WorkerState
208);