dataflow_rs/engine/steps.rs
1//! The authored step grammar: how a workflow's `tasks` array is read.
2//!
3//! An element of `tasks` is either a [`Task`] or a [`TaskGroup`], and the
4//! parser flattens that tree into `Workflow::tasks` at deserialization time so
5//! the executor keeps walking a flat slice. This module owns both halves of
6//! that grammar:
7//!
8//! - `flatten` — the parser, which builds `Vec<Task>` and fails on the first
9//! malformed element.
10//! - [`walk_authored_steps`] — a public walker over the *authored* JSON, which
11//! never fails and yields every node with the coordinate the author typed.
12//!
13//! They live together deliberately. The group test and the depth cap are the
14//! two facts a downstream host would otherwise have to mirror, and keeping the
15//! parser and the walker in one file puts both users of those facts on screen
16//! for anyone who changes them.
17//!
18//! # Why a host needs the authored shape
19//!
20//! By the time a host holds a [`Workflow`](crate::Workflow), the tree is gone:
21//! `tasks` is flat and `Task::group_starts` is not part of the stable API. But
22//! a validation error, a lint finding or a dependency extraction has to point
23//! at `tasks[1].tasks[0].id` — the coordinate in the document the author
24//! actually wrote. That is what this walker provides.
25
26use super::task::{Task, TaskGroup};
27use serde::Deserialize;
28use serde::de::{Deserializer, Error as DeError};
29use serde_json::Value;
30
31/// Maximum group nesting the parser accepts.
32///
33/// Deeper than this is a generated-JSON accident rather than an authored
34/// control-flow shape, and the bound keeps the per-task `group_starts` vector
35/// trivially small.
36///
37/// Public so a host validating authored JSON reads the engine's real limit
38/// instead of copying the number. Depth counts *enclosing groups*: a top-level
39/// group is at depth 0, so groups are accepted at depths `0..MAX_GROUP_DEPTH`
40/// and a group at `MAX_GROUP_DEPTH` is rejected by the parser and reported as
41/// [`StepKind::TooDeep`] by the walker.
42pub const MAX_GROUP_DEPTH: usize = 8;
43
44/// Whether this authored step element parses as a task group.
45///
46/// The test is **presence of a `tasks` key, nothing else** — the same test the
47/// parser makes. In particular a `tasks` key holding a non-array is still a
48/// group, and a malformed one: the parser will reject it as a bad group rather
49/// than silently reading it as a task.
50///
51/// An element carrying neither `tasks` nor `function` is *not* a group, so a
52/// caller reports a broken task — which is what the parser's own diagnostic
53/// says (`missing field 'function'`).
54///
55/// ```
56/// use dataflow_rs::engine::steps::is_group;
57/// use serde_json::json;
58///
59/// assert!(is_group(&json!({"id": "g", "tasks": []})));
60/// assert!(
61/// is_group(&json!({"id": "g", "tasks": "oops"})),
62/// "presence of the key, not its type — this is a malformed group"
63/// );
64/// assert!(!is_group(&json!({"id": "t", "function": {"name": "map"}})));
65/// assert!(!is_group(&json!({"id": "t"})), "neither key: a broken task");
66/// assert!(!is_group(&json!("not even an object")));
67/// ```
68#[inline]
69pub fn is_group(step: &Value) -> bool {
70 step.get("tasks").is_some()
71}
72
73/// What an authored step element is.
74///
75/// Deliberately not `#[non_exhaustive]`: a caller matching on this is deciding
76/// how to report a node, and a fourth kind would need that decision revisited
77/// at every site.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum StepKind {
80 /// A task — or an element malformed enough that it is not a group either.
81 Leaf,
82 /// A task group. Its members follow it in the walk.
83 Group,
84 /// A group nested at or beyond [`MAX_GROUP_DEPTH`]. The parser rejects the
85 /// whole workflow here; the walker reports it and does **not** descend, so
86 /// nothing is silently truncated without a node to point at.
87 TooDeep,
88}
89
90/// One node of an authored `tasks` tree.
91#[derive(Debug, Clone)]
92pub struct AuthoredStep<'a> {
93 /// The coordinate the author typed, rooted at the workflow: `tasks[1]`,
94 /// `tasks[1].tasks[0]`. Append your own field segment to point at a
95 /// property — `format!("{}.id", step.path)`.
96 pub path: String,
97 /// The element itself, borrowed from the input.
98 pub node: &'a Value,
99 /// Whether this is a task, a group, or a group too deeply nested.
100 pub kind: StepKind,
101 /// Enclosing groups. `0` for a top-level element.
102 pub depth: usize,
103}
104
105/// Walk an authored `tasks` array, yielding every node with its path.
106///
107/// Traversal is document order, pre-order: a group is yielded before its
108/// members, so filtering to [`StepKind::Leaf`] reproduces the engine's
109/// flattened `Workflow::tasks` exactly, in order.
110///
111/// **This walker never fails.** Where `flatten` returns `Err` on the first
112/// malformed element, an empty group or an over-deep group, the walker yields
113/// those nodes so a validator can collect every violation in one pass. A
114/// `tasks` value that is not an array yields nothing at all — whether `tasks`
115/// is a non-empty array is a rule for the caller to report, not for this walk
116/// to fail on.
117///
118/// ```
119/// use dataflow_rs::engine::steps::{StepKind, walk_authored_steps};
120/// use serde_json::json;
121///
122/// let tasks = json!([
123/// {"id": "first", "function": {"name": "map", "input": {"mappings": []}}},
124/// {"id": "guard", "condition": true, "tasks": [
125/// {"id": "inner", "function": {"name": "map", "input": {"mappings": []}}}
126/// ]}
127/// ]);
128///
129/// let steps: Vec<_> = walk_authored_steps(&tasks).collect();
130/// let seen: Vec<(&str, StepKind)> =
131/// steps.iter().map(|s| (s.path.as_str(), s.kind)).collect();
132///
133/// assert_eq!(seen, vec![
134/// ("tasks[0]", StepKind::Leaf),
135/// ("tasks[1]", StepKind::Group),
136/// ("tasks[1].tasks[0]", StepKind::Leaf),
137/// ]);
138/// ```
139pub fn walk_authored_steps(tasks: &Value) -> AuthoredSteps<'_> {
140 AuthoredSteps {
141 stack: match tasks.as_array() {
142 Some(items) => vec![Frame {
143 items,
144 idx: 0,
145 prefix: "tasks".to_string(),
146 depth: 0,
147 }],
148 // Not an array: nothing to walk. The caller reports the shape.
149 None => Vec::new(),
150 },
151 }
152}
153
154/// One level of the walk: the array being iterated, how far through it we are,
155/// and the path prefix its elements hang off.
156struct Frame<'a> {
157 items: &'a [Value],
158 idx: usize,
159 prefix: String,
160 depth: usize,
161}
162
163/// Iterator returned by [`walk_authored_steps`].
164///
165/// Lazy, over an explicit stack rather than recursion, so nothing is allocated
166/// beyond each node's `path` and the stack itself — which is bounded by
167/// [`MAX_GROUP_DEPTH`].
168pub struct AuthoredSteps<'a> {
169 stack: Vec<Frame<'a>>,
170}
171
172impl<'a> Iterator for AuthoredSteps<'a> {
173 type Item = AuthoredStep<'a>;
174
175 fn next(&mut self) -> Option<Self::Item> {
176 loop {
177 let frame = self.stack.last_mut()?;
178 let Some(node) = frame.items.get(frame.idx) else {
179 // This level is exhausted; resume the one that opened it.
180 self.stack.pop();
181 continue;
182 };
183
184 let path = format!("{}[{}]", frame.prefix, frame.idx);
185 let depth = frame.depth;
186 frame.idx += 1;
187
188 if !is_group(node) {
189 return Some(AuthoredStep {
190 path,
191 node,
192 kind: StepKind::Leaf,
193 depth,
194 });
195 }
196
197 // A group at the cap is what the parser rejects. Report it and do
198 // not descend — the members are unreachable either way, and this
199 // gives the caller a node to point at instead of a silent gap.
200 if depth >= MAX_GROUP_DEPTH {
201 return Some(AuthoredStep {
202 path,
203 node,
204 kind: StepKind::TooDeep,
205 depth,
206 });
207 }
208
209 // Descend only into a well-formed `tasks` array. A `tasks` key
210 // holding anything else is still a group — a malformed one — and is
211 // reported as such with no members.
212 if let Some(children) = node.get("tasks").and_then(Value::as_array) {
213 self.stack.push(Frame {
214 items: children,
215 idx: 0,
216 prefix: format!("{path}.tasks"),
217 depth: depth + 1,
218 });
219 }
220
221 return Some(AuthoredStep {
222 path,
223 node,
224 kind: StepKind::Group,
225 depth,
226 });
227 }
228 }
229}
230
231/// The non-`tasks` half of a group element. `tasks` is carried too so the
232/// whole element deserializes in one pass; unknown keys are ignored, as
233/// everywhere else in the workflow schema — with exactly one exception.
234///
235/// **`halt_on` is that exception, deliberately.** It is a per-*task* outcome
236/// rule and a group has no outcome of its own, so the executor could not honour
237/// it. Ignoring it would mean an author writing `"halt_on": "failure"` on a
238/// group gets silence and ships a guard that never fires — the precise failure
239/// this flag exists to prevent, so it is refused in `walk` instead. The cost of
240/// the exception is that a host using `halt_on` as its own annotation on a group
241/// node now fails to parse; `Workflow::validate_authored` reports it as
242/// `INVALID_HALT_ON` with the authored path, so the audit is mechanical.
243///
244/// `continue_on_error` is captured too, but **not** refused. It is the same
245/// class of mistake — a control-flow key the executor cannot honour — and the
246/// difference is age. `halt_on` was new, with no installed base to break;
247/// `continue_on_error` is real on both a [`Task`] and a `Workflow`, which is
248/// what makes a group the one place it looks like it should work, and a host
249/// may already carry it on group nodes. Refusing it would fail `Engine::build`,
250/// which aborts every workflow in that build. So it is recorded on
251/// [`TaskGroup::continue_on_error`] and reported by `check_workflow` as
252/// `GROUP_CONTINUE_ON_ERROR` instead of being refused or silently dropped.
253#[derive(Deserialize)]
254struct GroupHeader {
255 id: String,
256 #[serde(default)]
257 name: Option<String>,
258 #[serde(default)]
259 description: Option<String>,
260 #[serde(default = "crate::engine::utils::default_condition")]
261 condition: Value,
262 #[serde(default)]
263 terminal: bool,
264 /// Captured only so it can be refused — see the type-level note above.
265 /// Typed as `Option<Value>` rather than `Option<HaltOn>` so that *any*
266 /// shape is caught: a group carrying `halt_on` is wrong whatever its value.
267 #[serde(default)]
268 halt_on: Option<Value>,
269 /// Captured only so `check_workflow` can report it — see the type-level
270 /// note above. `Option<Value>` rather than `Option<bool>` for `halt_on`'s
271 /// reason inverted: a typed field would make `"continue_on_error": "yes"`
272 /// on a group a *parse error*, refusing a definition that loads today.
273 /// Only a literal `true` states an intent the engine defeats.
274 #[serde(default)]
275 continue_on_error: Option<Value>,
276 tasks: Vec<Value>,
277}
278
279/// `deserialize_with` target for `Workflow::tasks`.
280///
281/// Fails fast, unlike [`walk_authored_steps`]: the engine will not run a
282/// workflow it cannot fully parse, so the first malformed element ends the
283/// attempt. A host that wants every problem at once walks the authored JSON
284/// instead.
285pub(crate) fn flatten<'de, D>(deserializer: D) -> Result<Vec<Task>, D::Error>
286where
287 D: Deserializer<'de>,
288{
289 let steps = Vec::<Value>::deserialize(deserializer)?;
290 let mut tasks = Vec::with_capacity(steps.len());
291 walk(&steps, 0, &mut tasks).map_err(D::Error::custom)?;
292 Ok(tasks)
293}
294
295/// Append `steps` to `out` in document order, recording group spans.
296fn walk(steps: &[Value], depth: usize, out: &mut Vec<Task>) -> Result<(), String> {
297 for step in steps {
298 if !is_group(step) {
299 let task: Task = serde_json::from_value(step.clone())
300 .map_err(|e| format!("invalid task in workflow tasks: {e}"))?;
301 out.push(task);
302 continue;
303 }
304
305 if depth >= MAX_GROUP_DEPTH {
306 return Err(format!(
307 "task groups nested deeper than {MAX_GROUP_DEPTH} levels"
308 ));
309 }
310
311 let header: GroupHeader = serde_json::from_value(step.clone())
312 .map_err(|e| format!("invalid task group in workflow tasks: {e}"))?;
313
314 if header.halt_on.is_some() {
315 return Err(format!(
316 "task group '{}' cannot carry halt_on — halt_on is a per-task \
317 outcome rule; put it on the task that can fail",
318 header.id
319 ));
320 }
321
322 let start = out.len();
323 walk(&header.tasks, depth + 1, out)?;
324 let end = out.len();
325 if end == start {
326 return Err(format!(
327 "task group '{}' contains no tasks — an empty group can only be a mistake",
328 header.id
329 ));
330 }
331
332 // Outermost first: an inner group nested at the same start index
333 // has already pushed its own entry, so this one goes in front of
334 // it. Bounded by `MAX_GROUP_DEPTH`, so the shift is trivial.
335 out[start].group_starts.insert(
336 0,
337 TaskGroup {
338 id: header.id,
339 name: header.name,
340 description: header.description,
341 condition: header.condition,
342 compiled_condition: None,
343 terminal: header.terminal,
344 continue_on_error: matches!(header.continue_on_error, Some(Value::Bool(true))),
345 end,
346 },
347 );
348 }
349 Ok(())
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355 use crate::engine::workflow::Workflow;
356 use serde_json::json;
357
358 fn leaf(id: &str) -> Value {
359 json!({"id": id, "name": id, "function": {"name": "map", "input": {"mappings": []}}})
360 }
361
362 /// `n` groups nested one inside the next, innermost holding one task.
363 /// `n == 1` is a single top-level group, which sits at depth 0.
364 fn nested_groups(n: usize) -> Value {
365 let mut node = leaf("innermost");
366 for level in (0..n).rev() {
367 node = json!({"id": format!("g{level}"), "condition": true, "tasks": [node]});
368 }
369 json!([node])
370 }
371
372 fn workflow_with(tasks: &Value) -> Result<Workflow, String> {
373 Workflow::from_json(
374 &json!({"id": "w", "name": "w", "priority": 0, "tasks": tasks}).to_string(),
375 )
376 .map_err(|e| e.to_string())
377 }
378
379 fn kinds(tasks: &Value) -> Vec<(String, StepKind, usize)> {
380 walk_authored_steps(tasks)
381 .map(|s| (s.path, s.kind, s.depth))
382 .collect()
383 }
384
385 /// Acceptance criterion: the walker's leaf set is the parser's flattened
386 /// `Workflow::tasks`, by id and by order. This is what pins the two
387 /// recursions to each other — sharing `is_group` alone would not catch a
388 /// divergence in the walk itself.
389 #[test]
390 fn walker_leaves_match_the_parsers_flattened_tasks() {
391 let fixtures = vec![
392 json!([leaf("a"), leaf("b")]),
393 json!([{"id": "g", "condition": true, "tasks": [leaf("a"), leaf("b")]}]),
394 json!([
395 leaf("before"),
396 {"id": "g1", "condition": true, "tasks": [
397 leaf("in1"),
398 {"id": "g2", "condition": true, "tasks": [leaf("deep")]},
399 leaf("in2"),
400 ]},
401 leaf("after"),
402 ]),
403 nested_groups(MAX_GROUP_DEPTH),
404 ];
405
406 for tasks in fixtures {
407 let parsed = workflow_with(&tasks).expect("fixture parses");
408 let from_parser: Vec<&str> = parsed.tasks.iter().map(|t| t.id.as_str()).collect();
409
410 let from_walker: Vec<&str> = walk_authored_steps(&tasks)
411 .filter(|s| s.kind == StepKind::Leaf)
412 .map(|s| s.node["id"].as_str().unwrap())
413 .collect();
414
415 assert_eq!(
416 from_walker, from_parser,
417 "walker leaves must equal the flattened tasks, in order, for {tasks}"
418 );
419 }
420 }
421
422 #[test]
423 fn paths_are_the_coordinates_the_author_typed() {
424 let tasks = json!([
425 leaf("first"),
426 {"id": "g", "condition": true, "tasks": [leaf("inner"), leaf("second")]},
427 ]);
428
429 let paths: Vec<String> = walk_authored_steps(&tasks).map(|s| s.path).collect();
430 assert_eq!(
431 paths,
432 vec![
433 "tasks[0]",
434 "tasks[1]",
435 "tasks[1].tasks[0]",
436 "tasks[1].tasks[1]"
437 ]
438 );
439 }
440
441 #[test]
442 fn groups_are_yielded_before_their_members() {
443 let tasks = json!([{"id": "g", "condition": true, "tasks": [leaf("inner")]}]);
444 assert_eq!(
445 kinds(&tasks),
446 vec![
447 ("tasks[0]".to_string(), StepKind::Group, 0),
448 ("tasks[0].tasks[0]".to_string(), StepKind::Leaf, 1),
449 ],
450 "pre-order, so filtering to Leaf reproduces parse order"
451 );
452 }
453
454 #[test]
455 fn max_group_depth_is_the_value_the_parser_enforces() {
456 // Exactly at the cap parses: MAX_GROUP_DEPTH groups occupy depths
457 // 0..MAX_GROUP_DEPTH.
458 let ok = nested_groups(MAX_GROUP_DEPTH);
459 assert!(
460 workflow_with(&ok).is_ok(),
461 "{MAX_GROUP_DEPTH} levels of nesting is accepted"
462 );
463 assert!(
464 walk_authored_steps(&ok).all(|s| s.kind != StepKind::TooDeep),
465 "and the walker agrees nothing is too deep"
466 );
467
468 // One more is rejected by the parser…
469 let too_deep = nested_groups(MAX_GROUP_DEPTH + 1);
470 let err = workflow_with(&too_deep).expect_err("one level past the cap is rejected");
471 assert!(
472 err.contains("nested deeper than"),
473 "parser reports the depth cap, got: {err}"
474 );
475
476 // …and reported — not silently dropped — by the walker, at the same node.
477 let flagged: Vec<_> = walk_authored_steps(&too_deep)
478 .filter(|s| s.kind == StepKind::TooDeep)
479 .collect();
480 assert_eq!(flagged.len(), 1, "exactly the one offending group");
481 assert_eq!(flagged[0].depth, MAX_GROUP_DEPTH);
482 assert_eq!(flagged[0].node["id"], json!(format!("g{MAX_GROUP_DEPTH}")));
483 }
484
485 #[test]
486 fn a_too_deep_group_is_not_descended_into() {
487 let tasks = nested_groups(MAX_GROUP_DEPTH + 1);
488 let deepest = walk_authored_steps(&tasks).map(|s| s.depth).max().unwrap();
489 assert_eq!(
490 deepest, MAX_GROUP_DEPTH,
491 "the walk stops at the offending group; its members are never yielded"
492 );
493 assert!(
494 !walk_authored_steps(&tasks).any(|s| s.node["id"] == json!("innermost")),
495 "the leaf below the cap is unreachable, and reported as such by its absent parent"
496 );
497 }
498
499 #[test]
500 fn a_leaf_is_never_too_deep() {
501 // A task sitting inside the maximum legal nesting is fine — the parser
502 // checks depth only when it opens a group.
503 let tasks = nested_groups(MAX_GROUP_DEPTH);
504 let innermost = walk_authored_steps(&tasks)
505 .find(|s| s.node["id"] == json!("innermost"))
506 .expect("the deepest leaf is yielded");
507 assert_eq!(innermost.kind, StepKind::Leaf);
508 assert_eq!(innermost.depth, MAX_GROUP_DEPTH);
509 }
510
511 #[test]
512 fn an_element_with_neither_tasks_nor_function_is_a_leaf() {
513 // Reported as a broken *task*, matching the parser's own diagnostic —
514 // not as a broken group.
515 let tasks = json!([{"id": "orphan"}]);
516 assert_eq!(
517 kinds(&tasks),
518 vec![("tasks[0]".to_string(), StepKind::Leaf, 0)]
519 );
520
521 let err = workflow_with(&tasks).expect_err("the parser rejects it");
522 assert!(
523 err.contains("invalid task in workflow tasks"),
524 "and calls it a task, got: {err}"
525 );
526 }
527
528 #[test]
529 fn a_tasks_key_that_is_not_an_array_is_still_a_group() {
530 // Presence of the key decides, not its type. This is exactly where the
531 // TypeScript `isTaskGroup` used to disagree with the engine.
532 let tasks = json!([{"id": "g", "tasks": "oops"}]);
533 assert!(is_group(&tasks[0]));
534 assert_eq!(
535 kinds(&tasks),
536 vec![("tasks[0]".to_string(), StepKind::Group, 0)],
537 "a malformed group with no members, not a task"
538 );
539
540 let err = workflow_with(&tasks).expect_err("the parser rejects it");
541 assert!(
542 err.contains("invalid task group"),
543 "and calls it a group, got: {err}"
544 );
545 }
546
547 #[test]
548 fn an_empty_group_is_yielded_not_an_error() {
549 // The walker is total where the parser fails fast, so a validator can
550 // collect this alongside every other violation in one pass.
551 let tasks = json!([{"id": "empty", "condition": true, "tasks": []}]);
552 assert_eq!(
553 kinds(&tasks),
554 vec![("tasks[0]".to_string(), StepKind::Group, 0)]
555 );
556
557 let err = workflow_with(&tasks).expect_err("the parser rejects an empty group");
558 assert!(err.contains("contains no tasks"), "got: {err}");
559 }
560
561 #[test]
562 fn a_non_array_input_yields_nothing() {
563 for input in [
564 Value::Null,
565 json!({}),
566 json!("tasks"),
567 json!(7),
568 json!({"tasks": []}),
569 ] {
570 assert_eq!(
571 walk_authored_steps(&input).count(),
572 0,
573 "not an array, so nothing to walk: {input}"
574 );
575 }
576 }
577
578 #[test]
579 fn an_empty_array_yields_nothing_and_leaves_no_frame_behind() {
580 assert_eq!(walk_authored_steps(&json!([])).count(), 0);
581 // Nested empties must not hang or double-yield the parent.
582 let tasks = json!([{"id": "g", "tasks": [{"id": "inner", "tasks": []}]}]);
583 assert_eq!(
584 kinds(&tasks),
585 vec![
586 ("tasks[0]".to_string(), StepKind::Group, 0),
587 ("tasks[0].tasks[0]".to_string(), StepKind::Group, 1),
588 ]
589 );
590 }
591}