orbit-ir 0.4.0

ORBIT typed intermediate representation (orbit-ir/1), payload validation and expression evaluation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! The compiled workflow document (`orbit-ir/1`).
//!
//! The IR is the contract between compiler and runtime. It is fully resolved:
//! named schemas are inlined, step dependencies are explicit (including those
//! implied by data references), and every expression is typed and checked.

use crate::expr::Expr;
use crate::types::Type;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;

pub const IR_VERSION: &str = "orbit-ir/1";
/// IR version for workflows that use signals, queries, `await` or `compute`
/// steps, or lambdas. Workflows that use none of these keep `orbit-ir/1` (and
/// their definition hashes), so existing deployments are unaffected.
pub const IR_VERSION_2: &str = "orbit-ir/2";
/// Every IR version this crate reads and validates.
pub const SUPPORTED_IR_VERSIONS: &[&str] = &[IR_VERSION, IR_VERSION_2];

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowIr {
    pub ir_version: String,
    pub name: String,
    pub version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// `sha256:<hex>` over the semantic content (excludes `source_map`).
    #[serde(default)]
    pub definition_hash: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    pub input: Type,
    pub output: Type,
    /// Steps in a deterministic topological order.
    pub steps: Vec<StepIr>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<Expr>,
    /// Every worker contract referenced by this workflow.
    pub contracts: BTreeMap<String, TaskContract>,
    /// Typed signals this workflow accepts (`signal <name> { ... }`), by name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub signals: BTreeMap<String, Type>,
    /// Read-only queries over the execution state (`query <name> = <expr>`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub queries: BTreeMap<String, QueryIr>,
    /// `on failure|cancel|timeout { ... }`: steps run after compensation when
    /// the execution fails, is cancelled or times out. Keyed by kind; each list
    /// is in topological order. Unit keys are `on_<kind>:<step>`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub handlers: BTreeMap<String, Vec<StepIr>>,
    /// `limits { ... }`: per-workflow resource limits. The runtime applies the
    /// stricter of these and its own server-wide limits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limits: Option<WorkflowLimits>,
    /// `on event <signal> { ... }`: steps run once per received signal of
    /// that name, alongside the workflow. Keyed by signal. Unit keys are
    /// `on_event:<signal>@<seq>:<step>`; the instance unit
    /// `on_event:<signal>@<seq>` holds the signal payload (`event`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub events: BTreeMap<String, Vec<StepIr>>,
    /// Source locations for diagnostics and tooling (not hashed).
    #[serde(default)]
    pub source_map: BTreeMap<String, SourceLocation>,
}

/// Per-workflow resource limits (each optional).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowLimits {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_fan_out: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_history_events: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_payload_bytes: Option<u64>,
}

/// Names accepted in a `limits { ... }` block.
pub const WORKFLOW_LIMITS: &[&str] = &["max_fan_out", "max_history_events", "max_payload_bytes"];

/// `query <name> = <expr>`: evaluated on demand against the current state.
/// Step outputs read by a query are optional (the step may not have run yet).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QueryIr {
    pub expr: Expr,
    pub output_type: Type,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceLocation {
    pub file: String,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TaskContract {
    pub name: String,
    pub version: String,
    pub input: Type,
    pub output: Type,
    /// True for tasks executed inside the runtime (e.g. `orbit.http.request`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub builtin: bool,
    /// Set when this contract is a child workflow (`workflow "Name"` steps): the
    /// definition hash of the exact child version to start. The contract name is
    /// then `workflow:<Name>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workflow_hash: Option<String>,
    /// `compensated_by "<task>"`: steps calling this task must declare a
    /// compensation that calls the named task (checked by the compiler).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compensated_by: Option<String>,
}

/// Handler kinds, in the order `on <kind>` accepts them.
pub const HANDLER_KINDS: &[&str] = &["failure", "cancel", "timeout"];

/// Unit key of a handler step: `on_<kind>:<step>`.
pub fn handler_key(kind: &str, step: &str) -> String {
    format!("on_{kind}:{step}")
}

/// Key of an event-handler instance: `on_event:<signal>@<seq>`.
pub fn event_instance_key(signal: &str, seq: u64) -> String {
    format!("on_event:{signal}@{seq}")
}

/// `(instance key, signal, step)` for an event-handler step key
/// `on_event:<signal>@<seq>:<step>`.
pub fn parse_event_key(key: &str) -> Option<(&str, &str, &str)> {
    let rest = key.strip_prefix("on_event:")?;
    let (head, step) = rest.split_once(':')?;
    let (signal, seq) = head.split_once('@')?;
    seq.parse::<u64>().ok()?;
    let instance = &key[..key.len() - step.len() - 1];
    Some((instance, signal, step))
}

/// `(kind, step)` for a handler unit key.
pub fn parse_handler_key(key: &str) -> Option<(&str, &str)> {
    let rest = key.strip_prefix("on_")?;
    let (kind, step) = rest.split_once(':')?;
    HANDLER_KINDS.contains(&kind).then_some((kind, step))
}

/// Prefix of contract names that refer to child workflows.
pub const WORKFLOW_CONTRACT_PREFIX: &str = "workflow:";

/// `for <variable> in <items>`: the step runs once per list element.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ForEach {
    pub variable: String,
    pub items: Expr,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_parallel: Option<u32>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StepIr {
    pub id: String,
    pub action: Action,
    /// Direct dependencies, sorted. Explicit `after` plus data references.
    pub dependencies: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition: Option<Expr>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub for_each: Option<ForEach>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compensation: Option<Invocation>,
    /// The type other expressions see when they reference this step.
    pub output_type: Type,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Action {
    Task(Invocation),
    /// Durable timer handled by the runtime.
    Sleep {
        duration_ms: u64,
    },
    /// Start a child workflow. `task` is `workflow:<Name>`; its contract carries
    /// the child's definition hash.
    Workflow(Invocation),
    /// Wait for the next signal of this name; its payload is the step output.
    /// `timeout_ms` fails the step with `SIGNAL_TIMEOUT` if no signal arrives.
    Await {
        signal: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u64>,
    },
    /// Evaluate a pure expression in the runtime; the value is the step output.
    Compute {
        expr: Expr,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Invocation {
    pub task: String,
    pub contract_version: String,
    /// Optional routing constraint: only workers announcing this runtime receive the task.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    pub input: Expr,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<Expr>,
    /// Start-to-close limit for one attempt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// Maximum time the task may wait in the queue before a worker picks it up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub queue_timeout_ms: Option<u64>,
    pub retry: RetryPolicy,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Backoff {
    Fixed,
    Exponential,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RetryPolicy {
    /// Maximum total attempts, including the first.
    pub max_attempts: u32,
    pub backoff: Backoff,
    pub initial_delay_ms: u64,
    pub max_delay_ms: u64,
    /// Error codes that fail the step immediately.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub non_retryable: Vec<String>,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        RetryPolicy {
            max_attempts: 1,
            backoff: Backoff::Fixed,
            initial_delay_ms: 1000,
            max_delay_ms: 60_000,
            non_retryable: vec![],
        }
    }
}

impl RetryPolicy {
    /// Delay before attempt `next_attempt` (2 = first retry).
    pub fn delay_before(&self, next_attempt: u32) -> u64 {
        match self.backoff {
            Backoff::Fixed => self
                .initial_delay_ms
                .min(self.max_delay_ms.max(self.initial_delay_ms)),
            Backoff::Exponential => {
                let exp = next_attempt.saturating_sub(2).min(40);
                self.initial_delay_ms
                    .saturating_mul(1u64 << exp)
                    .min(self.max_delay_ms)
            }
        }
    }
}

impl StepIr {
    pub fn invocation(&self) -> Option<&Invocation> {
        match &self.action {
            Action::Task(i) | Action::Workflow(i) => Some(i),
            Action::Sleep { .. } | Action::Await { .. } | Action::Compute { .. } => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IrError(pub String);

impl fmt::Display for IrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for IrError {}

impl WorkflowIr {
    pub fn step(&self, id: &str) -> Option<&StepIr> {
        self.steps.iter().find(|s| s.id == id)
    }

    /// Canonical hash of the semantic content of the workflow.
    pub fn compute_hash(&self) -> String {
        let mut copy = self.clone();
        copy.definition_hash = String::new();
        copy.source_map.clear();
        let bytes = serde_json::to_vec(&copy).expect("IR serialises");
        let digest = Sha256::digest(&bytes);
        let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
        format!("sha256:{hex}")
    }

    pub fn seal(mut self) -> Self {
        self.definition_hash = self.compute_hash();
        self
    }

    pub fn from_json(text: &str) -> Result<WorkflowIr, IrError> {
        // Check the version before attempting a full parse so that future IR
        // versions produce a clear error instead of a confusing schema error.
        let raw: serde_json::Value =
            serde_json::from_str(text).map_err(|e| IrError(format!("invalid IR JSON: {e}")))?;
        match raw.get("ir_version").and_then(|v| v.as_str()) {
            Some(v) if SUPPORTED_IR_VERSIONS.contains(&v) => {}
            Some(other) => {
                return Err(IrError(format!(
                    "unsupported IR version `{other}`; this runtime supports {}",
                    SUPPORTED_IR_VERSIONS
                        .iter()
                        .map(|v| format!("`{v}`"))
                        .collect::<Vec<_>>()
                        .join(", ")
                )))
            }
            None => return Err(IrError("missing `ir_version`".into())),
        }
        let ir: WorkflowIr =
            serde_json::from_value(raw).map_err(|e| IrError(format!("malformed IR: {e}")))?;
        ir.validate()?;
        Ok(ir)
    }

    /// Enforce the IR invariants from RFC-0001 §7.3. The runtime calls this on
    /// every definition it accepts, so a hand-edited IR cannot bypass them.
    pub fn validate(&self) -> Result<(), IrError> {
        let e = |m: String| Err(IrError(m));
        if !SUPPORTED_IR_VERSIONS.contains(&self.ir_version.as_str()) {
            return e(format!("unsupported IR version `{}`", self.ir_version));
        }
        if self.ir_version == IR_VERSION && self.uses_v2_features() {
            return e(format!(
                "`{IR_VERSION}` cannot use signals, queries, `await`, `compute` or lambdas; use `{IR_VERSION_2}`"
            ));
        }
        if self.name.is_empty() || self.version.is_empty() {
            return e("workflow name and version are required".into());
        }
        if !matches!(self.input, Type::Record { .. }) {
            return e("workflow input must be a record type".into());
        }
        let mut ids = HashSet::new();
        for s in &self.steps {
            if !ids.insert(s.id.as_str()) {
                return e(format!("duplicate step id `{}`", s.id));
            }
        }
        let mut seen = HashSet::new();
        for s in &self.steps {
            for d in &s.dependencies {
                if !ids.contains(d.as_str()) {
                    return e(format!("step `{}` depends on unknown step `{d}`", s.id));
                }
                // Steps are in topological order, so dependencies must already be seen.
                if !seen.contains(d.as_str()) {
                    return e(format!(
                        "dependency graph is cyclic or not topologically ordered at `{}` -> `{d}`",
                        s.id
                    ));
                }
            }
            let mut refs = vec![];
            if let Some(c) = &s.condition {
                c.step_refs(&mut refs);
            }
            if let Some(f) = &s.for_each {
                f.items.step_refs(&mut refs);
                if f.max_parallel == Some(0) {
                    return e(format!("step `{}`: max_parallel must be at least 1", s.id));
                }
            }
            match &s.action {
                Action::Compute { expr } => expr.step_refs(&mut refs),
                Action::Await { signal, .. } if !self.signals.contains_key(signal) => {
                    return e(format!(
                        "step `{}` awaits undeclared signal `{signal}`",
                        s.id
                    ))
                }
                _ => {}
            }
            if let Some(inv) = s.invocation() {
                inv.input.step_refs(&mut refs);
                if let Some(k) = &inv.idempotency_key {
                    k.step_refs(&mut refs);
                }
            }
            let ancestors = self.ancestors(&s.id);
            for r in &refs {
                if !ancestors.contains(r.as_str()) {
                    return e(format!(
                        "step `{}` reads `{r}` which is not one of its dependencies",
                        s.id
                    ));
                }
            }
            for inv in s.invocation().into_iter().chain(s.compensation.as_ref()) {
                match self.contracts.get(&inv.task) {
                    None => {
                        return e(format!(
                            "step `{}` uses task `{}` with no contract",
                            s.id, inv.task
                        ))
                    }
                    Some(c) if c.version != inv.contract_version => {
                        return e(format!(
                            "step `{}` expects {}@{} but contract is {}",
                            s.id, inv.task, inv.contract_version, c.version
                        ))
                    }
                    _ => {}
                }
                if inv.retry.max_attempts == 0 {
                    return e(format!(
                        "step `{}`: retry attempts must be at least 1",
                        s.id
                    ));
                }
            }
            seen.insert(s.id.as_str());
        }
        for (kind, steps) in &self.handlers {
            if !HANDLER_KINDS.contains(&kind.as_str()) {
                return e(format!("unknown handler kind `{kind}`"));
            }
            for s in steps {
                if let Some(inv) = s.invocation() {
                    if self.contracts.get(&inv.task).map(|c| &c.version)
                        != Some(&inv.contract_version)
                    {
                        return e(format!(
                            "handler step `{}` uses task `{}` with no matching contract",
                            s.id, inv.task
                        ));
                    }
                }
            }
        }
        if !self.definition_hash.is_empty() && self.definition_hash != self.compute_hash() {
            return e(
                "definition_hash does not match the IR content (was the file modified?)".into(),
            );
        }
        Ok(())
    }

    /// The IR version this workflow needs: `orbit-ir/2` when it uses any
    /// feature introduced with it, `orbit-ir/1` otherwise.
    pub fn required_ir_version(&self) -> &'static str {
        if self.uses_v2_features() {
            IR_VERSION_2
        } else {
            IR_VERSION
        }
    }

    /// An `on event` step by signal and id.
    pub fn event_step(&self, signal: &str, id: &str) -> Option<&StepIr> {
        self.events.get(signal)?.iter().find(|s| s.id == id)
    }

    /// A handler step by kind and id.
    pub fn handler_step(&self, kind: &str, id: &str) -> Option<&StepIr> {
        self.handlers.get(kind)?.iter().find(|s| s.id == id)
    }

    fn uses_v2_features(&self) -> bool {
        let lambda = |e: &Expr| e.contains_lambda();
        !self.signals.is_empty()
            || !self.queries.is_empty()
            || !self.handlers.is_empty()
            || self.limits.is_some()
            || !self.events.is_empty()
            || self.result.as_ref().is_some_and(lambda)
            || self.steps.iter().any(|s| {
                matches!(s.action, Action::Await { .. } | Action::Compute { .. })
                    || s.condition.as_ref().is_some_and(lambda)
                    || s.for_each.as_ref().is_some_and(|f| lambda(&f.items))
                    || s.invocation()
                        .into_iter()
                        .chain(s.compensation.as_ref())
                        .any(|i| lambda(&i.input) || i.idempotency_key.as_ref().is_some_and(lambda))
            })
    }

    /// Transitive dependencies of a step.
    pub fn ancestors(&self, id: &str) -> HashSet<&str> {
        let by_id: HashMap<&str, &StepIr> = self.steps.iter().map(|s| (s.id.as_str(), s)).collect();
        let mut out = HashSet::new();
        let mut stack: Vec<&str> = by_id
            .get(id)
            .map(|s| s.dependencies.iter().map(String::as_str).collect())
            .unwrap_or_default();
        while let Some(n) = stack.pop() {
            if out.insert(n) {
                if let Some(s) = by_id.get(n) {
                    stack.extend(s.dependencies.iter().map(String::as_str));
                }
            }
        }
        out
    }
}