1use crate::active_plans::PlanRuntime;
4use crate::capability_execution;
5use crate::pb::executor::{ExecuteStreamInput, RtdlEvent};
6use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum as State;
7use crate::plan_input::{EXECUTE_STREAM_NODE, PlanInput};
8use crate::rtdl_events;
9use crate::verification::VerificationPolicy;
10use robonix_atlas::client::AtlasClient;
11use robonix_scribe::info;
12use std::sync::Arc;
13use tokio::sync::mpsc;
14use tokio::task::JoinSet;
15use tokio_stream::wrappers::ReceiverStream;
16use tokio_stream::{Stream, StreamExt};
17use tonic::Status;
18
19#[derive(Default)]
21struct Execution {
22 started: bool,
24 immediate: Option<bool>,
26 final_failed: Option<bool>,
28 verifying: bool,
30 canceled: bool,
32 active_child: Option<usize>,
34 iterations: u32,
36}
37
38enum Completion {
39 Call(usize, capability_execution::NodeExecution),
40 Verified(usize, bool),
41}
42
43pub(crate) struct PlanScheduler {
45 input: PlanInput,
47 execution: Vec<Execution>,
49 atlas: AtlasClient,
51 provider_id: String,
53 runtime: PlanRuntime,
55 verification: Arc<VerificationPolicy>,
57 tx: mpsc::Sender<Result<RtdlEvent, Status>>,
59 tasks: JoinSet<Completion>,
61 cancelled: bool,
63 error: Option<Status>,
65}
66
67impl PlanScheduler {
68 pub(crate) async fn start(
70 atlas: AtlasClient,
71 provider_id: String,
72 runtime: PlanRuntime,
73 verification: Arc<VerificationPolicy>,
74 input: PlanInput,
75 stream: impl Stream<Item = Result<ExecuteStreamInput, Status>> + Unpin + Send + 'static,
76 ) -> Result<ReceiverStream<Result<RtdlEvent, Status>>, Status> {
77 runtime
78 .register_plan(&input.plan().plan_id)
79 .await
80 .map_err(Status::invalid_argument)?;
81 let (tx, rx) = mpsc::channel(1024);
82 let scheduler = Self {
83 execution: (0..input.plan().nodes.len())
84 .map(|_| Execution::default())
85 .collect(),
86 input,
87 atlas,
88 provider_id,
89 runtime,
90 verification,
91 tx,
92 tasks: JoinSet::new(),
93 cancelled: false,
94 error: None,
95 };
96 tokio::spawn(scheduler.run(stream));
97 Ok(ReceiverStream::new(rx))
98 }
99
100 async fn cancel(&mut self) {
102 if self.cancelled {
103 return;
104 }
105 self.cancelled = true;
106 self.input.seal();
107 self.runtime
108 .cancel_plan_control(&self.input.plan().plan_id, 0)
109 .await;
110 }
111
112 fn permitted(&self, index: usize) -> (bool, bool) {
114 let Some(parent) = self.input.parent(index) else {
115 return (true, false);
116 };
117 let p = &self.execution[parent];
118 let parent_node = &self.input.plan().nodes[parent];
119 if !p.started || matches!(parent_node.node_kind, 3..=5) && p.active_child != Some(index) {
120 return (false, false);
121 }
122 if p.canceled || self.cancelled {
123 return (false, true);
124 }
125 if parent_node.node_kind != 0 {
126 return (true, false);
127 }
128 for sibling in &parent_node.children {
129 if *sibling as usize == index {
130 break;
131 }
132 match self.execution[*sibling as usize].immediate {
133 Some(true) => return (false, true),
134 None => return (false, false),
135 Some(false) => {}
136 }
137 }
138 (true, false)
139 }
140
141 async fn advance_control(&mut self, index: usize) -> bool {
143 let active_child = self.execution[index].active_child;
144 let child_failed = match active_child {
145 Some(child) => match self.execution[child].final_failed {
146 Some(failed) => failed,
147 None => return false,
148 },
149 None => false,
150 };
151 let node = &self.input.plan().nodes[index];
152 let ctx = rtdl_events::node_event_context(self.input.plan(), index);
153 let iterations = self.execution[index].iterations;
154 let (kind, limit) = match node.node_kind {
155 3 => ("if", 1),
156 4 => ("repeat", node.repeat_count),
157 _ => ("while", node.max_iterations),
158 };
159 if let Some(child) = active_child {
160 info!(
161 "[executor/rtdl] plan_id={} node={} op_id={} {kind} iteration={iterations} child={child} complete failed={child_failed}",
162 ctx.plan_id, index, ctx.op_id
163 );
164 } else {
165 info!(
166 "[executor/rtdl] plan_id={} node={} op_id={} {kind} start limit={limit}",
167 ctx.plan_id, index, ctx.op_id
168 );
169 }
170
171 let selection = if self.cancelled || child_failed || node.node_kind == 3 && iterations > 0 {
172 Ok(None)
173 } else if node.node_kind == 4 {
174 Ok((iterations < limit).then_some(0))
175 } else {
176 let condition =
177 serde_json::from_str(&node.condition_json).expect("validated condition");
178 let vars = self.runtime.context(&ctx.plan_id).await.snapshot().await;
179 crate::expression::eval_condi(&condition, &vars)
180 .map_err(|error| format!("condition evaluation: {error}"))
181 .and_then(|value| {
182 let selected = if value {
183 Some(0)
184 } else if node.node_kind == 3 && node.children.len() == 2 {
185 Some(1)
186 } else {
187 None
188 };
189 info!(
190 "[executor/rtdl] plan_id={} node={} op_id={} {kind} condition={value} completed_iterations={iterations} selected={selected:?}",
191 ctx.plan_id, index, ctx.op_id
192 );
193 if value && iterations >= limit {
194 Err("while condition remains true at max_iterations".into())
195 } else {
196 Ok(selected)
197 }
198 })
199 };
200
201 match selection {
202 Ok(Some(selected)) => {
203 let child = node.children[selected] as usize;
204 if active_child.is_some() {
205 let mut pending = vec![child];
207 while let Some(descendant) = pending.pop() {
208 self.execution[descendant] = Execution::default();
209 pending.extend(
210 self.input.plan().nodes[descendant]
211 .children
212 .iter()
213 .map(|&child| child as usize),
214 );
215 }
216 }
217 self.execution[index].active_child = Some(child);
218 self.execution[index].iterations += 1;
219 info!(
220 "[executor/rtdl] plan_id={} node={} op_id={} {kind} iteration={} limit={limit} child={child} start",
221 ctx.plan_id,
222 index,
223 ctx.op_id,
224 iterations + 1
225 );
226 }
227 Ok(None) => {
228 self.execution[index].immediate = Some(child_failed || self.cancelled);
229 self.finish_operator(index, &ctx, child_failed).await;
230 }
231 Err(detail) => {
232 self.execution[index].immediate = Some(true);
233 self.execution[index].final_failed = Some(true);
234 rtdl_events::send_node_failure(&self.tx, &ctx, detail, &self.runtime).await;
235 }
236 }
237 true
238 }
239
240 async fn finish_operator(
241 &mut self,
242 index: usize,
243 ctx: &rtdl_events::NodeEventContext,
244 failed: bool,
245 ) {
246 let canceled = self.cancelled || self.execution[index].canceled;
247 self.execution[index].final_failed = Some(failed || canceled);
248 rtdl_events::send_operator_final(&self.tx, ctx, failed, canceled, &self.runtime).await;
249 if self.runtime.is_cancelled(&ctx.plan_id).await {
250 self.cancel().await;
251 }
252 }
253
254 async fn schedule(&mut self) -> bool {
256 let mut progressed = false;
257 for position in 0..self.input.order().len() {
258 let index = self.input.order()[position];
259 if self.execution[index].started {
260 continue;
261 }
262 if matches!(self.input.plan().nodes[index].node_kind, 3..=5)
263 && !self.input.is_closed(index)
264 {
265 continue;
266 }
267 let (ready, blocked) = self.permitted(index);
268 if !ready && !blocked {
269 continue;
270 }
271 progressed = true;
272 let ctx = rtdl_events::node_event_context(self.input.plan(), index);
273 if self.cancelled || blocked {
274 let leaf = ctx.node_kind == 2;
275 let controlled = matches!(ctx.node_kind, 3..=5);
276 self.execution[index] = Execution {
277 started: true,
278 immediate: (leaf || controlled).then_some(true),
279 final_failed: (leaf || controlled).then_some(true),
280 canceled: true,
281 ..Execution::default()
282 };
283 if !leaf && !controlled {
284 continue;
285 }
286 self.runtime
287 .record_op_state(&ctx.plan_id, &ctx.op_id, State::Canceled as u32)
288 .await;
289 let _ = self
290 .tx
291 .send(Ok(rtdl_events::node_state(
292 &ctx,
293 State::Canceled as u32,
294 "canceled before execution".into(),
295 None,
296 )))
297 .await;
298 continue;
299 }
300 self.execution[index].started = true;
301 let node = &self.input.plan().nodes[index];
302 if let Some(call) = node.call.clone() {
303 let bind = node.bind.clone();
304 let atlas = self.atlas.clone();
305 let provider_id = self.provider_id.clone();
306 let runtime = self.runtime.clone();
307 let verification = self.verification.clone();
308 let tx = self.tx.clone();
309 self.tasks.spawn(async move {
310 if runtime.is_cancelled(&ctx.plan_id).await {
312 runtime
313 .record_op_state(&ctx.plan_id, &ctx.op_id, State::Canceled as u32)
314 .await;
315 let _ = tx
316 .send(Ok(rtdl_events::node_state(
317 &ctx,
318 State::Canceled as u32,
319 "canceled before execution".into(),
320 None,
321 )))
322 .await;
323 return Completion::Call(
324 index,
325 capability_execution::NodeExecution {
326 failed: true,
327 verifier: None,
328 },
329 );
330 }
331 let mut call = call;
332 let args: serde_json::Value =
333 serde_json::from_str(&call.args_json).expect("validated args");
334 let vars = runtime.context(&ctx.plan_id).await.snapshot().await;
335 match crate::expression::eval_value(&args, &vars) {
336 Ok(value) => call.args_json = value.to_string(),
337 Err(error) => {
338 rtdl_events::send_node_failure(
339 &tx,
340 &ctx,
341 format!("argument evaluation: {error}"),
342 &runtime,
343 )
344 .await;
345 return Completion::Call(
346 index,
347 capability_execution::NodeExecution {
348 failed: true,
349 verifier: None,
350 },
351 );
352 }
353 }
354 let result = capability_execution::execute_call(
355 &call,
356 &bind,
357 ctx,
358 tx,
359 atlas,
360 provider_id,
361 runtime,
362 verification,
363 )
364 .await;
365 Completion::Call(index, result)
366 });
367 } else {
368 rtdl_events::send_operator_state(
369 &self.tx,
370 &ctx,
371 State::Running as u32,
372 "running",
373 &self.runtime,
374 )
375 .await;
376 }
377 }
378 for position in (0..self.input.order().len()).rev() {
379 let index = self.input.order()[position];
380 let node = &self.input.plan().nodes[index];
381 if node.node_kind == 2
382 || !self.execution[index].started
383 || self.execution[index].final_failed.is_some()
384 || !self.input.is_closed(index)
385 {
386 continue;
387 }
388 if matches!(node.node_kind, 3..=5) {
389 progressed |= self.advance_control(index).await;
390 continue;
391 }
392 let children = &node.children;
393 if children
394 .iter()
395 .all(|c| self.execution[*c as usize].immediate.is_some())
396 {
397 let failed = self.cancelled
398 || self.execution[index].canceled
399 || children
400 .iter()
401 .any(|c| self.execution[*c as usize].immediate == Some(true));
402 progressed |= self.execution[index].immediate != Some(failed);
403 self.execution[index].immediate = Some(failed);
404 }
405 let ctx = rtdl_events::node_event_context(self.input.plan(), index);
406 if children
407 .iter()
408 .all(|c| self.execution[*c as usize].final_failed.is_some())
409 {
410 let failed = children
411 .iter()
412 .any(|c| self.execution[*c as usize].final_failed == Some(true));
413 progressed = true;
414 self.finish_operator(index, &ctx, failed).await;
415 } else if self.execution[index].immediate.is_some() && !self.execution[index].verifying
416 {
417 self.execution[index].verifying = true;
418 progressed = true;
419 rtdl_events::send_operator_state(
420 &self.tx,
421 &ctx,
422 State::Verifying as u32,
423 "waiting for descendant verification",
424 &self.runtime,
425 )
426 .await;
427 }
428 }
429 progressed
430 }
431
432 async fn run(
434 mut self,
435 mut stream: impl Stream<Item = Result<ExecuteStreamInput, Status>> + Unpin,
436 ) {
437 let started_at = std::time::Instant::now();
438 info!(
439 "[executor/rtdl] plan_id={} session_id={} round={} plan start",
440 self.input.plan().plan_id,
441 self.input.plan().session_id,
442 self.input.plan().round
443 );
444 self.runtime.record_plan_ops(self.input.plan()).await;
445 let _ = self
446 .tx
447 .send(Ok(rtdl_events::plan_started(
448 self.input.plan().plan_id.clone(),
449 )))
450 .await;
451 let mut input_eof = false;
452 let mut tick = tokio::time::interval(std::time::Duration::from_millis(10));
454 loop {
455 if self.runtime.is_cancelled(&self.input.plan().plan_id).await {
456 self.cancel().await;
457 }
458 let progressed = self.schedule().await;
459 if !self.cancelled && self.runtime.is_cancelled(&self.input.plan().plan_id).await {
460 self.cancel().await;
461 continue;
462 }
463 if self.input.ended()
464 && self.tasks.is_empty()
465 && self
466 .execution
467 .get(self.input.plan().root_index as usize)
468 .is_none_or(|root| root.final_failed.is_some())
469 {
470 break;
471 }
472 if progressed {
473 continue;
474 }
475 tokio::select! {
476 biased;
477 _ = self.tx.closed(), if !self.cancelled => { self.cancel().await; }
478 result = self.tasks.join_next(), if !self.tasks.is_empty() => {
479 match result {
480 Some(Ok(Completion::Call(index, outcome))) => {
481 self.execution[index].immediate = Some(outcome.failed);
482 if let Some(verifier) = outcome.verifier {
483 self.tasks.spawn(async move { Completion::Verified(index, capability_execution::wait_for_verifier(verifier).await) });
484 } else {
485 self.execution[index].final_failed = Some(outcome.failed);
486 }
487 }
488 Some(Ok(Completion::Verified(index, failed))) => { self.execution[index].final_failed = Some(failed || self.execution[index].immediate == Some(true)); }
489 Some(Err(error)) => {
490 self.error = Some(Status::internal(format!("execution task failed: {error}")));
491 self.cancel().await;
492 }
494 None => {},
495 }
496 }
497 incoming = stream.next(), if !input_eof && !self.cancelled => {
498 match incoming {
499 Some(Ok(msg)) => {
500 let is_node = msg.message_kind == EXECUTE_STREAM_NODE;
501 match self.input.accept(msg) {
502 Ok(()) => {
503 if is_node {
504 let node = self.input.plan().nodes.last().expect("accepted NODE");
505 if self.runtime.record_stream_node(&self.input.plan().plan_id, node).await {
506 self.execution.push(Execution::default());
507 } else {
508 self.input.discard_last_node();
509 self.cancel().await;
510 }
511 }
512 }
513 Err(error) => { self.error = Some(Status::invalid_argument(error)); self.cancel().await; }
514 }
515 }
516 None => {
517 input_eof = true;
518 if !self.input.ended() { self.error = Some(Status::invalid_argument("EOF before END")); self.cancel().await; }
519 }
520 Some(Err(error)) => { self.error = Some(error); self.cancel().await; }
521 }
522 }
523 _ = tick.tick() => {},
524 }
525 if self.error.is_some() && self.tasks.is_empty() {
526 for e in &mut self.execution {
527 e.immediate.get_or_insert(true);
528 e.final_failed.get_or_insert(true);
529 }
530 }
531 }
532 self.cancelled |= self.runtime.complete_plan(&self.input.plan().plan_id).await;
533 let failed = self.cancelled
534 || self
535 .execution
536 .get(self.input.plan().root_index as usize)
537 .is_some_and(|e| e.final_failed == Some(true));
538 info!(
539 "[executor/rtdl] plan_id={} plan end state={} nodes={} calls={} duration_ms={}",
540 self.input.plan().plan_id,
541 if self.cancelled {
542 "Canceled"
543 } else if failed || self.error.is_some() {
544 "Failed"
545 } else {
546 "Succeeded"
547 },
548 self.input.plan().nodes.len(),
549 self.input
550 .plan()
551 .nodes
552 .iter()
553 .filter(|node| node.call.is_some())
554 .count(),
555 started_at.elapsed().as_millis()
556 );
557 if let Some(error) = self.error {
558 let _ = self.tx.send(Err(error)).await;
559 } else {
560 let _ = self
561 .tx
562 .send(Ok(rtdl_events::plan_complete(
563 self.input.plan().plan_id.clone(),
564 failed,
565 )))
566 .await;
567 }
568 }
569}
570
571#[cfg(test)]
572mod scheduling_tests {
573 use super::*;
574 use crate::config::VerificationRule;
575 use crate::grpc_server::ExecutorServiceImpl;
576 use crate::pb::contracts::robonix_system_executor_execute_client::RobonixSystemExecutorExecuteClient;
577 use crate::pb::contracts::robonix_system_executor_execute_server::RobonixSystemExecutorExecute;
578 use crate::pb::contracts::robonix_system_executor_execute_server::RobonixSystemExecutorExecuteServer;
579 use crate::pb::contracts::robonix_system_executor_execute_stream_client::RobonixSystemExecutorExecuteStreamClient;
580 use crate::pb::contracts::robonix_system_executor_execute_stream_server::RobonixSystemExecutorExecuteStreamServer;
581 use crate::pb::pilot::Plan;
582 use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum;
583 use crate::pb::pilot::{CapabilityCall, RtdlNode};
584 use crate::plan_input::{EXECUTE_STREAM_CLOSE, EXECUTE_STREAM_END, EXECUTE_STREAM_START};
585 use crate::verification::VerificationPolicy;
586 use robonix_atlas::{
587 client::AtlasClient,
588 service::{AtlasRegistry, serve_atlas},
589 };
590 use std::net::SocketAddr;
591 use std::time::Duration;
592 use tonic::Request;
593 const RTDL_SEQUENCE: u32 = 0;
594 const RTDL_DO: u32 = 2;
595
596 fn reserve_address() -> SocketAddr {
597 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve port");
598 listener.local_addr().expect("reserved address")
599 }
600
601 #[tokio::test]
603 async fn overlap_preserves_immediate_sequence_result() {
604 for (overlap, incremental, repeat) in [
605 (false, false, false),
606 (false, true, false),
607 (true, false, false),
608 (true, true, false),
609 (false, false, true),
610 (true, false, true),
611 (true, true, true),
612 ] {
613 let sequence_index = u32::from(repeat);
614 let verified = sequence_index + 1;
615 let next = sequence_index + 2;
616 let atlas_addr = std::net::TcpListener::bind("127.0.0.1:0")
617 .unwrap()
618 .local_addr()
619 .unwrap();
620 let registry = Arc::new(AtlasRegistry::default());
621 let mut release_verifier = None;
622 let verifier = if repeat && overlap {
623 use robonix_atlas::pb::{
625 Kind, McpParams, Transport, TransportParams, transport_params,
626 };
627 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
628 let endpoint = format!("http://{}/mcp", listener.local_addr().unwrap());
629 let verifier_id = "held_verifier";
630 registry
631 .register(
632 verifier_id,
633 Kind::Service,
634 "robonix/service/verifier",
635 "",
636 "",
637 )
638 .await
639 .unwrap();
640 registry
641 .declare(
642 verifier_id,
643 crate::verification::VERIFY_CONTRACT_ID,
644 Transport::Mcp,
645 &endpoint,
646 TransportParams {
647 kind: Some(transport_params::Kind::Mcp(McpParams {
648 input_schema_json: r#"{"type":"object"}"#.into(),
649 })),
650 },
651 "Verify the call",
652 )
653 .await
654 .unwrap();
655 let (release, wait) = tokio::sync::oneshot::channel();
656 release_verifier = Some(release);
657 tokio::spawn(async move {
658 let _connection = listener.accept().await.unwrap();
659 let _ = wait.await;
660 });
661 verifier_id
662 } else {
663 "missing_verifier"
664 };
665 let atlas_task = tokio::spawn(serve_atlas(registry, atlas_addr));
666 let atlas = AtlasClient::connect_with_retry(
667 format!("http://{atlas_addr}"),
668 50,
669 Duration::from_millis(10),
670 )
671 .await
672 .unwrap();
673 let contract = "robonix/system/executor/builtin/get_all_plans";
674 let svc = ExecutorServiceImpl::new(
675 atlas,
676 "executor".into(),
677 Arc::new(VerificationPolicy::new(
678 overlap,
679 vec![VerificationRule {
680 target_contract_id: contract.into(),
681 target_provider_id: None,
682 verifier_provider_id: verifier.into(),
683 verifier_args: serde_json::json!({}),
684 }],
685 )),
686 );
687 let addr = std::net::TcpListener::bind("127.0.0.1:0")
688 .unwrap()
689 .local_addr()
690 .unwrap();
691 let server = tokio::spawn(
692 tonic::transport::Server::builder()
693 .add_service(RobonixSystemExecutorExecuteServer::new(svc.clone()))
694 .add_service(RobonixSystemExecutorExecuteStreamServer::new(svc.clone()))
695 .serve(addr),
696 );
697 let channel = AtlasClient::connect_with_retry(
698 format!("http://{addr}"),
699 50,
700 Duration::from_millis(10),
701 )
702 .await
703 .unwrap();
704 drop(channel);
705 let mut nodes = vec![
706 RtdlNode {
707 node_kind: 0,
708 children: vec![verified, next],
709 op_id: "root".into(),
710 description: "sequence".into(),
711 ..Default::default()
712 },
713 RtdlNode {
714 node_kind: 2,
715 op_id: "verified".into(),
716 description: "verify".into(),
717 call: Some(CapabilityCall {
718 call_id: "c1".into(),
719 provider_id: "executor".into(),
720 contract_id: contract.into(),
721 args_json: "{}".into(),
722 }),
723 ..Default::default()
724 },
725 RtdlNode {
726 node_kind: 2,
727 op_id: "next".into(),
728 description: "next".into(),
729 call: Some(CapabilityCall {
730 call_id: "c2".into(),
731 provider_id: "executor".into(),
732 contract_id: "robonix/system/executor/builtin/list_dir".into(),
733 args_json: r#"{"path":"."}"#.into(),
734 }),
735 ..Default::default()
736 },
737 ];
738 if repeat {
739 nodes.insert(
740 0,
741 RtdlNode {
742 node_kind: 4,
743 children: vec![sequence_index],
744 op_id: "repeat".into(),
745 description: "run the sequence twice".into(),
746 repeat_count: 2,
747 ..Default::default()
748 },
749 );
750 }
751 let mut response = if incremental {
752 let mut client =
753 RobonixSystemExecutorExecuteStreamClient::connect(format!("http://{addr}"))
754 .await
755 .unwrap();
756 let mut messages = vec![ExecuteStreamInput {
757 message_kind: EXECUTE_STREAM_START,
758 plan_id: "verify".into(),
759 ..Default::default()
760 }];
761 for (index, mut node) in nodes.into_iter().enumerate() {
762 node.children.clear();
763 messages.push(ExecuteStreamInput {
764 message_kind: EXECUTE_STREAM_NODE,
765 node_index: index as u32,
766 has_parent: index != 0,
767 parent_index: if index as u32 > sequence_index {
768 sequence_index
769 } else {
770 0
771 },
772 node: Some(node),
773 ..Default::default()
774 });
775 }
776 for node_index in (0..=sequence_index).rev() {
777 messages.push(ExecuteStreamInput {
778 message_kind: EXECUTE_STREAM_CLOSE,
779 node_index,
780 ..Default::default()
781 });
782 }
783 messages.push(ExecuteStreamInput {
784 message_kind: EXECUTE_STREAM_END,
785 ..Default::default()
786 });
787 client
788 .execute_stream(tokio_stream::iter(messages))
789 .await
790 .unwrap()
791 .into_inner()
792 } else {
793 let mut client =
794 RobonixSystemExecutorExecuteClient::connect(format!("http://{addr}"))
795 .await
796 .unwrap();
797 client
798 .execute(Plan {
799 plan_id: "verify".into(),
800 nodes,
801 ..Default::default()
802 })
803 .await
804 .unwrap()
805 .into_inner()
806 };
807 let events = tokio::time::timeout(Duration::from_secs(5), async {
808 let mut events = Vec::new();
809 while let Some(event) = response.message().await.unwrap() {
810 if let Some(state) = event.node_state.as_ref() {
811 if state.node_index == next
812 && state.state == State::Succeeded as u32
813 && let Some(release) = release_verifier.take()
814 {
815 release.send(()).unwrap();
816 }
817 if state.node_index == verified && state.state == State::Failed as u32 {
818 assert!(
819 release_verifier.is_none(),
820 "verification failed before the sibling ran"
821 );
822 }
823 }
824 events.push(event);
825 }
826 events
827 })
828 .await
829 .unwrap();
830 assert_eq!(
831 events.iter().filter(|e| e.plan_complete.is_some()).count(),
832 1
833 );
834 assert!(
835 events
836 .last()
837 .unwrap()
838 .plan_complete
839 .as_ref()
840 .unwrap()
841 .any_failed
842 );
843 let states: Vec<_> = events
844 .iter()
845 .filter_map(|e| e.node_state.as_ref())
846 .map(|s| (s.node_index, s.state))
847 .collect();
848 assert_eq!(
849 states
850 .iter()
851 .filter(|state| **state == (verified, State::Failed as u32))
852 .count(),
853 1,
854 "verification failure must prevent a second iteration"
855 );
856 assert!(states.contains(&(
857 next,
858 if overlap {
859 State::Succeeded
860 } else {
861 State::Canceled
862 } as u32
863 )));
864 assert_eq!(states.last(), Some(&(0, State::Failed as u32)));
865 assert_eq!(
866 serde_json::from_str::<serde_json::Value>(&svc.runtime.active_plans_json().await)
867 .unwrap()["count"],
868 0
869 );
870 server.abort();
871 atlas_task.abort();
872 }
873 }
874
875 #[tokio::test]
877 async fn overlap_stream_finalizes_the_leaf_before_failing_its_sequence() {
878 let atlas_addr = reserve_address();
879 let atlas_server =
880 tokio::spawn(serve_atlas(Arc::new(AtlasRegistry::default()), atlas_addr));
881 let atlas = AtlasClient::connect_with_retry(
882 format!("http://{atlas_addr}"),
883 50,
884 Duration::from_millis(10),
885 )
886 .await
887 .expect("connect test Atlas");
888 let contract_id = "robonix/system/executor/builtin/get_all_plans";
889 let service = ExecutorServiceImpl::new(
890 atlas,
891 "executor".into(),
892 Arc::new(VerificationPolicy::new(
893 true,
894 vec![VerificationRule {
895 target_contract_id: contract_id.into(),
896 target_provider_id: None,
897 verifier_provider_id: "missing_verifier".into(),
898 verifier_args: serde_json::json!({}),
899 }],
900 )),
901 );
902 let plan = Plan {
903 plan_id: "overlap-plan".into(),
904 session_id: "test".into(),
905 round: 0,
906 nodes: vec![
907 RtdlNode {
908 node_kind: RTDL_SEQUENCE,
909 children: vec![1, 2],
910 call: None,
911 op_id: "sequence".into(),
912 description: "run the verified sequence".into(),
913 ..Default::default()
914 },
915 RtdlNode {
916 node_kind: RTDL_DO,
917 children: Vec::new(),
918 call: Some(CapabilityCall {
919 call_id: "overlap-plan:1".into(),
920 provider_id: "executor".into(),
921 contract_id: contract_id.into(),
922 args_json: "{}".into(),
923 }),
924 op_id: "op_1".into(),
925 description: "list active plans".into(),
926 ..Default::default()
927 },
928 RtdlNode {
929 node_kind: RTDL_DO,
930 children: Vec::new(),
931 call: Some(CapabilityCall {
932 call_id: "overlap-plan:2".into(),
933 provider_id: "executor".into(),
934 contract_id: "robonix/system/executor/builtin/list_dir".into(),
935 args_json: r#"{"path":"."}"#.into(),
936 }),
937 op_id: "op_2".into(),
938 description: "continue with the next node".into(),
939 ..Default::default()
940 },
941 ],
942 root_index: 0,
943 };
944 let mut stream = service
945 .execute(Request::new(plan))
946 .await
947 .unwrap()
948 .into_inner();
949 let mut states = Vec::new();
950 let mut plan_failed = None;
951 while let Some(event) = stream.next().await {
952 let event = event.unwrap();
953 if let Some(state) = event.node_state {
954 states.push((state.node_index, state.state));
955 }
956 if let Some(complete) = event.plan_complete {
957 plan_failed = Some(complete.any_failed);
958 }
959 }
960
961 assert_eq!(
962 states.first(),
963 Some(&(0, RtdlNodeStateEnum::Running as u32))
964 );
965 assert!(states.contains(&(1, RtdlNodeStateEnum::Verifying as u32)));
966 assert!(states.contains(&(0, RtdlNodeStateEnum::Verifying as u32)));
967 assert!(states.contains(&(1, RtdlNodeStateEnum::Failed as u32)));
968 assert!(states.contains(&(2, RtdlNodeStateEnum::Succeeded as u32)));
969 assert_eq!(states.last(), Some(&(0, RtdlNodeStateEnum::Failed as u32)));
970 assert_eq!(plan_failed, Some(true));
971 atlas_server.abort();
972 }
973}