1use crate::pb::executor::ExecuteStreamInput;
4use crate::pb::pilot::{CapabilityCall, Plan, RtdlNode};
5use std::collections::HashSet;
6
7const RTDL_IF: u32 = 3;
8const RTDL_REPEAT: u32 = 4;
9const RTDL_WHILE: u32 = 5;
10const MAX_ITERATIONS: u32 = 10_000;
11
12pub(crate) const EXECUTE_STREAM_START: u32 = 0;
14pub(crate) const EXECUTE_STREAM_NODE: u32 = 1;
15pub(crate) const EXECUTE_STREAM_CLOSE: u32 = 2;
16pub(crate) const EXECUTE_STREAM_END: u32 = 3;
17
18#[derive(Debug, Default)]
20pub(crate) struct PlanInput {
21 plan: Plan,
23 started: bool,
25 ended: bool,
27 parents: Vec<Option<usize>>,
29 order: Vec<usize>,
31 closed: Vec<bool>,
33 op_ids: HashSet<String>,
35 call_ids: HashSet<String>,
37}
38
39impl PlanInput {
40 pub(crate) fn plan(&self) -> &Plan {
41 &self.plan
42 }
43
44 pub(crate) fn order(&self) -> &[usize] {
45 &self.order
46 }
47
48 pub(crate) fn parent(&self, index: usize) -> Option<usize> {
49 self.parents[index]
50 }
51
52 pub(crate) fn is_closed(&self, index: usize) -> bool {
53 self.closed[index]
54 }
55
56 pub(crate) fn ended(&self) -> bool {
57 self.ended
58 }
59
60 pub(crate) fn seal(&mut self) {
62 self.ended = true;
63 self.closed.fill(true);
64 }
65
66 pub(crate) fn from_plan(plan: Plan) -> Result<Self, String> {
68 let count = plan.nodes.len();
69 if plan.plan_id.trim().is_empty() || count == 0 || count > 256 {
70 return Err("Plan requires a nonempty plan_id and 1 to 256 nodes".into());
71 }
72 let root = plan.root_index as usize;
73 if root >= count {
74 return Err("Plan.root_index is out of bounds".into());
75 }
76 let mut input = Self {
77 started: true,
78 ended: true,
79 parents: vec![None; count],
80 closed: vec![true; count],
81 ..Self::default()
82 };
83 for (index, node) in plan.nodes.iter().enumerate() {
84 if node.children.iter().any(|child| *child as usize >= count) {
85 return Err(format!("node {index} child index is out of bounds"));
86 }
87 input.validate_node(index, node)?;
88 }
89 let mut visited = vec![false; count];
90 let mut pending = vec![(root, None, 1)];
91 while let Some((index, parent, depth)) = pending.pop() {
92 if visited[index] {
93 return Err(format!("cycle or repeated child at node {index}"));
94 }
95 if depth > 32 {
96 return Err("RTDL nesting exceeds 32".into());
97 }
98 visited[index] = true;
99 input.parents[index] = parent;
100 input.order.push(index);
101 for child in plan.nodes[index].children.iter().rev() {
102 pending.push((*child as usize, Some(index), depth + 1));
103 }
104 }
105 if input.order.len() != count {
106 return Err("Plan contains nodes unreachable from root_index".into());
107 }
108 for (index, node) in plan.nodes.iter().enumerate() {
109 validate_completed_operator(index, node)?;
110 }
111 validate_parallel_bindings(&plan.nodes)?;
112 input.plan = plan;
113 Ok(input)
114 }
115
116 fn validate_node(&mut self, index: usize, node: &RtdlNode) -> Result<(), String> {
118 let op_id = node.op_id.trim();
119 if op_id.is_empty() || node.description.trim().is_empty() {
120 return Err(format!(
121 "node {index} requires nonempty op_id and description"
122 ));
123 }
124 if self.op_ids.contains(op_id) {
125 return Err(format!("node {index} has duplicate op_id '{op_id}'"));
126 }
127 if !node.bind.is_empty() && (node.node_kind != 2 || node.bind.trim() != node.bind) {
128 return Err(format!("node {index} has invalid bind"));
129 }
130 if matches!(node.node_kind, RTDL_IF | RTDL_WHILE) {
131 let condition: serde_json::Value = serde_json::from_str(&node.condition_json)
132 .map_err(|error| format!("node {index} has invalid condition: {error}"))?;
133 crate::expression::validate_expr(&condition)?;
134 } else if !node.condition_json.is_empty() {
135 return Err(format!("node {index} must not contain a condition"));
136 }
137 if node.node_kind != RTDL_REPEAT && node.repeat_count != 0
138 || node.node_kind != RTDL_WHILE && node.max_iterations != 0
139 {
140 return Err(format!("node {index} has unexpected loop limit"));
141 }
142 if node.repeat_count > MAX_ITERATIONS
143 || node.max_iterations > MAX_ITERATIONS
144 || node.node_kind == RTDL_WHILE && node.max_iterations == 0
145 {
146 return Err(format!("node {index} has invalid loop limit"));
147 }
148 match node.node_kind {
149 0 | 1 | RTDL_IF | RTDL_REPEAT | RTDL_WHILE if node.call.is_none() => {}
150 2 => {
151 if !node.children.is_empty() {
152 return Err(format!("do node {index} must not have children"));
153 }
154 let call = node
155 .call
156 .as_ref()
157 .ok_or_else(|| format!("do node {index} must contain a call"))?;
158 validate_call(index, call)?;
159 let args: serde_json::Value = serde_json::from_str(&call.args_json)
160 .map_err(|error| format!("do node {index} has invalid args_json: {error}"))?;
161 if !args.is_object() || self.call_ids.contains(&call.call_id) {
162 return Err(format!(
163 "do node {index} requires object args and unique call_id"
164 ));
165 }
166 crate::expression::validate_expr(&args)?;
167 }
168 _ => {
169 return Err(format!(
170 "node {index} has invalid node kind or operator call payload"
171 ));
172 }
173 }
174 if let Some(call) = &node.call {
175 self.call_ids.insert(call.call_id.clone());
176 }
177 self.op_ids.insert(op_id.to_owned());
178 Ok(())
179 }
180
181 pub(crate) fn accept(&mut self, msg: ExecuteStreamInput) -> Result<(), String> {
183 if self.ended {
184 return Err("message after END".into());
185 }
186 if !self.started {
187 if msg.message_kind != EXECUTE_STREAM_START || msg.plan_id.trim().is_empty() {
188 return Err("stream must begin with START and a nonempty plan_id".into());
189 }
190 self.plan.plan_id = msg.plan_id;
191 self.plan.session_id = msg.session_id;
192 self.plan.round = msg.round;
193 self.started = true;
194 return Ok(());
195 }
196 match msg.message_kind {
197 EXECUTE_STREAM_NODE => self.node(msg),
198 EXECUTE_STREAM_CLOSE => {
199 let index = msg.node_index as usize;
200 if index >= self.closed.len() || self.closed[index] {
201 return Err("CLOSE requires an open operator".into());
202 }
203 for child in 0..self.closed.len() {
204 if !self.closed[child] {
205 let mut parent = self.parents[child];
206 while let Some(p) = parent {
207 if p == index {
208 return Err("CLOSE must be innermost first".into());
209 }
210 parent = self.parents[p];
211 }
212 }
213 }
214 validate_completed_operator(index, &self.plan.nodes[index])?;
215 if self.plan.nodes[index].node_kind == 1 {
216 validate_parallel_bindings(&self.plan.nodes)?;
217 }
218 self.closed[index] = true;
219 Ok(())
220 }
221 EXECUTE_STREAM_END => {
222 if self.plan.nodes.is_empty() || self.closed.iter().any(|closed| !closed) {
223 return Err("END requires a root and all operators closed".into());
224 }
225 self.ended = true;
226 Ok(())
227 }
228 _ => Err("unexpected message kind or repeated START".into()),
229 }
230 }
231
232 pub(crate) fn discard_last_node(&mut self) {
234 let node = self.plan.nodes.pop().expect("arrived node");
235 self.op_ids.remove(node.op_id.trim());
236 if let Some(call) = node.call {
237 self.call_ids.remove(&call.call_id);
238 }
239 self.closed.pop();
240 self.order.pop();
241 if let Some(parent) = self.parents.pop().flatten() {
242 self.plan.nodes[parent].children.pop();
243 }
244 }
245
246 fn node(&mut self, msg: ExecuteStreamInput) -> Result<(), String> {
248 let index = self.plan.nodes.len();
249 if msg.node_index as usize != index || index >= 256 {
250 return Err("NODE index must be consecutive and fewer than 256 nodes".into());
251 }
252 let parent = if index == 0 {
253 if msg.has_parent {
254 return Err("root must not have a parent".into());
255 }
256 None
257 } else {
258 let p = msg.parent_index as usize;
259 if !msg.has_parent || p >= index || self.closed[p] {
260 return Err("NODE requires an arrived open operator parent".into());
261 }
262 Some(p)
263 };
264 let mut depth = 1;
265 let mut ancestor = parent;
266 while let Some(p) = ancestor {
267 depth += 1;
268 ancestor = self.parents[p];
269 }
270 if depth > 32 {
271 return Err("RTDL nesting exceeds 32".into());
272 }
273 let node = msg.node.ok_or("NODE requires a node")?;
274 if !node.children.is_empty() {
275 return Err("NODE requires empty children".into());
276 }
277 self.validate_node(index, &node)?;
278 self.closed.push(node.node_kind == 2);
279 self.parents.push(parent);
280 self.order.push(index);
281 if let Some(p) = parent {
282 self.plan.nodes[p].children.push(index as u32);
283 }
284 self.plan.nodes.push(node);
285 Ok(())
286 }
287}
288
289fn validate_completed_operator(index: usize, node: &RtdlNode) -> Result<(), String> {
290 match node.node_kind {
291 RTDL_IF if !(1..=2).contains(&node.children.len()) => {
292 Err(format!("if node {index} requires one or two children"))
293 }
294 RTDL_REPEAT | RTDL_WHILE if node.children.len() != 1 => {
295 Err(format!("loop node {index} requires one body"))
296 }
297 _ => Ok(()),
298 }
299}
300
301fn expression_reads(value: &serde_json::Value, reads: &mut HashSet<String>) {
302 match value {
303 serde_json::Value::Object(fields) => {
304 if crate::expression::is_reference(fields)
305 && let Some(name) = fields.get("var").and_then(serde_json::Value::as_str)
306 {
307 reads.insert(name.into());
308 }
309 for value in fields.values() {
310 expression_reads(value, reads);
311 }
312 }
313 serde_json::Value::Array(values) => {
314 for value in values {
315 expression_reads(value, reads);
316 }
317 }
318 _ => {}
319 }
320}
321
322fn validate_parallel_bindings(nodes: &[RtdlNode]) -> Result<(), String> {
323 fn dependencies(
324 index: usize,
325 nodes: &[RtdlNode],
326 ) -> Result<(HashSet<String>, HashSet<String>), String> {
327 let node = &nodes[index];
328 let mut reads = HashSet::new();
329 let mut writes = HashSet::new();
330 if !node.bind.is_empty() {
331 writes.insert(node.bind.clone());
332 }
333 if !node.condition_json.is_empty() {
334 expression_reads(
335 &serde_json::from_str(&node.condition_json).expect("validated condition"),
336 &mut reads,
337 );
338 }
339 if let Some(call) = &node.call {
340 expression_reads(
341 &serde_json::from_str(&call.args_json).expect("validated args"),
342 &mut reads,
343 );
344 }
345 let mut branches: Vec<(HashSet<String>, HashSet<String>)> = Vec::new();
346 for &child in &node.children {
347 let branch = dependencies(child as usize, nodes)?;
348 if node.node_kind == 1 {
349 for (other_reads, other_writes) in &branches {
350 if !branch.1.is_disjoint(other_writes)
351 || !branch.0.is_disjoint(other_writes)
352 || !branch.1.is_disjoint(other_reads)
353 {
354 return Err(format!(
355 "parallel node {index} has conflicting variable dependencies"
356 ));
357 }
358 }
359 }
360 reads.extend(branch.0.iter().cloned());
361 writes.extend(branch.1.iter().cloned());
362 branches.push(branch);
363 }
364 Ok((reads, writes))
365 }
366 for (index, node) in nodes.iter().enumerate() {
367 if node.node_kind == 1 {
368 dependencies(index, nodes)?;
369 }
370 }
371 Ok(())
372}
373
374fn validate_call(node_index: usize, call: &CapabilityCall) -> Result<(), String> {
376 if call.call_id.is_empty() {
377 return Err(format!("do node {node_index} call_id must not be empty"));
378 }
379 if call.provider_id.is_empty() {
380 return Err(format!(
381 "do node {node_index} provider_id must not be empty"
382 ));
383 }
384 if call.contract_id.is_empty() {
385 return Err(format!(
386 "do node {node_index} contract_id must not be empty"
387 ));
388 }
389 Ok(())
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use crate::pb::pilot::{CapabilityCall, RtdlNode};
396
397 fn message(kind: u32, index: u32, parent: Option<u32>, node_kind: u32) -> ExecuteStreamInput {
399 ExecuteStreamInput {
400 message_kind: kind,
401 plan_id: "p".into(),
402 node_index: index,
403 has_parent: parent.is_some(),
404 parent_index: parent.unwrap_or_default(),
405 node: if kind == EXECUTE_STREAM_NODE {
406 Some(RtdlNode {
407 node_kind,
408 op_id: index.to_string(),
409 description: "step".into(),
410 call: if node_kind == 2 {
411 Some(CapabilityCall {
412 call_id: index.to_string(),
413 provider_id: "executor".into(),
414 contract_id: "test/run".into(),
415 args_json: "{}".into(),
416 })
417 } else {
418 None
419 },
420 ..Default::default()
421 })
422 } else {
423 None
424 },
425 ..Default::default()
426 }
427 }
428
429 #[test]
431 fn valid_nested_protocol_and_reconstructed_children() {
432 let mut input = PlanInput::default();
433 for msg in [
434 message(EXECUTE_STREAM_START, 0, None, 0),
435 message(EXECUTE_STREAM_NODE, 0, None, 0),
436 message(EXECUTE_STREAM_NODE, 1, Some(0), 1),
437 message(EXECUTE_STREAM_NODE, 2, Some(1), 2),
438 message(EXECUTE_STREAM_CLOSE, 1, None, 0),
439 message(EXECUTE_STREAM_NODE, 3, Some(0), 2),
440 message(EXECUTE_STREAM_CLOSE, 0, None, 0),
441 message(EXECUTE_STREAM_END, 0, None, 0),
442 ] {
443 input.accept(msg).unwrap();
444 }
445 assert_eq!(input.plan.nodes[0].children, [1, 3]);
446 assert_eq!(input.plan.nodes[1].children, [2]);
447 assert!(input.ended);
448 assert!(
449 input
450 .accept(message(EXECUTE_STREAM_END, 0, None, 0))
451 .is_err()
452 );
453 }
454
455 #[test]
457 fn invalid_protocol_transitions() {
458 let mut input = PlanInput::default();
459 assert!(
460 input
461 .accept(message(EXECUTE_STREAM_NODE, 0, None, 0))
462 .is_err()
463 );
464 input
465 .accept(message(EXECUTE_STREAM_START, 0, None, 0))
466 .unwrap();
467 assert!(
468 input
469 .accept(message(EXECUTE_STREAM_START, 0, None, 0))
470 .is_err()
471 );
472 assert!(
473 input
474 .accept(message(EXECUTE_STREAM_END, 0, None, 0))
475 .is_err()
476 );
477 assert!(
478 input
479 .accept(message(EXECUTE_STREAM_NODE, 1, None, 0))
480 .is_err()
481 );
482 assert!(
483 input
484 .accept(message(EXECUTE_STREAM_NODE, 0, Some(0), 0))
485 .is_err()
486 );
487 input
488 .accept(message(EXECUTE_STREAM_NODE, 0, None, 0))
489 .unwrap();
490 assert!(
491 input
492 .accept(message(EXECUTE_STREAM_NODE, 1, None, 0))
493 .is_err()
494 );
495 assert!(
496 input
497 .accept(message(EXECUTE_STREAM_NODE, 1, Some(2), 0))
498 .is_err()
499 );
500 input
501 .accept(message(EXECUTE_STREAM_NODE, 1, Some(0), 0))
502 .unwrap();
503 assert!(
504 input
505 .accept(message(EXECUTE_STREAM_CLOSE, 0, None, 0))
506 .is_err()
507 );
508 input
509 .accept(message(EXECUTE_STREAM_NODE, 2, Some(1), 2))
510 .unwrap();
511 assert!(
512 input
513 .accept(message(EXECUTE_STREAM_CLOSE, 2, None, 0))
514 .is_err()
515 );
516 assert!(
517 input
518 .accept(message(EXECUTE_STREAM_NODE, 3, Some(2), 2))
519 .is_err()
520 );
521 input
522 .accept(message(EXECUTE_STREAM_CLOSE, 1, None, 0))
523 .unwrap();
524 assert!(
525 input
526 .accept(message(EXECUTE_STREAM_CLOSE, 1, None, 0))
527 .is_err()
528 );
529 assert!(
530 input
531 .accept(message(EXECUTE_STREAM_NODE, 3, Some(1), 2))
532 .is_err()
533 );
534 assert!(
535 input
536 .accept(message(EXECUTE_STREAM_END, 0, None, 0))
537 .is_err()
538 );
539 input
540 .accept(message(EXECUTE_STREAM_CLOSE, 0, None, 0))
541 .unwrap();
542 input
543 .accept(message(EXECUTE_STREAM_END, 0, None, 0))
544 .unwrap();
545 }
546
547 #[test]
549 fn invalid_node_payloads() {
550 let mut input = PlanInput::default();
551 input
552 .accept(message(EXECUTE_STREAM_START, 0, None, 0))
553 .unwrap();
554 for mutate in [0, 1, 2, 3, 4] {
555 let mut msg = message(EXECUTE_STREAM_NODE, 0, None, 2);
556 let node = msg.node.as_mut().unwrap();
557 match mutate {
558 0 => node.children.push(1),
559 1 => node.call = None,
560 2 => node.call.as_mut().unwrap().args_json = "[]".into(),
561 3 => node.op_id.clear(),
562 _ => node.node_kind = 9,
563 }
564 assert!(
565 PlanInput::from_plan(Plan {
566 plan_id: "p".into(),
567 nodes: vec![node.clone()],
568 ..Default::default()
569 })
570 .is_err()
571 );
572 assert!(input.accept(msg).is_err());
573 assert!(input.plan.nodes.is_empty());
574 }
575 }
576
577 #[test]
579 fn complete_plan_preserves_arena_indices() {
580 let leaf = message(EXECUTE_STREAM_NODE, 0, None, 2).node.unwrap();
581 let mut root = message(EXECUTE_STREAM_NODE, 1, None, 0).node.unwrap();
582 root.children = vec![2, 0];
583 let operator = message(EXECUTE_STREAM_NODE, 2, None, 1).node.unwrap();
584 let input = PlanInput::from_plan(Plan {
585 plan_id: "p".into(),
586 root_index: 1,
587 nodes: vec![leaf, root, operator],
588 ..Default::default()
589 })
590 .unwrap();
591 assert_eq!(input.order, [1, 2, 0]);
592 assert_eq!(input.parents, [Some(1), None, Some(1)]);
593 assert_eq!(input.plan.root_index, 1);
594 assert_eq!(input.plan.nodes[1].children, [2, 0]);
595 }
596
597 #[test]
599 fn complete_plan_requires_one_tree() {
600 for children in [vec![1, 1], vec![]] {
601 let mut root = message(EXECUTE_STREAM_NODE, 0, None, 0).node.unwrap();
602 root.children = children;
603 let leaf = message(EXECUTE_STREAM_NODE, 1, None, 2).node.unwrap();
604 assert!(
605 PlanInput::from_plan(Plan {
606 plan_id: "p".into(),
607 nodes: vec![root, leaf],
608 ..Default::default()
609 })
610 .is_err()
611 );
612 }
613 }
614}
615
616#[cfg(test)]
617mod complete_plan_tests {
618 use super::*;
619 const RTDL_SEQUENCE: u32 = 0;
620 const RTDL_PARALLEL: u32 = 1;
621 const RTDL_DO: u32 = 2;
622
623 fn call(id: &str) -> CapabilityCall {
625 CapabilityCall {
626 call_id: id.to_string(),
627 provider_id: "provider".to_string(),
628 contract_id: "robonix/test/cap".to_string(),
629 args_json: "{}".to_string(),
630 }
631 }
632
633 fn node(kind: u32, children: Vec<u32>, call: Option<CapabilityCall>) -> RtdlNode {
634 node_with_identity("op", "test node", kind, children, call)
635 }
636
637 fn node_with_identity(
639 op_id: &str,
640 description: &str,
641 kind: u32,
642 children: Vec<u32>,
643 call: Option<CapabilityCall>,
644 ) -> RtdlNode {
645 RtdlNode {
646 node_kind: kind,
647 children,
648 call,
649 op_id: op_id.to_string(),
650 description: description.to_string(),
651 ..Default::default()
652 }
653 }
654
655 fn plan(nodes: Vec<RtdlNode>, root_index: u32) -> Plan {
657 Plan {
658 plan_id: "p".to_string(),
659 session_id: "s".to_string(),
660 round: 0,
661 nodes,
662 root_index,
663 }
664 }
665
666 #[test]
668 fn validates_sequence_and_parallel_nodes() {
669 let p = plan(
670 vec![
671 node_with_identity("op_1", "run sequence", RTDL_SEQUENCE, vec![1, 2], None),
672 node_with_identity("op_2", "call first cap", RTDL_DO, vec![], Some(call("p:0"))),
673 node_with_identity("op_3", "run parallel", RTDL_PARALLEL, vec![3, 4], None),
674 node_with_identity(
675 "op_4",
676 "call second cap",
677 RTDL_DO,
678 vec![],
679 Some(call("p:1")),
680 ),
681 node_with_identity("op_5", "call third cap", RTDL_DO, vec![], Some(call("p:2"))),
682 ],
683 0,
684 );
685 PlanInput::from_plan(p).unwrap();
686 }
687
688 #[test]
690 fn rejects_empty_op_id() {
691 let p = plan(
692 vec![node_with_identity("", "root", RTDL_SEQUENCE, vec![], None)],
693 0,
694 );
695 assert!(PlanInput::from_plan(p).unwrap_err().contains("op_id"));
696 }
697
698 #[test]
700 fn rejects_empty_description() {
701 let p = plan(
702 vec![node_with_identity("op_1", "", RTDL_SEQUENCE, vec![], None)],
703 0,
704 );
705 assert!(PlanInput::from_plan(p).unwrap_err().contains("description"));
706 }
707
708 #[test]
710 fn rejects_duplicate_op_id() {
711 let p = plan(
712 vec![
713 node_with_identity("op_1", "root", RTDL_SEQUENCE, vec![1], None),
714 node_with_identity("op_1", "child", RTDL_DO, vec![], Some(call("p:0"))),
715 ],
716 0,
717 );
718 assert!(
719 PlanInput::from_plan(p)
720 .unwrap_err()
721 .contains("duplicate op_id")
722 );
723 }
724
725 #[test]
726 fn rejects_invalid_root() {
727 let p = plan(vec![node(RTDL_SEQUENCE, vec![], None)], 3);
728 assert!(PlanInput::from_plan(p).unwrap_err().contains("root_index"));
729 }
730
731 #[test]
733 fn rejects_out_of_bounds_child() {
734 let p = plan(vec![node(RTDL_SEQUENCE, vec![9], None)], 0);
735 assert!(
736 PlanInput::from_plan(p)
737 .unwrap_err()
738 .contains("out of bounds")
739 );
740 }
741
742 #[test]
744 fn rejects_cycle() {
745 let p = plan(
746 vec![
747 node_with_identity("op_1", "root", RTDL_SEQUENCE, vec![1], None),
748 node_with_identity("op_2", "child", RTDL_PARALLEL, vec![0], None),
749 ],
750 0,
751 );
752 assert!(PlanInput::from_plan(p).unwrap_err().contains("cycle"));
753 }
754
755 #[test]
757 fn rejects_do_without_call() {
758 let p = plan(vec![node(RTDL_DO, vec![], None)], 0);
759 assert!(
760 PlanInput::from_plan(p)
761 .unwrap_err()
762 .contains("must contain a call")
763 );
764 }
765}