1use crate::active_plans::PlanRuntime;
5use crate::dispatch::{self, async_poll};
6use crate::pb::executor::RtdlEvent;
7use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum;
8use crate::pb::pilot::{CapabilityCall, CapabilityCallResult};
9use crate::rtdl_events::{self, NodeEventContext};
10use crate::verification::{self, VerificationPolicy};
11use robonix_atlas::client::AtlasClient;
12use robonix_scribe::{info, warn};
13use std::sync::Arc;
14use tokio::sync::mpsc::Sender;
15use tokio::task::JoinHandle;
16use tonic::Status;
17
18pub(crate) struct NodeExecution {
20 pub(crate) failed: bool,
22 pub(crate) verifier: Option<JoinHandle<bool>>,
24}
25
26impl NodeExecution {
27 fn finished(failed: bool) -> Self {
29 Self {
30 failed,
31 verifier: None,
32 }
33 }
34}
35
36pub(crate) async fn wait_for_verifier(verifier: JoinHandle<bool>) -> bool {
38 match verifier.await {
39 Ok(failed) => failed,
40 Err(error) => {
41 warn!("[executor/verification] overlap verifier failed to join: {error}");
42 true
43 }
44 }
45}
46
47struct OverlapVerifier {
49 call: CapabilityCall,
51 node: NodeEventContext,
53 tx: Sender<Result<RtdlEvent, Status>>,
55 atlas: AtlasClient,
57 provider_id: String,
59 runtime: PlanRuntime,
61 policy: Arc<VerificationPolicy>,
63 original: CapabilityCallResult,
65 output_view: Option<String>,
67}
68
69fn leaf_terminal_state(success: bool, cancelled: bool) -> u32 {
73 if cancelled {
74 RtdlNodeStateEnum::Canceled as u32
75 } else if success {
76 RtdlNodeStateEnum::Succeeded as u32
77 } else {
78 RtdlNodeStateEnum::Failed as u32
79 }
80}
81
82#[allow(clippy::too_many_arguments)]
84pub(crate) async fn execute_call(
85 call: &CapabilityCall,
86 bind: &str,
87 node: NodeEventContext,
88 tx: Sender<Result<RtdlEvent, Status>>,
89 mut atlas: AtlasClient,
90 provider_id: String,
91 runtime: PlanRuntime,
92 verification: Arc<VerificationPolicy>,
93) -> NodeExecution {
94 let args_preview: String = call.args_json.chars().take(256).collect();
98 let args_ellipsis = if call.args_json.len() > 256 {
99 "…"
100 } else {
101 ""
102 };
103 info!(
104 "[executor] dispatching call_id={} provider='{}' contract='{}' args={}{}",
105 call.call_id, call.provider_id, call.contract_id, args_preview, args_ellipsis,
106 );
107
108 runtime
111 .record_op_state(
112 &node.plan_id,
113 &node.op_id,
114 RtdlNodeStateEnum::Running as u32,
115 )
116 .await;
117
118 let before = verification::capture_before(
119 verification.as_ref(),
120 call,
121 &node,
122 &provider_id,
123 &mut atlas,
124 &runtime,
125 )
126 .await;
127 let external_channel = match before {
128 Err(error) => Err(format!(
129 "result verification unavailable: capability was not dispatched. {error}"
130 )),
131 Ok(()) if runtime.is_cancelled(&node.plan_id).await => Err("plan canceled".to_string()),
132 Ok(()) if call.provider_id == provider_id => Ok(None),
133 Ok(()) => dispatch::connect_channel(call, &provider_id, &mut atlas)
134 .await
135 .map(Some)
136 .map_err(|error| format!("{error:#}")),
137 };
138
139 let (mut result, mut state) = match external_channel {
140 Err(error) => {
141 let r = CapabilityCallResult {
142 call_id: call.call_id.clone(),
143 provider_id: call.provider_id.clone(),
144 contract_id: call.contract_id.clone(),
145 success: false,
146 output: String::new(),
147 error,
148 };
149 (r, RtdlNodeStateEnum::Failed as u32)
150 }
151 Ok(Some(channel)) => async_poll::run_until_terminal(call, &channel, &node, &runtime).await,
152 Ok(None) => {
153 let r =
154 crate::dispatch::dispatch(call, &provider_id, &mut atlas, &runtime, &node.plan_id)
155 .await;
156 let cancelled = runtime.is_cancelled(&node.plan_id).await;
157 let state = leaf_terminal_state(r.success, cancelled);
158 (r, state)
159 }
160 };
161
162 let eligible_for_verification = result.success
163 && state == RtdlNodeStateEnum::Succeeded as u32
164 && !runtime.is_cancelled(&node.plan_id).await;
165 let overlap = bind.is_empty()
166 && eligible_for_verification
167 && verification.overlap()
168 && verification.rule_for(call).is_some();
169
170 if overlap {
171 runtime
172 .record_op_state(
173 &node.plan_id,
174 &node.op_id,
175 RtdlNodeStateEnum::Verifying as u32,
176 )
177 .await;
178 let view = crate::output_view::prepare(&result).await;
179 let output_view = Some(view.output.clone());
180 let _ = tx
181 .send(Ok(rtdl_events::node_state_from_result(
182 &node,
183 view,
184 RtdlNodeStateEnum::Verifying as u32,
185 )))
186 .await;
187 log_success(call, &result);
188
189 let verifier = tokio::spawn(
190 OverlapVerifier {
191 call: call.clone(),
192 node,
193 tx,
194 atlas,
195 provider_id,
196 runtime,
197 policy: verification,
198 original: result,
199 output_view,
200 }
201 .run(),
202 );
203 return NodeExecution {
204 failed: false,
205 verifier: Some(verifier),
206 };
207 }
208
209 if eligible_for_verification {
210 result = verification::verify_result(
211 verification.as_ref(),
212 call,
213 &node,
214 result,
215 &provider_id,
216 &mut atlas,
217 &runtime,
218 )
219 .await;
220 if !result.success {
221 state = RtdlNodeStateEnum::Failed as u32;
222 }
223 }
224
225 if runtime.is_cancelled(&node.plan_id).await {
226 state = RtdlNodeStateEnum::Canceled as u32;
227 }
228 if state == RtdlNodeStateEnum::Succeeded as u32 && !bind.is_empty() {
229 runtime
230 .context(&node.plan_id)
231 .await
232 .store(bind, &result.output)
233 .await;
234 info!(
235 "[executor/rtdl] plan_id={} node={} op_id={} kind=do bind stored name='{}' output_bytes={}",
236 node.plan_id,
237 node.node_index,
238 node.op_id,
239 bind,
240 result.output.len()
241 );
242 }
243 runtime
244 .record_op_state(&node.plan_id, &node.op_id, state)
245 .await;
246 let _ = tx
247 .send(Ok(rtdl_events::node_state_from_result(
248 &node,
249 crate::output_view::prepare(&result).await,
250 state,
251 )))
252 .await;
253 let failed = !result.success;
254
255 if result.success {
256 log_success(call, &result);
257 } else {
258 warn!("[executor] '{}' failed: {}", call.contract_id, result.error);
259 }
260
261 NodeExecution::finished(failed)
262}
263
264impl OverlapVerifier {
265 async fn run(mut self) -> bool {
267 let original_output = self.original.output.clone();
268 let verified = verification::verify_result(
269 self.policy.as_ref(),
270 &self.call,
271 &self.node,
272 self.original,
273 &self.provider_id,
274 &mut self.atlas,
275 &self.runtime,
276 )
277 .await;
278 let state = leaf_terminal_state(verified.success, false);
282 self.runtime
283 .record_op_state(&self.node.plan_id, &self.node.op_id, state)
284 .await;
285 let mut view = verified.clone();
286 if let Some(output) = self
287 .output_view
288 .filter(|_| verified.output == original_output)
289 {
290 view.output = output;
291 } else {
292 view = crate::output_view::prepare(&verified).await;
293 }
294 let _ = self
295 .tx
296 .send(Ok(rtdl_events::node_state_from_result(
297 &self.node, view, state,
298 )))
299 .await;
300 if !verified.success {
301 warn!(
302 "[executor] '{}' verification finalized call_id={} as failed: {}",
303 self.call.contract_id, self.call.call_id, verified.error
304 );
305 }
306 !verified.success
307 }
308}
309
310fn log_success(call: &CapabilityCall, result: &CapabilityCallResult) {
312 let preview: String = result.output.chars().take(512).collect();
313 let ellipsis = if result.output.len() > 512 { "..." } else { "" };
314 info!(
315 "[executor] '{}' ok: {}{}",
316 call.contract_id, preview, ellipsis
317 );
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use crate::config::VerificationRule;
324 use robonix_atlas::service::{AtlasRegistry, serve_atlas};
325 use std::net::SocketAddr;
326 use std::time::Duration;
327 const RTDL_DO: u32 = 2;
328
329 fn call(id: &str) -> CapabilityCall {
331 CapabilityCall {
332 call_id: id.to_string(),
333 provider_id: "provider".to_string(),
334 contract_id: "robonix/test/cap".to_string(),
335 args_json: "{}".to_string(),
336 }
337 }
338
339 fn reserve_address() -> SocketAddr {
340 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve port");
341 listener.local_addr().expect("reserved address")
342 }
343
344 #[tokio::test]
346 async fn overlap_verifier_reports_outcome_and_join_failure() {
347 assert!(!wait_for_verifier(tokio::spawn(async { false })).await);
348 assert!(wait_for_verifier(tokio::spawn(async { true })).await);
349 assert!(wait_for_verifier(tokio::spawn(async { panic!("test verifier panic") })).await);
350 let verifier = tokio::spawn(std::future::pending::<bool>());
351 verifier.abort();
352 assert!(wait_for_verifier(verifier).await);
353 }
354
355 #[tokio::test]
357 async fn synchronous_verification_never_emits_verifying() {
358 let atlas_addr = reserve_address();
359 let atlas_server =
360 tokio::spawn(serve_atlas(Arc::new(AtlasRegistry::default()), atlas_addr));
361 let atlas = AtlasClient::connect_with_retry(
362 format!("http://{atlas_addr}"),
363 50,
364 Duration::from_millis(10),
365 )
366 .await
367 .expect("connect test Atlas");
368 let runtime = PlanRuntime::default();
369 runtime.register_plan("p").await.unwrap();
370 let contract_id = "robonix/system/executor/builtin/get_all_plans";
371 let call = CapabilityCall {
372 call_id: "p:1".into(),
373 provider_id: "executor".into(),
374 contract_id: contract_id.into(),
375 args_json: "{}".into(),
376 };
377 let (tx, mut rx) = tokio::sync::mpsc::channel(2);
378 let execution = execute_call(
379 &call,
380 "",
381 NodeEventContext {
382 plan_id: "p".into(),
383 node_index: 1,
384 node_kind: RTDL_DO,
385 op_id: "op_1".into(),
386 description: "verify synchronously".into(),
387 },
388 tx,
389 atlas,
390 "executor".into(),
391 runtime,
392 Arc::new(VerificationPolicy::new(
393 false,
394 vec![VerificationRule {
395 target_contract_id: contract_id.into(),
396 target_provider_id: None,
397 verifier_provider_id: "missing_verifier".into(),
398 verifier_args: serde_json::json!({}),
399 }],
400 )),
401 )
402 .await;
403
404 assert!(execution.failed);
405 assert!(execution.verifier.is_none());
406 let terminal = rx.recv().await.unwrap().unwrap().node_state.unwrap();
407 assert_eq!(terminal.state, RtdlNodeStateEnum::Failed as u32);
408 assert!(!terminal.leaf_result.unwrap().output.is_empty());
409 assert!(rx.try_recv().is_err());
410 atlas_server.abort();
411 }
412
413 #[tokio::test]
415 async fn overlap_verifier_failure_finalizes_only_its_node() {
416 let atlas_addr = reserve_address();
417 let atlas_server =
418 tokio::spawn(serve_atlas(Arc::new(AtlasRegistry::default()), atlas_addr));
419 let atlas = AtlasClient::connect_with_retry(
420 format!("http://{atlas_addr}"),
421 50,
422 Duration::from_millis(10),
423 )
424 .await
425 .expect("connect test Atlas");
426 let runtime = PlanRuntime::default();
427 runtime.register_plan("p").await.unwrap();
428 let (tx, mut rx) = tokio::sync::mpsc::channel(1);
429 let target_call = call("p:1");
430 let verifier = OverlapVerifier {
431 output_view: Some("saved-reference".into()),
433 call: target_call.clone(),
434 node: NodeEventContext {
435 plan_id: "p".into(),
436 node_index: 1,
437 node_kind: RTDL_DO,
438 op_id: "op_1".into(),
439 description: "verify this node only".into(),
440 },
441 tx,
442 atlas,
443 provider_id: "executor".into(),
444 runtime,
445 policy: Arc::new(VerificationPolicy::new(
446 true,
447 vec![VerificationRule {
448 target_contract_id: target_call.contract_id.clone(),
449 target_provider_id: None,
450 verifier_provider_id: "missing_verifier".into(),
451 verifier_args: serde_json::json!({}),
452 }],
453 )),
454 original: CapabilityCallResult {
455 call_id: target_call.call_id,
456 provider_id: target_call.provider_id,
457 contract_id: target_call.contract_id,
458 success: true,
459 output: "done".into(),
460 error: String::new(),
461 },
462 };
463
464 assert!(verifier.run().await);
465 let event = rx.recv().await.unwrap().unwrap();
466 let final_state = event.node_state.unwrap();
467 assert_eq!(final_state.node_index, 1);
468 assert_eq!(final_state.state, RtdlNodeStateEnum::Failed as u32);
469 let leaf = final_state.leaf_result.unwrap();
470 assert!(!leaf.success);
471 assert_eq!(leaf.output, "saved-reference");
472 assert!(rx.try_recv().is_err());
473 atlas_server.abort();
474 }
475
476 #[tokio::test]
478 async fn canceled_plan_keeps_verifying_leaf_success() {
479 let atlas_addr = reserve_address();
480 let atlas_server =
481 tokio::spawn(serve_atlas(Arc::new(AtlasRegistry::default()), atlas_addr));
482 let atlas = AtlasClient::connect_with_retry(
483 format!("http://{atlas_addr}"),
484 50,
485 Duration::from_millis(10),
486 )
487 .await
488 .expect("connect test Atlas");
489 let runtime = PlanRuntime::default();
490 runtime.register_plan("p").await.unwrap();
491 runtime.cancel_plan_control("p", 0).await;
492 assert!(runtime.is_cancelled("p").await);
493 let (tx, mut rx) = tokio::sync::mpsc::channel(1);
494 let target_call = call("p:1");
495 let verifier = OverlapVerifier {
496 output_view: None,
497 call: target_call.clone(),
498 node: NodeEventContext {
499 plan_id: "p".into(),
500 node_index: 1,
501 node_kind: RTDL_DO,
502 op_id: "op_1".into(),
503 description: "already completed capability".into(),
504 },
505 tx,
506 atlas,
507 provider_id: "executor".into(),
508 runtime,
509 policy: Arc::new(VerificationPolicy::new(true, Vec::new())),
510 original: CapabilityCallResult {
511 call_id: target_call.call_id,
512 provider_id: target_call.provider_id,
513 contract_id: target_call.contract_id,
514 success: true,
515 output: "done".into(),
516 error: String::new(),
517 },
518 };
519
520 assert!(!verifier.run().await);
521 let final_state = rx.recv().await.unwrap().unwrap().node_state.unwrap();
522 assert_eq!(final_state.state, RtdlNodeStateEnum::Succeeded as u32);
523 assert!(final_state.leaf_result.unwrap().success);
524 atlas_server.abort();
525 }
526
527 #[test]
529 fn canceled_leaf_is_not_reported_as_failed_provider_work() {
530 assert_eq!(
531 leaf_terminal_state(false, true),
532 RtdlNodeStateEnum::Canceled as u32
533 );
534 assert_eq!(
535 leaf_terminal_state(false, false),
536 RtdlNodeStateEnum::Failed as u32
537 );
538 assert_eq!(
539 leaf_terminal_state(true, false),
540 RtdlNodeStateEnum::Succeeded as u32
541 );
542 }
543}