Skip to main content

vlo_kernel/
classify.rs

1//! Event classification. The kernel routes on the header alone; it never parses a
2//! payload to decide what an event means.
3
4use vlo_types::{Cause, EventInput, Kind, Status, START_STEP_ID};
5
6use crate::error::{code, err_step, KResult};
7
8/// Step id of the run-level cancel marker.
9pub const CANCEL_STEP_ID: &str = "cancel";
10/// Step id of the nondeterminism marker written by the re-fold check.
11pub const NONDETERMINISM_STEP_ID: &str = "nondeterminism";
12/// Step id of the marker the host writes when a reducer throws (`WorkflowFailure`).
13pub const FAIL_STEP_ID: &str = "fail";
14/// Step id of the marker a `complete` command writes.
15pub const COMPLETE_STEP_ID: &str = "complete";
16/// Step id of the marker a `continue_as_new` command writes.
17pub const CONTINUE_STEP_ID: &str = "continue";
18/// Suffix of the deadline timer an `await_signal` with `timeout_ms` reserves beside its
19/// signal step: signal `x` races timer `x:timeout`. Whichever settles first closes the
20/// other as `cancelled`, so the reducer only ever sees the winner.
21pub const TIMEOUT_SUFFIX: &str = ":timeout";
22
23/// Step id of the deadline timer paired with signal step `step_id`.
24pub fn timeout_step_id(step_id: &str) -> String {
25    format!("{step_id}{TIMEOUT_SUFFIX}")
26}
27
28/// The signal step a `<id>:timeout` timer is paired with, or `None` when `step_id` does
29/// not carry the suffix. The caller still checks that a signal step of that id is open.
30pub fn timeout_owner(step_id: &str) -> Option<&str> {
31    step_id
32        .strip_suffix(TIMEOUT_SUFFIX)
33        .filter(|owner| !owner.is_empty())
34}
35
36/// How `prepare_event` routes an event, decided from the header alone.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Class {
39    /// The run's first event. Calls `init(input)` then `on.started`.
40    Started,
41    /// Terminal task result: `succeeded` or `failed`.
42    TaskResult,
43    /// Worker accepted the push.
44    TaskRunning,
45    /// Host planned a retry; the step goes back to `scheduled` on the next attempt.
46    TaskRetrying,
47    /// The host cancelled the task (lifecycle only).
48    TaskCancelled,
49    /// A timer step fired.
50    TimerFired,
51    /// A signal reached a parked step.
52    SignalDelivered,
53    /// A child run reached a terminal status.
54    ChildDone,
55    /// The `cancel` marker: the user cancelled the run.
56    UserCancel,
57    /// The reducer threw; the host reports the failure rather than folding it.
58    RunFailed,
59    /// The `nondeterminism` marker: a re-fold diverged, so the run fails.
60    NondeterminismDetected,
61}
62
63impl Class {
64    /// Whether this class calls the reducer. The rest are pure bookkeeping.
65    pub fn is_reduce(self) -> bool {
66        matches!(
67            self,
68            Class::Started
69                | Class::TaskResult
70                | Class::TimerFired
71                | Class::SignalDelivered
72                | Class::ChildDone
73        )
74    }
75}
76
77/// Route an event by `kind`, `status` and, for markers, `step_id`.
78///
79/// Errors with `invalid_event` for a combination the kernel has no route for.
80pub fn classify(event: &EventInput) -> KResult<Class> {
81    let invalid = |what: &str| {
82        Err(err_step(
83            code::INVALID_EVENT,
84            format!("{what}: kind={:?} status={:?}", event.kind, event.status),
85            &event.step_id,
86        ))
87    };
88
89    match event.kind {
90        Kind::Marker => match event.step_id.as_str() {
91            START_STEP_ID if event.status == Status::Succeeded => Ok(Class::Started),
92            CANCEL_STEP_ID => Ok(Class::UserCancel),
93            FAIL_STEP_ID if event.status == Status::Failed => Ok(Class::RunFailed),
94            NONDETERMINISM_STEP_ID if event.cause == Some(Cause::NondeterminismDetected) => {
95                Ok(Class::NondeterminismDetected)
96            }
97            _ => invalid("unroutable marker"),
98        },
99        Kind::Task => match event.status {
100            Status::Succeeded | Status::Failed => Ok(Class::TaskResult),
101            Status::Running => Ok(Class::TaskRunning),
102            Status::Retrying => Ok(Class::TaskRetrying),
103            Status::Cancelled => Ok(Class::TaskCancelled),
104            _ => invalid("task events never carry this status"),
105        },
106        Kind::Timer => match event.status {
107            Status::Succeeded => Ok(Class::TimerFired),
108            _ => invalid("timer events only fire with status succeeded"),
109        },
110        Kind::Signal => match event.status {
111            Status::Succeeded => Ok(Class::SignalDelivered),
112            _ => invalid("signal events only arrive with status succeeded"),
113        },
114        Kind::Child => match event.status {
115            Status::Succeeded | Status::Failed | Status::Cancelled => Ok(Class::ChildDone),
116            _ => invalid("child events only carry a terminal status"),
117        },
118    }
119}