Skip to main content

orbit_runtime/
decide.rs

1//! The deterministic workflow decider.
2//!
3//! `decide(state, definition, now)` inspects an execution and returns the
4//! events that should happen next (schedule ready steps, fan out `for` steps,
5//! fire timers, apply retry policy, start compensation, finish the
6//! workflow...). It performs no I/O. The engine applies the events, persists
7//! them, and calls `decide` again until it returns nothing.
8//!
9//! Unit keys: `step` for a step, `step[i]` for element `i` of a `for` step,
10//! and `compensate:<unit>` for the compensation of a unit.
11
12use crate::model::*;
13use orbit_ir::{eval, Action, Invocation, Scope, StepIr, WorkflowIr};
14use serde_json::Value;
15
16/// Expression scope over an execution, optionally with a loop variable bound
17/// and with one step's output overridden (an element's own output inside its
18/// compensation).
19pub struct StateScope<'a> {
20    pub state: &'a ExecutionState,
21    pub local: Option<(&'a str, &'a Value)>,
22    pub own_output: Option<(&'a str, &'a Value)>,
23}
24
25impl<'a> StateScope<'a> {
26    pub fn new(state: &'a ExecutionState) -> Self {
27        StateScope {
28            state,
29            local: None,
30            own_output: None,
31        }
32    }
33}
34
35impl Scope for StateScope<'_> {
36    fn input(&self) -> &Value {
37        &self.state.input
38    }
39
40    fn step_output(&self, step: &str) -> Option<&Value> {
41        if let Some((s, v)) = self.own_output {
42            if s == step {
43                return Some(v);
44            }
45        }
46        let u = self.state.units.get(step)?;
47        match u.status() {
48            UnitStatus::Succeeded | UnitStatus::Skipped => u.output.as_ref(),
49            _ => None,
50        }
51    }
52
53    fn execution_field(&self, field: &str) -> Option<Value> {
54        Some(Value::String(match field {
55            "id" => self.state.id.clone(),
56            "workflow" => self.state.workflow.clone(),
57            "version" => self.state.version.clone(),
58            _ => return None,
59        }))
60    }
61
62    fn local(&self, name: &str) -> Option<&Value> {
63        self.local.filter(|(n, _)| *n == name).map(|(_, v)| v)
64    }
65}
66
67/// The invocation behind a unit key.
68pub fn invocation<'a>(def: &'a WorkflowIr, key: &str) -> Option<&'a Invocation> {
69    let k = parse_key(key);
70    let step = def.step(k.step)?;
71    if k.compensation {
72        step.compensation.as_ref()
73    } else {
74        step.invocation()
75    }
76}
77
78fn unit(state: &ExecutionState, key: &str) -> UnitState {
79    state.units.get(key).cloned().unwrap_or_default()
80}
81
82/// The `for` element bound to a unit, if any: (variable, value).
83fn element<'a>(
84    state: &'a ExecutionState,
85    def: &'a WorkflowIr,
86    key: &str,
87) -> Option<(&'a str, &'a Value)> {
88    let k = parse_key(key);
89    let index = k.index?;
90    let fe = def.step(k.step)?.for_each.as_ref()?;
91    let items = state.units.get(k.step)?.input.as_ref()?.as_array()?;
92    Some((fe.variable.as_str(), items.get(index)?))
93}
94
95/// Evaluate the payload and idempotency key for a unit's first attempt.
96fn schedule(state: &ExecutionState, def: &WorkflowIr, key: &str, inv: &Invocation) -> Event {
97    let k = parse_key(key);
98    let mut scope = StateScope::new(state);
99    scope.local = element(state, def, key);
100    // Inside the compensation of an element, `<step>` is that element's output.
101    let element_unit = if k.compensation && k.index.is_some() {
102        key.strip_prefix("compensate:")
103    } else {
104        None
105    };
106    let own = element_unit
107        .and_then(|e| state.units.get(e))
108        .and_then(|u| u.output.as_ref());
109    if let Some(v) = own {
110        scope.own_output = Some((k.step, v));
111    }
112    let fail = |code: &str, msg: String| Event::StepFailed {
113        step: key.into(),
114        error: TaskError::new(code, msg, false),
115    };
116    let mut input = match eval(&inv.input, &scope) {
117        Ok(v) => v,
118        Err(e) => return fail(codes::EXPRESSION_ERROR, format!("evaluating input: {e}")),
119    };
120    if let Some(contract) = def.contracts.get(&inv.task) {
121        contract.input.apply_defaults(&mut input);
122        if let Err(e) = contract.input.validate(&input, false) {
123            return fail(
124                codes::INPUT_CONTRACT_VIOLATION,
125                format!("input for `{}` is invalid at {e}", inv.task),
126            );
127        }
128    }
129    let idempotency_key = match &inv.idempotency_key {
130        Some(expr) => match eval(expr, &scope) {
131            Ok(Value::String(s)) => s,
132            Ok(Value::Null) => format!("{}/{key}", state.id),
133            Ok(other) => other.to_string(),
134            Err(e) => {
135                return fail(
136                    codes::EXPRESSION_ERROR,
137                    format!("evaluating idempotency_key: {e}"),
138                )
139            }
140        },
141        None => format!("{}/{key}", state.id),
142    };
143    Event::StepScheduled {
144        step: key.into(),
145        attempt: 1,
146        input,
147        idempotency_key,
148        redelivery: false,
149    }
150}
151
152/// Retry-or-fail decision after a failed attempt.
153fn after_failure(
154    state: &ExecutionState,
155    key: &str,
156    u: &UnitState,
157    inv: Option<&Invocation>,
158    now: u64,
159) -> Event {
160    let error = u
161        .last_error
162        .clone()
163        .unwrap_or_else(|| TaskError::new("UNKNOWN", "attempt failed", true));
164    let is_compensation = key.starts_with("compensate:");
165    let aborting = state.abort.is_some() && !is_compensation;
166    if let Some(inv) = inv {
167        let policy = &inv.retry;
168        let retryable = error.retryable && !policy.non_retryable.contains(&error.code);
169        if retryable && !aborting && u.attempt < policy.max_attempts {
170            let next = u.attempt + 1;
171            let delay = policy.delay_before(next);
172            return Event::RetryScheduled {
173                step: key.into(),
174                next_attempt: next,
175                delay_ms: delay,
176                fire_at_ms: now + delay,
177            };
178        }
179        if retryable && u.attempt >= policy.max_attempts && policy.max_attempts > 1 {
180            let mut e = error.clone();
181            e.message = format!("{} (gave up after {} attempts)", e.message, u.attempt);
182            return Event::StepFailed {
183                step: key.into(),
184                error: e,
185            };
186        }
187    }
188    Event::StepFailed {
189        step: key.into(),
190        error,
191    }
192}
193
194fn finish(state: &ExecutionState, outcome: CompensationOutcome) -> Event {
195    match &state.abort {
196        Some(AbortReason::Cancelled { .. }) => Event::WorkflowCancelled {
197            compensation: outcome,
198        },
199        Some(AbortReason::TimedOut) => Event::WorkflowTimedOut {
200            compensation: outcome,
201        },
202        Some(AbortReason::Failed { error }) => Event::WorkflowFailed {
203            error: error.clone(),
204            compensation: outcome,
205        },
206        None => Event::WorkflowFailed {
207            error: TaskError::new("UNKNOWN", "workflow aborted", false),
208            compensation: outcome,
209        },
210    }
211}
212
213/// Compute the next events. Returns an empty vector at a fixpoint.
214pub fn decide(state: &ExecutionState, def: &WorkflowIr, now: u64) -> Vec<Event> {
215    if state.status.is_terminal() {
216        return vec![];
217    }
218    let mut out = vec![];
219
220    // 1. Workflow deadline.
221    if state.status == WorkflowStatus::Running && state.abort.is_none() {
222        if let Some(t) = def.timeout_ms {
223            if now >= state.created_at_ms + t {
224                return vec![Event::WorkflowTimeoutReached {}];
225            }
226        }
227    }
228
229    // 2. Per-unit transitions: deadlines, timers, retries, redelivery.
230    for (key, u) in &state.units {
231        let inv = invocation(def, key);
232        match u.status() {
233            UnitStatus::Dispatched => {
234                if u.deadline_ms.is_some_and(|d| now >= d) {
235                    out.push(Event::StepAttemptFailed {
236                        step: key.clone(),
237                        attempt: u.attempt,
238                        error: TaskError::new(
239                            codes::TIMEOUT,
240                            format!("attempt {} exceeded its timeout", u.attempt),
241                            true,
242                        ),
243                    });
244                }
245            }
246            UnitStatus::Scheduled => {
247                let qt = inv.and_then(|i| i.queue_timeout_ms);
248                if let (Some(qt), Some(at)) = (qt, u.scheduled_at_ms) {
249                    if !u.redelivery && now >= at + qt {
250                        out.push(Event::StepAttemptFailed {
251                            step: key.clone(),
252                            attempt: u.attempt,
253                            error: TaskError::new(
254                                codes::QUEUE_TIMEOUT,
255                                "no worker picked up the task before queue_timeout",
256                                false,
257                            ),
258                        });
259                    }
260                }
261            }
262            UnitStatus::Waiting => {
263                if u.wake_at_ms.is_some_and(|w| now >= w) {
264                    out.push(Event::TimerFired { step: key.clone() });
265                }
266            }
267            UnitStatus::RetryWait => {
268                if u.wake_at_ms.is_some_and(|w| now >= w) {
269                    if state.abort.is_some() && !key.starts_with("compensate:") {
270                        out.push(Event::StepFailed {
271                            step: key.clone(),
272                            error: u.last_error.clone().unwrap_or_else(|| {
273                                TaskError::new(codes::CANCELLED, "aborted", false)
274                            }),
275                        });
276                    } else {
277                        out.push(Event::StepScheduled {
278                            step: key.clone(),
279                            attempt: u.attempt,
280                            input: u.input.clone().unwrap_or(Value::Null),
281                            idempotency_key: u.idempotency_key.clone().unwrap_or_default(),
282                            redelivery: false,
283                        });
284                    }
285                }
286            }
287            UnitStatus::AttemptFailed => out.push(after_failure(state, key, u, inv, now)),
288            UnitStatus::Uncertain => out.push(Event::StepScheduled {
289                step: key.clone(),
290                attempt: u.attempt,
291                input: u.input.clone().unwrap_or(Value::Null),
292                idempotency_key: u.idempotency_key.clone().unwrap_or_default(),
293                redelivery: true,
294            }),
295            _ => {}
296        }
297    }
298    if !out.is_empty() {
299        return out;
300    }
301
302    match state.status {
303        WorkflowStatus::Running => decide_running(state, def, now),
304        WorkflowStatus::Compensating => decide_compensating(state, def),
305        _ => vec![],
306    }
307}
308
309fn deps_done(state: &ExecutionState, step: &StepIr) -> bool {
310    step.dependencies.iter().all(|d| {
311        matches!(
312            unit(state, d).status(),
313            UnitStatus::Succeeded | UnitStatus::Skipped
314        )
315    })
316}
317
318/// Element unit keys of a fanned-out step, in order.
319fn element_keys(state: &ExecutionState, step: &str) -> Vec<String> {
320    let n = state
321        .units
322        .get(step)
323        .and_then(|u| u.input.as_ref())
324        .and_then(Value::as_array)
325        .map(Vec::len)
326        .unwrap_or(0);
327    (0..n).map(|i| element_key(step, i)).collect()
328}
329
330fn in_flight(status: UnitStatus) -> bool {
331    matches!(
332        status,
333        UnitStatus::Scheduled
334            | UnitStatus::Dispatched
335            | UnitStatus::AttemptFailed
336            | UnitStatus::Uncertain
337            | UnitStatus::RetryWait
338    )
339}
340
341/// Progress a running `for` step: schedule elements within `max_parallel`,
342/// and resolve the step once every element is done (or one failed).
343fn advance_fan_out(state: &ExecutionState, def: &WorkflowIr, step: &StepIr, out: &mut Vec<Event>) {
344    let keys = element_keys(state, &step.id);
345    let units: Vec<UnitState> = keys.iter().map(|k| unit(state, k)).collect();
346    if let Some(failed) = units.iter().find(|u| u.status() == UnitStatus::Failed) {
347        out.push(Event::StepFailed {
348            step: step.id.clone(),
349            error: failed
350                .error
351                .clone()
352                .unwrap_or_else(|| TaskError::new("UNKNOWN", "element failed", false)),
353        });
354        return;
355    }
356    if units.iter().all(|u| u.status() == UnitStatus::Succeeded) {
357        let output = Value::Array(
358            units
359                .iter()
360                .map(|u| u.output.clone().unwrap_or(Value::Null))
361                .collect(),
362        );
363        out.push(Event::StepSucceeded {
364            step: step.id.clone(),
365            attempt: 1,
366            output,
367        });
368        return;
369    }
370    let Some(inv) = step.invocation() else { return };
371    let limit = step
372        .for_each
373        .as_ref()
374        .and_then(|f| f.max_parallel)
375        .map(|n| n as usize)
376        .unwrap_or(usize::MAX);
377    let mut running = units.iter().filter(|u| in_flight(u.status())).count();
378    for (key, u) in keys.iter().zip(&units) {
379        if running >= limit {
380            break;
381        }
382        if u.status() == UnitStatus::Pending {
383            out.push(schedule(state, def, key, inv));
384            running += 1;
385        }
386    }
387}
388
389fn decide_running(state: &ExecutionState, def: &WorkflowIr, now: u64) -> Vec<Event> {
390    let mut out = vec![];
391    if state.abort.is_none() {
392        for step in &def.steps {
393            let u = unit(state, &step.id);
394            if u.status() == UnitStatus::Running {
395                advance_fan_out(state, def, step, &mut out);
396                continue;
397            }
398            if u.status() != UnitStatus::Pending || !deps_done(state, step) {
399                continue;
400            }
401            if let Some(cond) = &step.condition {
402                match eval(cond, &StateScope::new(state)) {
403                    Ok(Value::Bool(true)) => {}
404                    Ok(Value::Bool(false)) | Ok(Value::Null) => {
405                        out.push(Event::StepSkipped {
406                            step: step.id.clone(),
407                            reason: "`when` condition was false".into(),
408                        });
409                        continue;
410                    }
411                    Ok(other) => {
412                        out.push(Event::StepFailed {
413                            step: step.id.clone(),
414                            error: TaskError::new(
415                                codes::EXPRESSION_ERROR,
416                                format!("`when` evaluated to {other}, expected Bool"),
417                                false,
418                            ),
419                        });
420                        continue;
421                    }
422                    Err(e) => {
423                        out.push(Event::StepFailed {
424                            step: step.id.clone(),
425                            error: TaskError::new(
426                                codes::EXPRESSION_ERROR,
427                                format!("evaluating `when`: {e}"),
428                                false,
429                            ),
430                        });
431                        continue;
432                    }
433                }
434            }
435            if let Some(fe) = &step.for_each {
436                match eval(&fe.items, &StateScope::new(state)) {
437                    Ok(Value::Array(items)) => out.push(Event::StepFanOut {
438                        step: step.id.clone(),
439                        items,
440                    }),
441                    Ok(Value::Null) => out.push(Event::StepFanOut {
442                        step: step.id.clone(),
443                        items: vec![],
444                    }),
445                    Ok(other) => out.push(Event::StepFailed {
446                        step: step.id.clone(),
447                        error: TaskError::new(
448                            codes::EXPRESSION_ERROR,
449                            format!("`for` expected a list, got {other}"),
450                            false,
451                        ),
452                    }),
453                    Err(e) => out.push(Event::StepFailed {
454                        step: step.id.clone(),
455                        error: TaskError::new(
456                            codes::EXPRESSION_ERROR,
457                            format!("evaluating `for`: {e}"),
458                            false,
459                        ),
460                    }),
461                }
462                continue;
463            }
464            match &step.action {
465                Action::Sleep { duration_ms } => out.push(Event::TimerStarted {
466                    step: step.id.clone(),
467                    fire_at_ms: now + duration_ms,
468                }),
469                Action::Task(inv) | Action::Workflow(inv) => {
470                    out.push(schedule(state, def, &step.id, inv))
471                }
472            }
473        }
474        if !out.is_empty() {
475            return out;
476        }
477        let all_done = def
478            .steps
479            .iter()
480            .all(|s| unit(state, &s.id).status().is_terminal());
481        if all_done {
482            let output = match &def.result {
483                Some(expr) => match eval(expr, &StateScope::new(state)) {
484                    Ok(v) => v,
485                    Err(e) => {
486                        return vec![Event::WorkflowFailed {
487                            error: TaskError::new(
488                                codes::EXPRESSION_ERROR,
489                                format!("evaluating `return`: {e}"),
490                                false,
491                            ),
492                            compensation: CompensationOutcome::None,
493                        }]
494                    }
495                },
496                None => Value::Object(Default::default()),
497            };
498            if let Err(e) = def.output.validate(&output, false) {
499                return vec![Event::WorkflowFailed {
500                    error: TaskError::new(
501                        codes::OUTPUT_CONTRACT_VIOLATION,
502                        format!("workflow output is invalid at {e}"),
503                        false,
504                    ),
505                    compensation: CompensationOutcome::None,
506                }];
507            }
508            return vec![Event::WorkflowCompleted { output }];
509        }
510        return out;
511    }
512
513    // Aborting: withdraw work that has not started, wait for in-flight work,
514    // then compensate completed units in reverse completion order.
515    let mut waiting = false;
516    let withdraw =
517        |key: &str, u: &UnitState, out: &mut Vec<Event>, waiting: &mut bool| match u.status() {
518            UnitStatus::Pending | UnitStatus::Waiting | UnitStatus::RetryWait => {
519                out.push(Event::StepCancelled { step: key.into() })
520            }
521            UnitStatus::Scheduled if !u.redelivery => {
522                out.push(Event::StepCancelled { step: key.into() })
523            }
524            UnitStatus::Scheduled
525            | UnitStatus::Dispatched
526            | UnitStatus::AttemptFailed
527            | UnitStatus::Uncertain => *waiting = true,
528            _ => {}
529        };
530    for step in &def.steps {
531        let u = unit(state, &step.id);
532        if u.status() == UnitStatus::Running {
533            let mut element_waiting = false;
534            let mut failed = None;
535            for key in element_keys(state, &step.id) {
536                let eu = unit(state, &key);
537                if eu.status() == UnitStatus::Failed && failed.is_none() {
538                    failed = eu.error.clone();
539                }
540                withdraw(&key, &eu, &mut out, &mut element_waiting);
541            }
542            if element_waiting {
543                waiting = true;
544            } else {
545                // Every element is resolved: close the step itself.
546                out.push(match failed {
547                    Some(error) => Event::StepFailed {
548                        step: step.id.clone(),
549                        error,
550                    },
551                    None => Event::StepCancelled {
552                        step: step.id.clone(),
553                    },
554                });
555            }
556        } else {
557            withdraw(&step.id, &u, &mut out, &mut waiting);
558        }
559    }
560    if !out.is_empty() || waiting {
561        return out;
562    }
563    // Units that succeeded and have a compensation: whole steps, or each
564    // succeeded element of a `for` step.
565    let mut done: Vec<(String, u64)> = vec![];
566    for s in def.steps.iter().filter(|s| s.compensation.is_some()) {
567        let keys = if s.for_each.is_some() {
568            element_keys(state, &s.id)
569        } else {
570            vec![s.id.clone()]
571        };
572        for key in keys {
573            if let Some(u) = state.units.get(&key) {
574                if u.status() == UnitStatus::Succeeded {
575                    done.push((key, u.succeeded_seq.unwrap_or(0)));
576                }
577            }
578        }
579    }
580    done.sort_by_key(|d| std::cmp::Reverse(d.1));
581    if done.is_empty() {
582        return vec![finish(state, CompensationOutcome::None)];
583    }
584    let reason = match &state.abort {
585        Some(AbortReason::Failed { error }) => error.message.clone(),
586        Some(AbortReason::Cancelled { reason }) => format!("cancelled: {reason}"),
587        Some(AbortReason::TimedOut) => "workflow timed out".into(),
588        None => String::new(),
589    };
590    vec![Event::CompensationStarted {
591        reason,
592        steps: done.into_iter().map(|(s, _)| s).collect(),
593    }]
594}
595
596fn decide_compensating(state: &ExecutionState, def: &WorkflowIr) -> Vec<Event> {
597    // Compensations run one at a time, newest completed unit first (Saga).
598    for step in &state.compensation_order {
599        let key = compensation_key(step);
600        let u = unit(state, &key);
601        match u.status() {
602            UnitStatus::Succeeded => continue,
603            UnitStatus::Failed | UnitStatus::Cancelled => {
604                let error = u
605                    .error
606                    .unwrap_or_else(|| TaskError::new("UNKNOWN", "compensation failed", false));
607                return vec![
608                    Event::CompensationFailed {
609                        step: step.clone(),
610                        error,
611                    },
612                    finish(state, CompensationOutcome::Failed),
613                ];
614            }
615            UnitStatus::Pending => {
616                return match invocation(def, &key) {
617                    Some(inv) => vec![schedule(state, def, &key, inv)],
618                    None => vec![Event::StepFailed {
619                        step: key,
620                        error: TaskError::new("UNKNOWN", "missing compensation", false),
621                    }],
622                };
623            }
624            _ => return vec![],
625        }
626    }
627    vec![
628        Event::CompensationCompleted {},
629        finish(state, CompensationOutcome::Completed),
630    ]
631}