1use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
2
3use crate::{
4 CycleValidationCurrent, EdgeEndpointCurrent, EdgeSpecCurrent, ExecutionGroup, ExecutionModel,
5 ExecutionModelCurrent, FanOutPolicyCurrent, GraphDocumentCurrent, GraphNodeCurrent,
6 GraphValidationResultCurrent, MergePolicyCurrent, NodeDefinitionCurrent,
7 PatchDefinitionCurrent, PlanEdge, PlanEdgeMetadata, PlanNode, ProjectDocumentCurrent,
8 RuntimeDiagnostic, ViewState,
9};
10use serde::Deserialize;
11use serde_json::{Map, Value, json};
12
13const SUBPATCH_KIND: &str = "core.subpatch";
14const SUBPATCH_SHORTHAND_KIND: &str = "p";
15const INLET_KIND: &str = "core.inlet";
16const OUTLET_KIND: &str = "core.outlet";
17const MAX_SUBPATCH_DEPTH: usize = 16;
18pub const CURRENT_SCHEMA_VERSION: &str = "0.1.0";
19
20#[derive(Debug, Clone, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct ProjectRequestCurrent {
23 #[serde(skip)]
24 pub document: Option<ProjectDocumentCurrent>,
25 pub graph: GraphDocumentCurrent,
26 #[serde(default)]
27 pub nodes: Vec<NodeDefinitionCurrent>,
28 #[serde(default)]
29 pub patch_library: Vec<PatchDefinitionCurrent>,
30 #[serde(default)]
31 pub view_state: Option<ViewState>,
32}
33
34#[derive(Debug, Clone, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct RunProjectRequestCurrent {
37 #[serde(skip)]
38 pub document: Option<ProjectDocumentCurrent>,
39 pub graph: GraphDocumentCurrent,
40 #[serde(default)]
41 pub nodes: Vec<NodeDefinitionCurrent>,
42 #[serde(default)]
43 pub patch_library: Vec<PatchDefinitionCurrent>,
44 #[serde(default)]
45 pub view_state: Option<ViewState>,
46 pub frames: Option<usize>,
47}
48
49impl From<ProjectDocumentCurrent> for ProjectRequestCurrent {
50 fn from(document: ProjectDocumentCurrent) -> Self {
51 Self {
52 graph: document.graph.clone(),
53 nodes: Vec::new(),
54 patch_library: document.patch_library.clone(),
55 view_state: Some(document.view_state.clone()),
56 document: Some(document),
57 }
58 }
59}
60
61impl From<ProjectDocumentCurrent> for RunProjectRequestCurrent {
62 fn from(document: ProjectDocumentCurrent) -> Self {
63 Self {
64 graph: document.graph.clone(),
65 nodes: Vec::new(),
66 patch_library: document.patch_library.clone(),
67 view_state: Some(document.view_state.clone()),
68 document: Some(document),
69 frames: None,
70 }
71 }
72}
73
74impl ProjectRequestCurrent {
75 pub fn from_project_document(
76 document: ProjectDocumentCurrent,
77 nodes: Vec<NodeDefinitionCurrent>,
78 ) -> Self {
79 Self {
80 graph: document.graph.clone(),
81 nodes,
82 patch_library: document.patch_library.clone(),
83 view_state: Some(document.view_state.clone()),
84 document: Some(document),
85 }
86 }
87}
88
89impl RunProjectRequestCurrent {
90 pub fn from_project_document(
91 document: ProjectDocumentCurrent,
92 nodes: Vec<NodeDefinitionCurrent>,
93 frames: Option<usize>,
94 ) -> Self {
95 Self {
96 graph: document.graph.clone(),
97 nodes,
98 patch_library: document.patch_library.clone(),
99 view_state: Some(document.view_state.clone()),
100 document: Some(document),
101 frames,
102 }
103 }
104}
105
106type CurrentValidation =
107 Result<(Vec<RuntimeDiagnostic>, GraphValidationResultCurrent), Vec<RuntimeDiagnostic>>;
108
109#[derive(Debug, Clone)]
110struct ExpandedGraphCurrent {
111 nodes: Vec<GraphNodeCurrent>,
112 edges: Vec<ExpansionEdge>,
113 boundary_pins: HashSet<String>,
114 inlets: HashMap<String, String>,
115 outlets: HashMap<String, String>,
116}
117
118#[derive(Debug, Clone)]
119struct ExpansionEdge {
120 edge: EdgeSpecCurrent,
121 source: ExpansionEndpoint,
122 target: ExpansionEndpoint,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
126enum ExpansionEndpoint {
127 Node(EdgeEndpointCurrent),
128 Boundary(String),
129}
130
131#[derive(Debug, Clone)]
132enum NodeExpansion {
133 Node(String),
134 Boundary(String),
135 Subpatch {
136 inlets: HashMap<String, String>,
137 outlets: HashMap<String, String>,
138 },
139}
140
141#[derive(Debug, Clone, Copy)]
142enum BoundaryKind {
143 Inlet,
144 Outlet,
145}
146
147struct ExpansionContext<'a> {
148 patches: HashMap<&'a str, &'a PatchDefinitionCurrent>,
149 diagnostics: Vec<RuntimeDiagnostic>,
150}
151
152pub fn expand_project_graph_current(
153 graph: &GraphDocumentCurrent,
154 patch_library: &[PatchDefinitionCurrent],
155) -> Result<GraphDocumentCurrent, Vec<RuntimeDiagnostic>> {
156 let mut context = ExpansionContext {
157 patches: patch_library
158 .iter()
159 .map(|definition| (definition.id.as_str(), definition))
160 .collect(),
161 diagnostics: Vec::new(),
162 };
163 let expanded = expand_graph_current(graph, "", 0, &[], &mut context);
164
165 if !context.diagnostics.is_empty() {
166 return Err(context.diagnostics);
167 }
168
169 Ok(GraphDocumentCurrent {
170 schema: graph.schema.clone(),
171 schema_version: graph.schema_version.clone(),
172 id: graph.id.clone(),
173 revision: graph.revision.clone(),
174 nodes: expanded.nodes,
175 edges: contract_boundary_edges(expanded.edges, expanded.boundary_pins),
176 cable_styles: graph.cable_styles.clone(),
177 })
178}
179
180pub fn validate_project_request_current(request: &ProjectRequestCurrent) -> CurrentValidation {
181 validate_patch_library_current(&request.patch_library)?;
182 let graph = expand_project_graph_current(&request.graph, &request.patch_library)?;
183 validate_project_current(&graph, &request.nodes)
184}
185
186pub fn build_execution_plan_request_current(
187 request: &ProjectRequestCurrent,
188) -> Result<(crate::ExecutionPlan, Vec<RuntimeDiagnostic>), Vec<RuntimeDiagnostic>> {
189 validate_patch_library_current(&request.patch_library)?;
190 let graph = expand_project_graph_current(&request.graph, &request.patch_library)?;
191 build_execution_plan_current(&graph, &request.nodes)
192}
193
194pub fn build_execution_plan_run_request_current(
195 request: &RunProjectRequestCurrent,
196) -> Result<(crate::ExecutionPlan, Vec<RuntimeDiagnostic>), Vec<RuntimeDiagnostic>> {
197 validate_patch_library_current(&request.patch_library)?;
198 let graph = expand_project_graph_current(&request.graph, &request.patch_library)?;
199 build_execution_plan_current(&graph, &request.nodes)
200}
201
202fn validate_patch_library_current(
203 patch_library: &[PatchDefinitionCurrent],
204) -> Result<(), Vec<RuntimeDiagnostic>> {
205 let mut diagnostics = Vec::new();
206 let mut seen = HashSet::new();
207
208 for patch in patch_library {
209 if !seen.insert(patch.id.as_str()) {
210 diagnostics.push(RuntimeDiagnostic::structured_error(
211 "subpatch.duplicate-patch-id",
212 format!("duplicate patch id: {}", patch.id),
213 json!({ "patchId": patch.id }),
214 ));
215 }
216
217 if let Some(diagnostic) = schema_version_diagnostic_with_details(
218 "graph",
219 Some(patch.graph.schema_version.as_str()),
220 json!({ "patchId": patch.id }),
221 ) {
222 diagnostics.push(diagnostic);
223 }
224
225 if let Err(report) = skenion_contracts::validate_patch_definition_v01(patch) {
226 diagnostics.extend(
227 report
228 .errors()
229 .iter()
230 .filter(|error| !is_schema_version_contract_error(&error.message))
231 .map(|error| {
232 RuntimeDiagnostic::structured_error(
233 "subpatch.invalid-patch-definition",
234 error.message.clone(),
235 json!({ "patchId": patch.id }),
236 )
237 }),
238 );
239 }
240 }
241
242 if diagnostics.is_empty() {
243 Ok(())
244 } else {
245 Err(diagnostics)
246 }
247}
248
249fn expand_graph_current(
250 graph: &GraphDocumentCurrent,
251 namespace: &str,
252 depth: usize,
253 stack: &[String],
254 context: &mut ExpansionContext<'_>,
255) -> ExpandedGraphCurrent {
256 let mut expanded = ExpandedGraphCurrent {
257 nodes: Vec::new(),
258 edges: Vec::new(),
259 boundary_pins: HashSet::new(),
260 inlets: HashMap::new(),
261 outlets: HashMap::new(),
262 };
263 let mut node_expansions = HashMap::new();
264
265 for node in &graph.nodes {
266 if is_inlet_node(node) {
267 let pin = register_boundary_node(
268 node,
269 namespace,
270 BoundaryKind::Inlet,
271 &mut expanded.boundary_pins,
272 &mut expanded.inlets,
273 );
274 node_expansions.insert(node.id.clone(), NodeExpansion::Boundary(pin));
275 } else if is_outlet_node(node) {
276 let pin = register_boundary_node(
277 node,
278 namespace,
279 BoundaryKind::Outlet,
280 &mut expanded.boundary_pins,
281 &mut expanded.outlets,
282 );
283 node_expansions.insert(node.id.clone(), NodeExpansion::Boundary(pin));
284 } else if is_subpatch_node(node) {
285 let Some(patch_ref) = subpatch_ref(node) else {
286 context.diagnostics.push(subpatch_diagnostic(
287 "subpatch.missing-ref",
288 format!(
289 "subpatch node {} is missing a patch reference",
290 namespaced_id(namespace, &node.id)
291 ),
292 namespace,
293 node,
294 None,
295 depth,
296 stack,
297 ));
298 continue;
299 };
300
301 if stack.iter().any(|id| id == &patch_ref) {
302 let mut path = stack.to_vec();
303 path.push(patch_ref.clone());
304 context.diagnostics.push(subpatch_diagnostic_with_path(
305 "subpatch.recursion",
306 format!(
307 "subpatch node {} recursively references patch definition {patch_ref}",
308 namespaced_id(namespace, &node.id)
309 ),
310 namespace,
311 node,
312 Some(&patch_ref),
313 depth + 1,
314 &path,
315 ));
316 continue;
317 }
318
319 if depth + 1 > MAX_SUBPATCH_DEPTH {
320 let mut path = stack.to_vec();
321 path.push(patch_ref.clone());
322 context.diagnostics.push(subpatch_diagnostic_with_path(
323 "subpatch.depth-exceeded",
324 format!(
325 "subpatch node {} exceeds maximum expansion depth {MAX_SUBPATCH_DEPTH}",
326 namespaced_id(namespace, &node.id)
327 ),
328 namespace,
329 node,
330 Some(&patch_ref),
331 depth + 1,
332 &path,
333 ));
334 continue;
335 }
336
337 let Some(definition_graph) = context
338 .patches
339 .get(patch_ref.as_str())
340 .map(|definition| definition.graph.clone())
341 else {
342 context.diagnostics.push(subpatch_diagnostic(
343 "subpatch.missing-patch",
344 format!(
345 "subpatch node {} references missing patch definition {patch_ref}",
346 namespaced_id(namespace, &node.id)
347 ),
348 namespace,
349 node,
350 Some(&patch_ref),
351 depth,
352 stack,
353 ));
354 continue;
355 };
356
357 let child_namespace = namespaced_id(namespace, &node.id);
358 let mut child_stack = stack.to_vec();
359 child_stack.push(patch_ref);
360 let child = expand_graph_current(
361 &definition_graph,
362 &child_namespace,
363 depth + 1,
364 &child_stack,
365 context,
366 );
367 expanded.nodes.extend(child.nodes);
368 expanded.edges.extend(child.edges);
369 expanded.boundary_pins.extend(child.boundary_pins);
370 node_expansions.insert(
371 node.id.clone(),
372 NodeExpansion::Subpatch {
373 inlets: child.inlets,
374 outlets: child.outlets,
375 },
376 );
377 } else {
378 let namespaced = namespaced_id(namespace, &node.id);
379 let mut cloned = node.clone();
380 cloned.id = namespaced.clone();
381 expanded.nodes.push(cloned);
382 node_expansions.insert(node.id.clone(), NodeExpansion::Node(namespaced));
383 }
384 }
385
386 for edge in &graph.edges {
387 let source = resolve_source_endpoint(edge, namespace, &node_expansions, context);
388 let target = resolve_target_endpoint(edge, namespace, &node_expansions, context);
389 let mut cloned = edge.clone();
390 cloned.id = namespaced_id(namespace, &edge.id);
391 expanded.edges.push(ExpansionEdge {
392 edge: cloned,
393 source,
394 target,
395 });
396 }
397
398 expanded
399}
400
401fn contract_boundary_edges(
402 mut edges: Vec<ExpansionEdge>,
403 boundary_pins: HashSet<String>,
404) -> Vec<EdgeSpecCurrent> {
405 let mut counter = 0usize;
406
407 while let Some(pin) = boundary_pins
408 .iter()
409 .find(|pin| {
410 has_incoming_boundary_edge(&edges, pin) && has_outgoing_boundary_edge(&edges, pin)
411 })
412 .cloned()
413 {
414 let incoming = edges
415 .iter()
416 .filter(|edge| matches!(&edge.target, ExpansionEndpoint::Boundary(candidate) if candidate == &pin))
417 .cloned()
418 .collect::<Vec<_>>();
419 let outgoing = edges
420 .iter()
421 .filter(|edge| matches!(&edge.source, ExpansionEndpoint::Boundary(candidate) if candidate == &pin))
422 .cloned()
423 .collect::<Vec<_>>();
424 let mut retained = edges
425 .into_iter()
426 .filter(|edge| !edge_touches_boundary_pin(edge, &pin))
427 .collect::<Vec<_>>();
428
429 for source_edge in &incoming {
430 for target_edge in &outgoing {
431 if source_edge.source == target_edge.target {
432 continue;
433 }
434 counter += 1;
435 retained.push(merge_boundary_edges(
436 source_edge,
437 target_edge,
438 &pin,
439 counter,
440 ));
441 }
442 }
443
444 edges = retained;
445 }
446
447 edges
448 .into_iter()
449 .filter_map(expansion_edge_to_real_edge)
450 .collect()
451}
452
453fn has_incoming_boundary_edge(edges: &[ExpansionEdge], pin: &str) -> bool {
454 edges.iter().any(
455 |edge| matches!(&edge.target, ExpansionEndpoint::Boundary(candidate) if candidate == pin),
456 )
457}
458
459fn has_outgoing_boundary_edge(edges: &[ExpansionEdge], pin: &str) -> bool {
460 edges.iter().any(
461 |edge| matches!(&edge.source, ExpansionEndpoint::Boundary(candidate) if candidate == pin),
462 )
463}
464
465fn edge_touches_boundary_pin(edge: &ExpansionEdge, pin: &str) -> bool {
466 matches!(&edge.source, ExpansionEndpoint::Boundary(candidate) if candidate == pin)
467 || matches!(&edge.target, ExpansionEndpoint::Boundary(candidate) if candidate == pin)
468}
469
470fn merge_boundary_edges(
471 source_edge: &ExpansionEdge,
472 target_edge: &ExpansionEdge,
473 pin: &str,
474 counter: usize,
475) -> ExpansionEdge {
476 let mut edge = target_edge.edge.clone();
477 edge.id = format!(
478 "{}__{}__{}",
479 source_edge.edge.id,
480 boundary_id_fragment(pin),
481 counter
482 );
483 if edge.resolved_type.is_none() {
484 edge.resolved_type = source_edge.edge.resolved_type.clone();
485 }
486 if edge.order.is_none() {
487 edge.order = source_edge.edge.order;
488 }
489 if edge.enabled.is_none() {
490 edge.enabled = source_edge.edge.enabled;
491 }
492 if edge.adapter.is_none() {
493 edge.adapter = source_edge.edge.adapter.clone();
494 }
495 if edge.feedback.is_none() {
496 edge.feedback = source_edge.edge.feedback.clone();
497 }
498 if edge.style_override.is_none() {
499 edge.style_override = source_edge.edge.style_override.clone();
500 }
501 if edge.label.is_none() {
502 edge.label = source_edge.edge.label.clone();
503 }
504 if edge.description.is_none() {
505 edge.description = source_edge.edge.description.clone();
506 }
507
508 ExpansionEdge {
509 edge,
510 source: source_edge.source.clone(),
511 target: target_edge.target.clone(),
512 }
513}
514
515fn expansion_edge_to_real_edge(expansion: ExpansionEdge) -> Option<EdgeSpecCurrent> {
516 let ExpansionEndpoint::Node(source) = expansion.source else {
517 return None;
518 };
519 let ExpansionEndpoint::Node(target) = expansion.target else {
520 return None;
521 };
522 let mut edge = expansion.edge;
523 edge.source = source;
524 edge.target = target;
525 Some(edge)
526}
527
528fn resolve_source_endpoint(
529 edge: &EdgeSpecCurrent,
530 namespace: &str,
531 nodes: &HashMap<String, NodeExpansion>,
532 context: &mut ExpansionContext<'_>,
533) -> ExpansionEndpoint {
534 match nodes.get(&edge.source.node_id) {
535 Some(NodeExpansion::Node(node_id)) => ExpansionEndpoint::Node(EdgeEndpointCurrent {
536 node_id: node_id.clone(),
537 port_id: edge.source.port_id.clone(),
538 }),
539 Some(NodeExpansion::Boundary(pin)) => ExpansionEndpoint::Boundary(pin.clone()),
540 Some(NodeExpansion::Subpatch { outlets, .. }) => outlets
541 .get(edge.source.port_id.as_str())
542 .map(|pin| ExpansionEndpoint::Boundary(pin.clone()))
543 .unwrap_or_else(|| {
544 context.diagnostics.push(boundary_diagnostic(
545 "subpatch.missing-outlet",
546 format!(
547 "subpatch node {} has no outlet boundary for port {}",
548 namespaced_id(namespace, &edge.source.node_id),
549 edge.source.port_id
550 ),
551 namespace,
552 &edge.source.node_id,
553 &edge.source.port_id,
554 BoundaryKind::Outlet,
555 ));
556 ExpansionEndpoint::Node(EdgeEndpointCurrent {
557 node_id: namespaced_id(namespace, &edge.source.node_id),
558 port_id: edge.source.port_id.clone(),
559 })
560 }),
561 None => ExpansionEndpoint::Node(EdgeEndpointCurrent {
562 node_id: namespaced_id(namespace, &edge.source.node_id),
563 port_id: edge.source.port_id.clone(),
564 }),
565 }
566}
567
568fn resolve_target_endpoint(
569 edge: &EdgeSpecCurrent,
570 namespace: &str,
571 nodes: &HashMap<String, NodeExpansion>,
572 context: &mut ExpansionContext<'_>,
573) -> ExpansionEndpoint {
574 match nodes.get(&edge.target.node_id) {
575 Some(NodeExpansion::Node(node_id)) => ExpansionEndpoint::Node(EdgeEndpointCurrent {
576 node_id: node_id.clone(),
577 port_id: edge.target.port_id.clone(),
578 }),
579 Some(NodeExpansion::Boundary(pin)) => ExpansionEndpoint::Boundary(pin.clone()),
580 Some(NodeExpansion::Subpatch { inlets, .. }) => inlets
581 .get(edge.target.port_id.as_str())
582 .map(|pin| ExpansionEndpoint::Boundary(pin.clone()))
583 .unwrap_or_else(|| {
584 context.diagnostics.push(boundary_diagnostic(
585 "subpatch.missing-inlet",
586 format!(
587 "subpatch node {} has no inlet boundary for port {}",
588 namespaced_id(namespace, &edge.target.node_id),
589 edge.target.port_id
590 ),
591 namespace,
592 &edge.target.node_id,
593 &edge.target.port_id,
594 BoundaryKind::Inlet,
595 ));
596 ExpansionEndpoint::Node(EdgeEndpointCurrent {
597 node_id: namespaced_id(namespace, &edge.target.node_id),
598 port_id: edge.target.port_id.clone(),
599 })
600 }),
601 None => ExpansionEndpoint::Node(EdgeEndpointCurrent {
602 node_id: namespaced_id(namespace, &edge.target.node_id),
603 port_id: edge.target.port_id.clone(),
604 }),
605 }
606}
607
608fn register_boundary_node(
609 node: &GraphNodeCurrent,
610 namespace: &str,
611 kind: BoundaryKind,
612 boundary_pins: &mut HashSet<String>,
613 aliases: &mut HashMap<String, String>,
614) -> String {
615 let key = boundary_key(node);
616 let pin = format!(
617 "{}@{}::{}",
618 namespace_prefix(namespace),
619 match kind {
620 BoundaryKind::Inlet => "inlet",
621 BoundaryKind::Outlet => "outlet",
622 },
623 key
624 );
625 boundary_pins.insert(pin.clone());
626
627 for alias in boundary_aliases(node, &key) {
628 match aliases.get(&alias) {
629 Some(existing) if existing != &pin => {
630 aliases.remove(&alias);
631 }
632 Some(_) => {}
633 None => {
634 aliases.insert(alias, pin.clone());
635 }
636 }
637 }
638
639 pin
640}
641
642fn boundary_aliases(node: &GraphNodeCurrent, key: &str) -> Vec<String> {
643 let mut aliases = vec![key.to_owned(), node.id.clone()];
644 for param_key in ["portId", "port", "name", "id", "label"] {
645 if let Some(alias) = string_param(&node.params, param_key) {
646 aliases.push(alias);
647 }
648 }
649 if node.ports.len() == 1 {
650 aliases.push(node.ports[0].id.clone());
651 }
652 aliases.sort();
653 aliases.dedup();
654 aliases
655}
656
657fn boundary_key(node: &GraphNodeCurrent) -> String {
658 ["portId", "port", "name", "id", "label"]
659 .into_iter()
660 .find_map(|key| string_param(&node.params, key))
661 .unwrap_or_else(|| node.id.clone())
662}
663
664fn subpatch_ref(node: &GraphNodeCurrent) -> Option<String> {
665 ["patchRef", "patchId", "patch", "ref", "name", "id"]
666 .into_iter()
667 .find_map(|key| string_param(&node.params, key))
668 .or_else(|| {
669 ["objectText", "sourceText", "text"]
670 .into_iter()
671 .find_map(|key| string_param(&node.params, key))
672 .and_then(|text| parse_subpatch_object_text(&text))
673 })
674}
675
676fn parse_subpatch_object_text(text: &str) -> Option<String> {
677 let mut parts = text.split_whitespace();
678 match (parts.next(), parts.next()) {
679 (Some("p" | "core.subpatch"), Some(patch_ref)) => Some(patch_ref.to_owned()),
680 _ => None,
681 }
682}
683
684fn string_param(params: &Map<String, Value>, key: &str) -> Option<String> {
685 match params.get(key)? {
686 Value::String(value) if !value.is_empty() => Some(value.clone()),
687 Value::Number(value) => Some(value.to_string()),
688 _ => None,
689 }
690}
691
692fn is_subpatch_node(node: &GraphNodeCurrent) -> bool {
693 matches!(node.kind.as_str(), SUBPATCH_KIND | SUBPATCH_SHORTHAND_KIND)
694}
695
696fn is_inlet_node(node: &GraphNodeCurrent) -> bool {
697 node.kind == INLET_KIND
698}
699
700fn is_outlet_node(node: &GraphNodeCurrent) -> bool {
701 node.kind == OUTLET_KIND
702}
703
704fn namespaced_id(namespace: &str, id: &str) -> String {
705 if namespace.is_empty() {
706 id.to_owned()
707 } else {
708 format!("{namespace}::{id}")
709 }
710}
711
712fn namespace_prefix(namespace: &str) -> String {
713 if namespace.is_empty() {
714 String::new()
715 } else {
716 format!("{namespace}::")
717 }
718}
719
720fn boundary_id_fragment(pin: &str) -> String {
721 pin.chars()
722 .map(|character| match character {
723 ':' | '@' | '/' | '\\' | ' ' => '_',
724 _ => character,
725 })
726 .collect()
727}
728
729fn subpatch_diagnostic(
730 code: &'static str,
731 message: String,
732 namespace: &str,
733 node: &GraphNodeCurrent,
734 patch_ref: Option<&str>,
735 depth: usize,
736 stack: &[String],
737) -> RuntimeDiagnostic {
738 subpatch_diagnostic_with_path(code, message, namespace, node, patch_ref, depth, stack)
739}
740
741fn subpatch_diagnostic_with_path(
742 code: &'static str,
743 message: String,
744 namespace: &str,
745 node: &GraphNodeCurrent,
746 patch_ref: Option<&str>,
747 depth: usize,
748 path: &[String],
749) -> RuntimeDiagnostic {
750 RuntimeDiagnostic::structured_error(
751 code,
752 message,
753 json!({
754 "nodeId": namespaced_id(namespace, &node.id),
755 "kind": node.kind.as_str(),
756 "patchRef": patch_ref,
757 "depth": depth,
758 "path": path,
759 }),
760 )
761}
762
763fn boundary_diagnostic(
764 code: &'static str,
765 message: String,
766 namespace: &str,
767 node_id: &str,
768 port_id: &str,
769 kind: BoundaryKind,
770) -> RuntimeDiagnostic {
771 RuntimeDiagnostic::structured_error(
772 code,
773 message,
774 json!({
775 "nodeId": namespaced_id(namespace, node_id),
776 "portId": port_id,
777 "boundary": match kind {
778 BoundaryKind::Inlet => "inlet",
779 BoundaryKind::Outlet => "outlet",
780 },
781 }),
782 )
783}
784
785pub fn validate_project_current(
786 graph: &GraphDocumentCurrent,
787 nodes: &[NodeDefinitionCurrent],
788) -> CurrentValidation {
789 let mut diagnostics = Vec::new();
790 let mut registry: HashMap<(&str, &str), &NodeDefinitionCurrent> = HashMap::new();
791
792 for definition in nodes {
793 if let Err(report) = skenion_contracts::validate_node_definition_v01(definition) {
794 diagnostics.extend(report.errors().iter().map(|error| {
795 contract_validation_diagnostic(
796 "node-definition",
797 "node-definition.invalid-contract",
798 error.message.clone(),
799 &definition.schema_version,
800 json!({ "nodeDefinitionId": definition.id }),
801 )
802 }));
803 }
804 registry.insert(
805 (definition.id.as_str(), definition.version.as_str()),
806 definition,
807 );
808 }
809
810 let graph_analysis = match skenion_contracts::validate_graph_document_v01(graph) {
811 Ok(analysis) => analysis,
812 Err(report) => {
813 diagnostics.extend(report.errors().iter().map(|error| {
814 contract_validation_diagnostic(
815 "graph",
816 "graph.invalid-contract",
817 error.message.clone(),
818 &graph.schema_version,
819 json!({ "graphId": graph.id }),
820 )
821 }));
822 skenion_contracts::analyze_graph_document_v01(graph)
823 }
824 };
825 diagnostics.extend(
826 graph_analysis
827 .diagnostics
828 .iter()
829 .filter(|diagnostic| diagnostic.severity == "warning")
830 .map(|diagnostic| {
831 let message = format!("{}: {}", diagnostic.code, diagnostic.message);
832 RuntimeDiagnostic::structured_warning(
833 diagnostic.code.clone(),
834 message,
835 json!({
836 "surface": "graph",
837 "graphId": graph.id,
838 "nodes": diagnostic.nodes,
839 "edges": diagnostic.edges,
840 }),
841 )
842 }),
843 );
844
845 for node in &graph.nodes {
846 match registry.get(&(node.kind.as_str(), node.kind_version.as_str())) {
847 Some(definition) => validate_node_snapshot_current(node, definition, &mut diagnostics),
848 None => diagnostics.push(RuntimeDiagnostic::structured_error(
849 "node-definition.missing",
850 format!(
851 "missing node definition: {}@{}",
852 node.kind, node.kind_version
853 ),
854 json!({
855 "surface": "node-definition",
856 "nodeId": node.id,
857 "kind": node.kind,
858 "kindVersion": node.kind_version,
859 }),
860 )),
861 }
862 }
863
864 if diagnostics
865 .iter()
866 .any(|diagnostic| diagnostic.severity == crate::DiagnosticSeverity::Error)
867 {
868 Err(diagnostics)
869 } else {
870 Ok((diagnostics, graph_analysis))
871 }
872}
873
874fn contract_validation_diagnostic(
875 surface: &'static str,
876 code: &'static str,
877 message: String,
878 received_schema_version: &str,
879 mut details: Value,
880) -> RuntimeDiagnostic {
881 let object = details
882 .as_object_mut()
883 .expect("contract validation diagnostic details should be an object");
884 object.insert("surface".to_owned(), json!(surface));
885 object.insert(
886 "expectedSchemaVersion".to_owned(),
887 json!(CURRENT_SCHEMA_VERSION),
888 );
889 object.insert(
890 "receivedSchemaVersion".to_owned(),
891 json!(received_schema_version),
892 );
893 RuntimeDiagnostic::structured_error(code, message, details)
894}
895
896pub fn schema_version_diagnostic(
897 surface: &'static str,
898 received_schema_version: Option<&str>,
899) -> Option<RuntimeDiagnostic> {
900 schema_version_diagnostic_with_details(surface, received_schema_version, json!({}))
901}
902
903fn schema_version_diagnostic_with_details(
904 surface: &'static str,
905 received_schema_version: Option<&str>,
906 mut details: Value,
907) -> Option<RuntimeDiagnostic> {
908 let object = details
909 .as_object_mut()
910 .expect("schema version diagnostic details should be an object");
911 object.insert("surface".to_owned(), json!(surface));
912 object.insert(
913 "expectedSchemaVersion".to_owned(),
914 json!(CURRENT_SCHEMA_VERSION),
915 );
916 object.insert(
917 "receivedSchemaVersion".to_owned(),
918 received_schema_version.map_or(Value::Null, Value::from),
919 );
920
921 match received_schema_version {
922 Some(CURRENT_SCHEMA_VERSION) => None,
923 Some(version) => Some(RuntimeDiagnostic::structured_error(
924 "project.unsupported-schema-version",
925 format!("unsupported {surface}.schemaVersion: {version}"),
926 details,
927 )),
928 None => Some(RuntimeDiagnostic::structured_error(
929 "project.missing-schema-version",
930 format!("missing {surface}.schemaVersion in project request"),
931 details,
932 )),
933 }
934}
935
936pub fn project_document_validation_diagnostics_current(
937 document: &ProjectDocumentCurrent,
938 report: &skenion_contracts::ValidationReportV01,
939) -> Vec<RuntimeDiagnostic> {
940 let mut diagnostics = Vec::new();
941 if let Some(diagnostic) =
942 schema_version_diagnostic("project", Some(document.schema_version.as_str()))
943 {
944 diagnostics.push(diagnostic);
945 }
946 if let Some(diagnostic) =
947 schema_version_diagnostic("graph", Some(document.graph.schema_version.as_str()))
948 {
949 diagnostics.push(diagnostic);
950 }
951 for patch in &document.patch_library {
952 if let Some(diagnostic) = schema_version_diagnostic_with_details(
953 "graph",
954 Some(patch.graph.schema_version.as_str()),
955 json!({ "patchId": patch.id }),
956 ) {
957 diagnostics.push(diagnostic);
958 }
959 }
960
961 diagnostics.extend(
962 report
963 .errors()
964 .iter()
965 .filter(|error| !is_schema_version_contract_error(&error.message))
966 .map(|error| {
967 RuntimeDiagnostic::structured_error(
968 "project.invalid-0.1",
969 error.message.clone(),
970 json!({ "projectId": document.id }),
971 )
972 }),
973 );
974 diagnostics
975}
976
977pub fn project_document_payload_schema_diagnostics(value: &Value) -> Vec<RuntimeDiagnostic> {
978 let mut diagnostics = Vec::new();
979 if let Some(diagnostic) = schema_version_diagnostic(
980 "project",
981 value.get("schemaVersion").and_then(Value::as_str),
982 ) {
983 diagnostics.push(diagnostic);
984 }
985 if let Some(diagnostic) = schema_version_diagnostic(
986 "graph",
987 value
988 .get("graph")
989 .and_then(|graph| graph.get("schemaVersion"))
990 .and_then(Value::as_str),
991 ) {
992 diagnostics.push(diagnostic);
993 }
994 if let Some(patches) = value.get("patchLibrary").and_then(Value::as_array) {
995 for patch in patches {
996 let patch_id = patch.get("id").and_then(Value::as_str);
997 if let Some(diagnostic) = schema_version_diagnostic_with_details(
998 "graph",
999 patch
1000 .get("graph")
1001 .and_then(|graph| graph.get("schemaVersion"))
1002 .and_then(Value::as_str),
1003 json!({ "patchId": patch_id }),
1004 ) {
1005 diagnostics.push(diagnostic);
1006 }
1007 }
1008 }
1009 diagnostics
1010}
1011
1012fn is_schema_version_contract_error(message: &str) -> bool {
1013 message.contains("expected schemaVersion 0.1.0, found")
1014}
1015
1016pub fn build_execution_plan_current(
1017 graph: &GraphDocumentCurrent,
1018 nodes: &[NodeDefinitionCurrent],
1019) -> Result<(crate::ExecutionPlan, Vec<RuntimeDiagnostic>), Vec<RuntimeDiagnostic>> {
1020 let (diagnostics, analysis) = validate_project_current(graph, nodes)?;
1021 let registry = nodes
1022 .iter()
1023 .map(|definition| {
1024 (
1025 (definition.id.as_str(), definition.version.as_str()),
1026 definition,
1027 )
1028 })
1029 .collect::<HashMap<_, _>>();
1030 let ordered_node_ids = topological_order_current(graph);
1031 let graph_nodes = graph
1032 .nodes
1033 .iter()
1034 .map(|node| (node.id.as_str(), node))
1035 .collect::<HashMap<_, _>>();
1036 let mut groups_by_model: BTreeMap<String, ExecutionGroup> = BTreeMap::new();
1037 let mut plan_nodes = Vec::new();
1038
1039 for (order, node_id) in ordered_node_ids.iter().enumerate() {
1040 let node = graph_nodes
1041 .get(node_id.as_str())
1042 .expect("current 0.1 planning order should only contain graph nodes");
1043 let definition = registry
1044 .get(&(node.kind.as_str(), node.kind_version.as_str()))
1045 .expect("current 0.1 validation should resolve definitions");
1046 let execution_model = map_execution_model_current(&definition.execution.model);
1047 plan_nodes.push(PlanNode {
1048 node_id: node.id.clone(),
1049 kind: node.kind.clone(),
1050 kind_version: node.kind_version.clone(),
1051 execution_model: execution_model.clone(),
1052 order,
1053 });
1054 groups_by_model
1055 .entry(format!("{execution_model:?}"))
1056 .or_insert_with(|| ExecutionGroup {
1057 execution_model: execution_model.clone(),
1058 node_ids: Vec::new(),
1059 })
1060 .node_ids
1061 .push(node.id.clone());
1062 }
1063
1064 Ok((
1065 crate::ExecutionPlan {
1066 graph_id: graph.id.clone(),
1067 graph_revision: graph.revision.clone(),
1068 nodes: plan_nodes,
1069 edges: graph
1070 .edges
1071 .iter()
1072 .map(|edge| plan_edge_current(graph, edge, &analysis))
1073 .collect(),
1074 groups: groups_by_model.into_values().collect(),
1075 },
1076 diagnostics,
1077 ))
1078}
1079
1080fn topological_order_current(graph: &GraphDocumentCurrent) -> Vec<String> {
1081 let mut indegree: HashMap<&str, usize> = graph
1082 .nodes
1083 .iter()
1084 .map(|node| (node.id.as_str(), 0usize))
1085 .collect();
1086 let mut adjacency: HashMap<&str, Vec<&str>> = HashMap::new();
1087
1088 for edge in graph.edges.iter().filter(|edge| !is_feedback_edge(edge)) {
1089 if indegree.contains_key(edge.source.node_id.as_str())
1090 && indegree.contains_key(edge.target.node_id.as_str())
1091 {
1092 adjacency
1093 .entry(edge.source.node_id.as_str())
1094 .or_default()
1095 .push(edge.target.node_id.as_str());
1096 *indegree
1097 .get_mut(edge.target.node_id.as_str())
1098 .expect("target node exists") += 1;
1099 }
1100 }
1101
1102 let mut queue = graph
1103 .nodes
1104 .iter()
1105 .filter(|node| indegree.get(node.id.as_str()).copied() == Some(0))
1106 .map(|node| node.id.as_str())
1107 .collect::<VecDeque<_>>();
1108 let mut ordered = Vec::new();
1109
1110 while let Some(node_id) = queue.pop_front() {
1111 ordered.push(node_id.to_owned());
1112 for next in adjacency.get(node_id).into_iter().flatten().copied() {
1113 let next_indegree = indegree.get_mut(next).expect("adjacent node exists");
1114 *next_indegree -= 1;
1115 if *next_indegree == 0 {
1116 queue.push_back(next);
1117 }
1118 }
1119 }
1120
1121 if ordered.len() == graph.nodes.len() {
1122 return ordered;
1123 }
1124
1125 let ordered_set = ordered.iter().cloned().collect::<HashSet<_>>();
1126 ordered.extend(
1127 graph
1128 .nodes
1129 .iter()
1130 .filter(|node| !ordered_set.contains(node.id.as_str()))
1131 .map(|node| node.id.clone()),
1132 );
1133 ordered
1134}
1135
1136fn is_feedback_edge(edge: &EdgeSpecCurrent) -> bool {
1137 edge.feedback
1138 .as_ref()
1139 .is_some_and(|feedback| feedback.enabled)
1140}
1141
1142fn validate_node_snapshot_current(
1143 node: &crate::GraphNodeCurrent,
1144 definition: &NodeDefinitionCurrent,
1145 diagnostics: &mut Vec<RuntimeDiagnostic>,
1146) {
1147 let definition_ports = definition
1148 .ports
1149 .iter()
1150 .map(|port| (port.id.as_str(), port))
1151 .collect::<HashMap<_, _>>();
1152 let snapshot_ports = node
1153 .ports
1154 .iter()
1155 .map(|port| (port.id.as_str(), port))
1156 .collect::<HashMap<_, _>>();
1157
1158 for definition_port in &definition.ports {
1159 if !snapshot_ports.contains_key(definition_port.id.as_str()) {
1160 diagnostics.push(node_snapshot_diagnostic(
1161 "node.port-snapshot.missing-manifest-port",
1162 format!(
1163 "port snapshot missing manifest port: {}.{}",
1164 node.id, definition_port.id
1165 ),
1166 node,
1167 definition_port.id.as_str(),
1168 ));
1169 }
1170 }
1171
1172 for snapshot_port in &node.ports {
1173 let Some(definition_port) = definition_ports.get(snapshot_port.id.as_str()) else {
1174 diagnostics.push(node_snapshot_diagnostic(
1175 "node.port-snapshot.unknown-manifest-port",
1176 format!(
1177 "port snapshot references missing manifest port: {}.{}",
1178 node.id, snapshot_port.id
1179 ),
1180 node,
1181 snapshot_port.id.as_str(),
1182 ));
1183 continue;
1184 };
1185
1186 if snapshot_port.direction != definition_port.direction {
1187 diagnostics.push(node_snapshot_diagnostic(
1188 "node.port-snapshot.direction-mismatch",
1189 format!(
1190 "port snapshot mismatch: {}.{} direction differs from definition",
1191 node.id, snapshot_port.id
1192 ),
1193 node,
1194 snapshot_port.id.as_str(),
1195 ));
1196 }
1197 if snapshot_port.port_type != definition_port.port_type {
1198 diagnostics.push(node_snapshot_diagnostic(
1199 "node.port-snapshot.type-mismatch",
1200 format!(
1201 "port snapshot mismatch: {}.{} type {} != definition type {}",
1202 node.id, snapshot_port.id, snapshot_port.port_type, definition_port.port_type
1203 ),
1204 node,
1205 snapshot_port.id.as_str(),
1206 ));
1207 }
1208 }
1209}
1210
1211fn node_snapshot_diagnostic(
1212 code: &'static str,
1213 message: String,
1214 node: &crate::GraphNodeCurrent,
1215 port_id: &str,
1216) -> RuntimeDiagnostic {
1217 RuntimeDiagnostic::structured_error(
1218 code,
1219 message,
1220 json!({
1221 "surface": "node-snapshot",
1222 "nodeId": node.id,
1223 "kind": node.kind,
1224 "kindVersion": node.kind_version,
1225 "portId": port_id,
1226 }),
1227 )
1228}
1229
1230fn plan_edge_current(
1231 graph: &GraphDocumentCurrent,
1232 edge: &EdgeSpecCurrent,
1233 analysis: &GraphValidationResultCurrent,
1234) -> PlanEdge {
1235 let source = find_port(graph, &edge.source.node_id, &edge.source.port_id)
1236 .expect("current 0.1 validation should resolve source port");
1237 let target = find_port(graph, &edge.target.node_id, &edge.target.port_id)
1238 .expect("current 0.1 validation should resolve target port");
1239
1240 PlanEdge {
1241 from_node: edge.source.node_id.clone(),
1242 from_port: edge.source.port_id.clone(),
1243 to_node: edge.target.node_id.clone(),
1244 to_port: edge.target.port_id.clone(),
1245 metadata: Some(PlanEdgeMetadata {
1246 resolved_type: Some(
1247 edge.resolved_type
1248 .clone()
1249 .unwrap_or_else(|| source.port_type.clone()),
1250 ),
1251 merge_policy: Some(merge_policy_label(target.merge_policy.as_ref())),
1252 fan_out_policy: Some(fan_out_policy_label(source.fan_out_policy.as_ref())),
1253 order: edge.order,
1254 feedback: edge.feedback.clone(),
1255 cycle_classification: cycle_classification_for_edge(edge, analysis),
1256 }),
1257 }
1258}
1259
1260fn find_port<'a>(
1261 graph: &'a GraphDocumentCurrent,
1262 node_id: &str,
1263 port_id: &str,
1264) -> Option<&'a crate::PortSpecCurrent> {
1265 graph
1266 .nodes
1267 .iter()
1268 .find(|node| node.id == node_id)?
1269 .ports
1270 .iter()
1271 .find(|port| port.id == port_id)
1272}
1273
1274fn cycle_classification_for_edge(
1275 edge: &EdgeSpecCurrent,
1276 analysis: &GraphValidationResultCurrent,
1277) -> Option<String> {
1278 analysis
1279 .cycles
1280 .iter()
1281 .find(|cycle| cycle.edges.iter().any(|edge_id| edge_id == &edge.id))
1282 .map(|cycle| cycle_validation_label(&cycle.classification).to_owned())
1283}
1284
1285fn cycle_validation_label(classification: &CycleValidationCurrent) -> &'static str {
1286 match classification {
1287 CycleValidationCurrent::NoCycle => "no-cycle",
1288 CycleValidationCurrent::ValidFeedback => "valid-feedback",
1289 CycleValidationCurrent::RiskyFeedback => "risky-feedback",
1290 CycleValidationCurrent::AmbiguousAlgebraicLoop => "ambiguous-algebraic-loop",
1291 CycleValidationCurrent::InvalidCycle => "invalid-cycle",
1292 }
1293}
1294
1295fn merge_policy_label(policy: Option<&MergePolicyCurrent>) -> String {
1296 match policy {
1297 Some(MergePolicyCurrent::OrderedEvents) => "ordered-events",
1298 Some(MergePolicyCurrent::Mix) => "mix",
1299 Some(MergePolicyCurrent::Array) => "array",
1300 Some(MergePolicyCurrent::Latest) => "latest",
1301 Some(MergePolicyCurrent::First) => "first",
1302 Some(MergePolicyCurrent::Custom) => "custom",
1303 Some(MergePolicyCurrent::Forbid) | None => "forbid",
1304 }
1305 .to_owned()
1306}
1307
1308fn fan_out_policy_label(policy: Option<&FanOutPolicyCurrent>) -> String {
1309 match policy {
1310 Some(FanOutPolicyCurrent::Forbid) => "forbid",
1311 Some(FanOutPolicyCurrent::Copy) => "copy",
1312 Some(FanOutPolicyCurrent::Share) => "share",
1313 Some(FanOutPolicyCurrent::Allow) | None => "allow",
1314 }
1315 .to_owned()
1316}
1317
1318fn map_execution_model_current(model: &ExecutionModelCurrent) -> ExecutionModel {
1319 match model {
1320 ExecutionModelCurrent::Event => ExecutionModel::Event,
1321 ExecutionModelCurrent::Value => ExecutionModel::Value,
1322 ExecutionModelCurrent::Frame => ExecutionModel::Frame,
1323 ExecutionModelCurrent::AudioBlock => ExecutionModel::AudioBlock,
1324 ExecutionModelCurrent::VideoFrame => ExecutionModel::VideoFrame,
1325 ExecutionModelCurrent::GpuPass => ExecutionModel::GpuPass,
1326 ExecutionModelCurrent::AsyncResource => ExecutionModel::AsyncResource,
1327 ExecutionModelCurrent::ScriptControl => ExecutionModel::ScriptControl,
1328 ExecutionModelCurrent::NativePlugin => ExecutionModel::NativePlugin,
1329 }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334 use serde_json::{Value, json};
1335
1336 use super::*;
1337 use crate::{
1338 DiagnosticSeverity, FeedbackBoundaryCurrent, PortDirectionCurrent, PortSpecCurrent,
1339 };
1340
1341 fn graph(value: Value) -> GraphDocumentCurrent {
1342 serde_json::from_value(value).expect("graph should parse")
1343 }
1344
1345 fn definition(value: Value) -> NodeDefinitionCurrent {
1346 serde_json::from_value(value).expect("definition should parse")
1347 }
1348
1349 fn clear_definition() -> NodeDefinitionCurrent {
1350 definition(json!({
1351 "schema": "skenion.node.definition",
1352 "schemaVersion": "0.1.0",
1353 "id": "render.clear-color",
1354 "version": "0.1.0",
1355 "displayName": "Clear Color",
1356 "category": "Render",
1357 "ports": [
1358 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1359 ],
1360 "execution": { "model": "gpu_pass", "clock": "frame" },
1361 "state": { "persistent": false },
1362 "permissions": [],
1363 "capabilities": []
1364 }))
1365 }
1366
1367 fn output_definition() -> NodeDefinitionCurrent {
1368 definition(json!({
1369 "schema": "skenion.node.definition",
1370 "schemaVersion": "0.1.0",
1371 "id": "render.output",
1372 "version": "0.1.0",
1373 "displayName": "Render Output",
1374 "category": "Render",
1375 "ports": [
1376 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true }
1377 ],
1378 "execution": { "model": "gpu_pass", "clock": "frame" },
1379 "state": { "persistent": false },
1380 "permissions": [],
1381 "capabilities": []
1382 }))
1383 }
1384
1385 fn pass_definition() -> NodeDefinitionCurrent {
1386 definition(json!({
1387 "schema": "skenion.node.definition",
1388 "schemaVersion": "0.1.0",
1389 "id": "test.pass",
1390 "version": "0.1.0",
1391 "displayName": "Pass",
1392 "category": "Test",
1393 "ports": [
1394 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true },
1395 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1396 ],
1397 "execution": { "model": "gpu_pass", "clock": "frame" },
1398 "state": { "persistent": false },
1399 "permissions": [],
1400 "capabilities": []
1401 }))
1402 }
1403
1404 fn render_graph() -> GraphDocumentCurrent {
1405 graph(json!({
1406 "schema": "skenion.graph",
1407 "schemaVersion": "0.1.0",
1408 "id": "render",
1409 "revision": "1",
1410 "nodes": [
1411 {
1412 "id": "clear",
1413 "kind": "render.clear-color",
1414 "kindVersion": "0.1.0",
1415 "params": {},
1416 "ports": [
1417 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1418 ]
1419 },
1420 {
1421 "id": "output",
1422 "kind": "render.output",
1423 "kindVersion": "0.1.0",
1424 "params": {},
1425 "ports": [
1426 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true }
1427 ]
1428 }
1429 ],
1430 "edges": [
1431 {
1432 "id": "edge_clear_output",
1433 "source": { "nodeId": "clear", "portId": "out" },
1434 "target": { "nodeId": "output", "portId": "in" },
1435 "resolvedType": "render.frame"
1436 }
1437 ]
1438 }))
1439 }
1440
1441 fn identity_patch() -> PatchDefinitionCurrent {
1442 serde_json::from_value(json!({
1443 "id": "identity",
1444 "revision": "1",
1445 "graph": {
1446 "schema": "skenion.graph",
1447 "schemaVersion": "0.1.0",
1448 "id": "identity-graph",
1449 "revision": "1",
1450 "nodes": [
1451 {
1452 "id": "patch_in",
1453 "kind": "core.inlet",
1454 "kindVersion": "0.1.0",
1455 "params": { "portId": "in", "label": "Input" },
1456 "ports": [
1457 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render", "description": "Frame entering the patch" }
1458 ]
1459 },
1460 {
1461 "id": "pass",
1462 "kind": "test.pass",
1463 "kindVersion": "0.1.0",
1464 "params": {},
1465 "ports": [
1466 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true },
1467 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1468 ]
1469 },
1470 {
1471 "id": "patch_out",
1472 "kind": "core.outlet",
1473 "kindVersion": "0.1.0",
1474 "params": { "portId": "out", "label": "Output" },
1475 "ports": [
1476 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true, "description": "Frame leaving the patch" }
1477 ]
1478 }
1479 ],
1480 "edges": [
1481 {
1482 "id": "edge_in_pass",
1483 "source": { "nodeId": "patch_in", "portId": "out" },
1484 "target": { "nodeId": "pass", "portId": "in" },
1485 "resolvedType": "render.frame"
1486 },
1487 {
1488 "id": "edge_pass_out",
1489 "source": { "nodeId": "pass", "portId": "out" },
1490 "target": { "nodeId": "patch_out", "portId": "in" },
1491 "resolvedType": "render.frame"
1492 }
1493 ]
1494 }
1495 }))
1496 .expect("patch definition should parse")
1497 }
1498
1499 fn subpatch_graph() -> GraphDocumentCurrent {
1500 graph(json!({
1501 "schema": "skenion.graph",
1502 "schemaVersion": "0.1.0",
1503 "id": "render-subpatch",
1504 "revision": "1",
1505 "nodes": [
1506 {
1507 "id": "clear",
1508 "kind": "render.clear-color",
1509 "kindVersion": "0.1.0",
1510 "params": {},
1511 "ports": [
1512 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1513 ]
1514 },
1515 {
1516 "id": "fx",
1517 "kind": "core.subpatch",
1518 "kindVersion": "0.1.0",
1519 "params": { "patchRef": "identity" },
1520 "ports": [
1521 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true },
1522 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1523 ]
1524 },
1525 {
1526 "id": "output",
1527 "kind": "render.output",
1528 "kindVersion": "0.1.0",
1529 "params": {},
1530 "ports": [
1531 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render", "required": true }
1532 ]
1533 }
1534 ],
1535 "edges": [
1536 {
1537 "id": "edge_clear_fx",
1538 "source": { "nodeId": "clear", "portId": "out" },
1539 "target": { "nodeId": "fx", "portId": "in" },
1540 "resolvedType": "render.frame"
1541 },
1542 {
1543 "id": "edge_fx_output",
1544 "source": { "nodeId": "fx", "portId": "out" },
1545 "target": { "nodeId": "output", "portId": "in" },
1546 "resolvedType": "render.frame"
1547 }
1548 ]
1549 }))
1550 }
1551
1552 fn project_document() -> ProjectDocumentCurrent {
1553 serde_json::from_value(json!({
1554 "schema": "skenion.project",
1555 "schemaVersion": "0.1.0",
1556 "id": "render-project",
1557 "revision": "1",
1558 "graph": subpatch_graph(),
1559 "viewState": {
1560 "schema": "skenion.view-state",
1561 "schemaVersion": "0.1.0",
1562 "canvas": { "nodes": {} }
1563 },
1564 "patchLibrary": [identity_patch()]
1565 }))
1566 .expect("project document should parse")
1567 }
1568
1569 #[test]
1570 fn validates_and_builds_current_plan_metadata() {
1571 let graph = render_graph();
1572 let nodes = vec![clear_definition(), output_definition()];
1573 let (warnings, analysis) =
1574 validate_project_current(&graph, &nodes).expect("project should validate");
1575 assert!(warnings.is_empty());
1576 assert!(analysis.cycles.is_empty());
1577
1578 let (plan, diagnostics) =
1579 build_execution_plan_current(&graph, &nodes).expect("plan should build");
1580 assert!(diagnostics.is_empty());
1581 assert_eq!(plan.graph_id, "render");
1582 assert_eq!(plan.nodes.len(), 2);
1583 assert_eq!(plan.groups.len(), 1);
1584 let metadata = plan.edges[0]
1585 .metadata
1586 .as_ref()
1587 .expect("metadata should exist");
1588 assert_eq!(metadata.resolved_type.as_deref(), Some("render.frame"));
1589 assert_eq!(metadata.merge_policy.as_deref(), Some("forbid"));
1590 assert_eq!(metadata.fan_out_policy.as_deref(), Some("allow"));
1591 assert_eq!(metadata.cycle_classification, None);
1592 }
1593
1594 #[test]
1595 fn records_merge_order_feedback_and_risky_warnings() {
1596 let mut graph = graph(json!({
1597 "schema": "skenion.graph",
1598 "schemaVersion": "0.1.0",
1599 "id": "feedback",
1600 "revision": "1",
1601 "nodes": [
1602 {
1603 "id": "node",
1604 "kind": "render.feedback-composite",
1605 "kindVersion": "0.1.0",
1606 "params": {},
1607 "ports": [
1608 { "id": "previous", "direction": "input", "type": "render.frame", "rate": "render" },
1609 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render", "fanOutPolicy": "copy" }
1610 ]
1611 }
1612 ],
1613 "edges": [
1614 {
1615 "id": "edge_feedback",
1616 "source": { "nodeId": "node", "portId": "out" },
1617 "target": { "nodeId": "node", "portId": "previous" },
1618 "order": 3,
1619 "feedback": { "enabled": true, "boundary": "render-frame", "intentional": true }
1620 }
1621 ]
1622 }));
1623 let definition = definition(json!({
1624 "schema": "skenion.node.definition",
1625 "schemaVersion": "0.1.0",
1626 "id": "render.feedback-composite",
1627 "version": "0.1.0",
1628 "displayName": "Feedback",
1629 "category": "Render",
1630 "ports": [
1631 { "id": "previous", "direction": "input", "type": "render.frame", "rate": "render" },
1632 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render", "fanOutPolicy": "copy" }
1633 ],
1634 "execution": { "model": "gpu_pass", "clock": "frame" },
1635 "state": { "persistent": false },
1636 "permissions": [],
1637 "capabilities": []
1638 }));
1639
1640 let (plan, diagnostics) =
1641 build_execution_plan_current(&graph, std::slice::from_ref(&definition))
1642 .expect("feedback should plan");
1643 assert!(diagnostics.is_empty());
1644 let metadata = plan.edges[0].metadata.as_ref().unwrap();
1645 assert_eq!(metadata.order, Some(3));
1646 assert_eq!(metadata.fan_out_policy.as_deref(), Some("copy"));
1647 assert_eq!(
1648 metadata.cycle_classification.as_deref(),
1649 Some("valid-feedback")
1650 );
1651 assert_eq!(
1652 metadata.feedback.as_ref().unwrap().boundary,
1653 FeedbackBoundaryCurrent::RenderFrame
1654 );
1655
1656 graph.edges[0].feedback.as_mut().unwrap().boundary = FeedbackBoundaryCurrent::SameTurn;
1657 let (_plan, diagnostics) = build_execution_plan_current(&graph, &[definition])
1658 .expect("risky feedback should plan");
1659 assert_eq!(diagnostics[0].severity, DiagnosticSeverity::Warning);
1660 assert!(diagnostics[0].message.contains("risky-feedback"));
1661 }
1662
1663 #[test]
1664 fn project_document_conversions_default_runtime_fields() {
1665 let document = project_document();
1666
1667 let request: ProjectRequestCurrent = document.clone().into();
1668 assert_eq!(request.graph.id, "render-subpatch");
1669 assert!(request.nodes.is_empty());
1670 assert_eq!(request.patch_library[0].id, "identity");
1671
1672 let run_request: RunProjectRequestCurrent = document.into();
1673 assert_eq!(run_request.graph.id, "render-subpatch");
1674 assert!(run_request.nodes.is_empty());
1675 assert_eq!(run_request.patch_library[0].id, "identity");
1676 assert_eq!(run_request.frames, None);
1677 }
1678
1679 #[test]
1680 fn expands_subpatches_before_current_validation_and_planning() {
1681 let request = ProjectRequestCurrent {
1682 document: None,
1683 graph: subpatch_graph(),
1684 nodes: vec![clear_definition(), output_definition(), pass_definition()],
1685 patch_library: vec![identity_patch()],
1686 view_state: None,
1687 };
1688
1689 let expanded = expand_project_graph_current(&request.graph, &request.patch_library)
1690 .expect("subpatch graph should expand");
1691 let node_ids = expanded
1692 .nodes
1693 .iter()
1694 .map(|node| node.id.as_str())
1695 .collect::<Vec<_>>();
1696 assert_eq!(node_ids, vec!["clear", "fx::pass", "output"]);
1697 assert!(expanded.edges.iter().any(|edge| {
1698 edge.source.node_id == "clear"
1699 && edge.source.port_id == "out"
1700 && edge.target.node_id == "fx::pass"
1701 && edge.target.port_id == "in"
1702 }));
1703 assert!(expanded.edges.iter().any(|edge| {
1704 edge.source.node_id == "fx::pass"
1705 && edge.source.port_id == "out"
1706 && edge.target.node_id == "output"
1707 && edge.target.port_id == "in"
1708 }));
1709
1710 let (diagnostics, _) =
1711 validate_project_request_current(&request).expect("expanded project should validate");
1712 assert!(diagnostics.is_empty());
1713 let (plan, diagnostics) =
1714 build_execution_plan_request_current(&request).expect("expanded project should plan");
1715 assert!(diagnostics.is_empty());
1716 assert_eq!(
1717 plan.nodes
1718 .iter()
1719 .map(|node| node.node_id.as_str())
1720 .collect::<Vec<_>>(),
1721 vec!["clear", "fx::pass", "output"]
1722 );
1723 }
1724
1725 #[test]
1726 fn current_plan_sorts_expanded_nodes_by_dependency_order() {
1727 let mut graph = subpatch_graph();
1728 graph.nodes.reverse();
1729 let request = ProjectRequestCurrent {
1730 document: None,
1731 graph,
1732 nodes: vec![clear_definition(), output_definition(), pass_definition()],
1733 patch_library: vec![identity_patch()],
1734 view_state: None,
1735 };
1736
1737 let expanded = expand_project_graph_current(&request.graph, &request.patch_library)
1738 .expect("subpatch graph should expand");
1739 assert_eq!(
1740 expanded
1741 .nodes
1742 .iter()
1743 .map(|node| node.id.as_str())
1744 .collect::<Vec<_>>(),
1745 vec!["output", "fx::pass", "clear"]
1746 );
1747
1748 let (plan, diagnostics) =
1749 build_execution_plan_request_current(&request).expect("expanded project should plan");
1750
1751 assert!(diagnostics.is_empty());
1752 assert_eq!(
1753 plan.nodes
1754 .iter()
1755 .map(|node| node.node_id.as_str())
1756 .collect::<Vec<_>>(),
1757 vec!["clear", "fx::pass", "output"]
1758 );
1759 assert_eq!(
1760 plan.nodes.iter().map(|node| node.order).collect::<Vec<_>>(),
1761 vec![0, 1, 2]
1762 );
1763 }
1764
1765 #[test]
1766 fn contracts_boundary_edges_and_filters_boundary_only_edges() {
1767 let base_edge = render_graph().edges[0].clone();
1768 let endpoint = EdgeEndpointCurrent {
1769 node_id: "same".to_owned(),
1770 port_id: "out".to_owned(),
1771 };
1772 let self_loop_edges = vec![
1773 ExpansionEdge {
1774 edge: base_edge.clone(),
1775 source: ExpansionEndpoint::Node(endpoint.clone()),
1776 target: ExpansionEndpoint::Boundary("pin".to_owned()),
1777 },
1778 ExpansionEdge {
1779 edge: base_edge.clone(),
1780 source: ExpansionEndpoint::Boundary("pin".to_owned()),
1781 target: ExpansionEndpoint::Node(endpoint.clone()),
1782 },
1783 ];
1784
1785 let contracted = contract_boundary_edges(
1786 self_loop_edges,
1787 std::collections::HashSet::from(["pin".to_owned()]),
1788 );
1789 assert!(contracted.is_empty());
1790
1791 let mut source_edge = base_edge.clone();
1792 source_edge.id = "source_edge".to_owned();
1793 source_edge.resolved_type = Some("render.frame".to_owned());
1794 let mut target_edge = base_edge.clone();
1795 target_edge.id = "target_edge".to_owned();
1796 target_edge.resolved_type = None;
1797 let merged = contract_boundary_edges(
1798 vec![
1799 ExpansionEdge {
1800 edge: source_edge,
1801 source: ExpansionEndpoint::Node(EdgeEndpointCurrent {
1802 node_id: "source".to_owned(),
1803 port_id: "out".to_owned(),
1804 }),
1805 target: ExpansionEndpoint::Boundary("fx::@inlet::in".to_owned()),
1806 },
1807 ExpansionEdge {
1808 edge: target_edge,
1809 source: ExpansionEndpoint::Boundary("fx::@inlet::in".to_owned()),
1810 target: ExpansionEndpoint::Node(EdgeEndpointCurrent {
1811 node_id: "target".to_owned(),
1812 port_id: "in".to_owned(),
1813 }),
1814 },
1815 ],
1816 std::collections::HashSet::from(["fx::@inlet::in".to_owned()]),
1817 );
1818 assert_eq!(merged.len(), 1);
1819 assert_eq!(merged[0].resolved_type.as_deref(), Some("render.frame"));
1820 assert!(merged[0].id.contains("fx___inlet__in"));
1821
1822 assert!(
1823 expansion_edge_to_real_edge(ExpansionEdge {
1824 edge: base_edge.clone(),
1825 source: ExpansionEndpoint::Boundary("pin".to_owned()),
1826 target: ExpansionEndpoint::Node(endpoint.clone()),
1827 })
1828 .is_none()
1829 );
1830 assert!(
1831 expansion_edge_to_real_edge(ExpansionEdge {
1832 edge: base_edge,
1833 source: ExpansionEndpoint::Node(endpoint),
1834 target: ExpansionEndpoint::Boundary("pin".to_owned()),
1835 })
1836 .is_none()
1837 );
1838 }
1839
1840 #[test]
1841 fn reports_missing_ref_depth_and_duplicate_patch_diagnostics() {
1842 let duplicate = ProjectRequestCurrent {
1843 document: None,
1844 graph: render_graph(),
1845 nodes: vec![clear_definition(), output_definition()],
1846 patch_library: vec![identity_patch(), identity_patch()],
1847 view_state: None,
1848 };
1849 let duplicate_diagnostics = validate_project_request_current(&duplicate)
1850 .expect_err("duplicate patch ids should fail");
1851 assert_eq!(
1852 duplicate_diagnostics[0].code.as_deref(),
1853 Some("subpatch.duplicate-patch-id")
1854 );
1855
1856 let missing_ref = graph(json!({
1857 "schema": "skenion.graph",
1858 "schemaVersion": "0.1.0",
1859 "id": "missing-ref",
1860 "revision": "1",
1861 "nodes": [
1862 {
1863 "id": "fx",
1864 "kind": "core.subpatch",
1865 "kindVersion": "0.1.0",
1866 "params": {},
1867 "ports": []
1868 }
1869 ],
1870 "edges": []
1871 }));
1872 let missing_ref_diagnostics =
1873 expand_project_graph_current(&missing_ref, &[]).expect_err("missing ref should fail");
1874 assert_eq!(
1875 missing_ref_diagnostics[0].code.as_deref(),
1876 Some("subpatch.missing-ref")
1877 );
1878 assert_eq!(
1879 missing_ref_diagnostics[0].details.as_ref().unwrap()["patchRef"],
1880 Value::Null
1881 );
1882
1883 let mut patch_library = Vec::new();
1884 for index in 0..=15 {
1885 patch_library.push(
1886 serde_json::from_value(json!({
1887 "id": format!("p{index}"),
1888 "revision": "1",
1889 "graph": {
1890 "schema": "skenion.graph",
1891 "schemaVersion": "0.1.0",
1892 "id": format!("p{index}-graph"),
1893 "revision": "1",
1894 "nodes": [
1895 {
1896 "id": "next",
1897 "kind": "core.subpatch",
1898 "kindVersion": "0.1.0",
1899 "params": { "patchRef": format!("p{}", index + 1) },
1900 "ports": []
1901 }
1902 ],
1903 "edges": []
1904 }
1905 }))
1906 .expect("patch should parse"),
1907 );
1908 }
1909 let depth_root = graph(json!({
1910 "schema": "skenion.graph",
1911 "schemaVersion": "0.1.0",
1912 "id": "depth-root",
1913 "revision": "1",
1914 "nodes": [
1915 {
1916 "id": "root",
1917 "kind": "core.subpatch",
1918 "kindVersion": "0.1.0",
1919 "params": { "patchRef": "p0" },
1920 "ports": []
1921 }
1922 ],
1923 "edges": []
1924 }));
1925 let depth_diagnostics = expand_project_graph_current(&depth_root, &patch_library)
1926 .expect_err("depth should fail");
1927 assert_eq!(
1928 depth_diagnostics[0].code.as_deref(),
1929 Some("subpatch.depth-exceeded")
1930 );
1931 assert_eq!(depth_diagnostics[0].details.as_ref().unwrap()["depth"], 17);
1932 }
1933
1934 #[test]
1935 fn parses_subpatch_aliases_and_reports_missing_boundaries() {
1936 assert_eq!(
1937 parse_subpatch_object_text("p identity").as_deref(),
1938 Some("identity")
1939 );
1940 assert_eq!(
1941 parse_subpatch_object_text("core.subpatch identity").as_deref(),
1942 Some("identity")
1943 );
1944 assert_eq!(parse_subpatch_object_text("object identity"), None);
1945 assert_eq!(namespace_prefix(""), "");
1946
1947 let params = serde_json::Map::from_iter([
1948 ("patchId".to_owned(), json!(42)),
1949 ("empty".to_owned(), json!("")),
1950 ("enabled".to_owned(), json!(true)),
1951 ]);
1952 assert_eq!(string_param(¶ms, "patchId").as_deref(), Some("42"));
1953 assert_eq!(string_param(¶ms, "empty"), None);
1954 assert_eq!(string_param(¶ms, "enabled"), None);
1955
1956 let fallback_boundary = graph(json!({
1957 "schema": "skenion.graph",
1958 "schemaVersion": "0.1.0",
1959 "id": "fallback-boundary",
1960 "revision": "1",
1961 "nodes": [
1962 {
1963 "id": "plain_inlet",
1964 "kind": "core.inlet",
1965 "kindVersion": "0.1.0",
1966 "params": {},
1967 "ports": []
1968 }
1969 ],
1970 "edges": []
1971 }));
1972 assert_eq!(boundary_key(&fallback_boundary.nodes[0]), "plain_inlet");
1973
1974 let duplicate_inlet_patch: PatchDefinitionCurrent = serde_json::from_value(json!({
1975 "id": "alias-patch",
1976 "revision": "1",
1977 "graph": {
1978 "schema": "skenion.graph",
1979 "schemaVersion": "0.1.0",
1980 "id": "alias-patch-graph",
1981 "revision": "1",
1982 "nodes": [
1983 {
1984 "id": "in_a",
1985 "kind": "core.inlet",
1986 "kindVersion": "0.1.0",
1987 "params": { "portId": "in_a", "label": "shared" },
1988 "ports": [
1989 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1990 ]
1991 },
1992 {
1993 "id": "in_b",
1994 "kind": "core.inlet",
1995 "kindVersion": "0.1.0",
1996 "params": { "portId": "in_b", "label": "shared" },
1997 "ports": [
1998 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
1999 ]
2000 }
2001 ],
2002 "edges": []
2003 }
2004 }))
2005 .expect("patch should parse");
2006 let mut boundary_pins = std::collections::HashSet::new();
2007 let mut aliases = std::collections::HashMap::new();
2008 let first_pin = register_boundary_node(
2009 &duplicate_inlet_patch.graph.nodes[0],
2010 "fx",
2011 BoundaryKind::Inlet,
2012 &mut boundary_pins,
2013 &mut aliases,
2014 );
2015 let second_pin = register_boundary_node(
2016 &duplicate_inlet_patch.graph.nodes[0],
2017 "fx",
2018 BoundaryKind::Inlet,
2019 &mut boundary_pins,
2020 &mut aliases,
2021 );
2022 assert_eq!(first_pin, second_pin);
2023
2024 let root = graph(json!({
2025 "schema": "skenion.graph",
2026 "schemaVersion": "0.1.0",
2027 "id": "alias-root",
2028 "revision": "1",
2029 "nodes": [
2030 {
2031 "id": "clear",
2032 "kind": "render.clear-color",
2033 "kindVersion": "0.1.0",
2034 "params": {},
2035 "ports": [
2036 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
2037 ]
2038 },
2039 {
2040 "id": "fx",
2041 "kind": "p",
2042 "kindVersion": "0.1.0",
2043 "params": { "objectText": "p alias-patch" },
2044 "ports": [
2045 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render" },
2046 { "id": "out", "direction": "output", "type": "render.frame", "rate": "render" }
2047 ]
2048 },
2049 {
2050 "id": "output",
2051 "kind": "render.output",
2052 "kindVersion": "0.1.0",
2053 "params": {},
2054 "ports": [
2055 { "id": "in", "direction": "input", "type": "render.frame", "rate": "render" }
2056 ]
2057 }
2058 ],
2059 "edges": [
2060 {
2061 "id": "edge_clear_fx",
2062 "source": { "nodeId": "clear", "portId": "out" },
2063 "target": { "nodeId": "fx", "portId": "shared" }
2064 },
2065 {
2066 "id": "edge_fx_output",
2067 "source": { "nodeId": "fx", "portId": "out" },
2068 "target": { "nodeId": "output", "portId": "in" }
2069 }
2070 ]
2071 }));
2072 let diagnostics = expand_project_graph_current(&root, &[duplicate_inlet_patch])
2073 .expect_err("boundaries fail");
2074 let codes = diagnostics
2075 .iter()
2076 .map(|diagnostic| diagnostic.code.as_deref())
2077 .collect::<Vec<_>>();
2078 assert!(codes.contains(&Some("subpatch.missing-inlet")));
2079 assert!(codes.contains(&Some("subpatch.missing-outlet")));
2080 }
2081
2082 #[test]
2083 fn reports_missing_recursive_and_invalid_patch_library_diagnostics() {
2084 let missing = ProjectRequestCurrent {
2085 document: None,
2086 graph: subpatch_graph(),
2087 nodes: vec![clear_definition(), output_definition(), pass_definition()],
2088 patch_library: Vec::new(),
2089 view_state: None,
2090 };
2091 let missing_diagnostics =
2092 validate_project_request_current(&missing).expect_err("missing patch should fail");
2093 assert_eq!(
2094 missing_diagnostics[0].code.as_deref(),
2095 Some("subpatch.missing-patch")
2096 );
2097
2098 let recursive_patch: PatchDefinitionCurrent = serde_json::from_value(json!({
2099 "id": "recursive",
2100 "revision": "1",
2101 "graph": {
2102 "schema": "skenion.graph",
2103 "schemaVersion": "0.1.0",
2104 "id": "recursive-graph",
2105 "revision": "1",
2106 "nodes": [
2107 {
2108 "id": "self",
2109 "kind": "core.subpatch",
2110 "kindVersion": "0.1.0",
2111 "params": { "patchRef": "recursive" },
2112 "ports": []
2113 }
2114 ],
2115 "edges": []
2116 }
2117 }))
2118 .expect("recursive patch should parse");
2119 let recursive = ProjectRequestCurrent {
2120 document: None,
2121 graph: graph(json!({
2122 "schema": "skenion.graph",
2123 "schemaVersion": "0.1.0",
2124 "id": "recursive-root",
2125 "revision": "1",
2126 "nodes": [
2127 {
2128 "id": "root",
2129 "kind": "core.subpatch",
2130 "kindVersion": "0.1.0",
2131 "params": { "patchRef": "recursive" },
2132 "ports": []
2133 }
2134 ],
2135 "edges": []
2136 })),
2137 nodes: Vec::new(),
2138 patch_library: vec![recursive_patch],
2139 view_state: None,
2140 };
2141 let recursive_diagnostics =
2142 validate_project_request_current(&recursive).expect_err("recursive patch should fail");
2143 assert_eq!(
2144 recursive_diagnostics[0].code.as_deref(),
2145 Some("subpatch.recursion")
2146 );
2147
2148 let mut duplicate_boundary = identity_patch();
2149 duplicate_boundary.graph.nodes[2].params["portId"] = json!("in");
2150 let invalid = ProjectRequestCurrent {
2151 document: None,
2152 graph: render_graph(),
2153 nodes: vec![clear_definition(), output_definition()],
2154 patch_library: vec![duplicate_boundary],
2155 view_state: None,
2156 };
2157 let invalid_diagnostics =
2158 validate_project_request_current(&invalid).expect_err("invalid patch should fail");
2159 assert_eq!(
2160 invalid_diagnostics[0].code.as_deref(),
2161 Some("subpatch.invalid-patch-definition")
2162 );
2163 }
2164
2165 fn assert_patch_graph_schema_diagnostic(
2166 diagnostics: &[RuntimeDiagnostic],
2167 expected_code: &str,
2168 expected_received_schema_version: &str,
2169 ) {
2170 let diagnostic = diagnostics
2171 .iter()
2172 .find(|diagnostic| diagnostic.code.as_deref() == Some(expected_code))
2173 .unwrap_or_else(|| panic!("missing {expected_code} diagnostic: {diagnostics:#?}"));
2174 let details = diagnostic
2175 .details
2176 .as_ref()
2177 .expect("schema diagnostic should include details");
2178
2179 assert_eq!(details["surface"], "graph");
2180 assert_eq!(details["patchId"], "identity");
2181 assert_eq!(details["expectedSchemaVersion"], "0.1.0");
2182 assert_eq!(
2183 details["receivedSchemaVersion"],
2184 expected_received_schema_version
2185 );
2186 assert!(
2187 diagnostics.iter().all(|diagnostic| {
2188 diagnostic.code.as_deref() != Some("subpatch.invalid-patch-definition")
2189 || !diagnostic.message.contains("schemaVersion")
2190 }),
2191 "patch graph schemaVersion should not also be reported as generic patch contract failure: {diagnostics:#?}"
2192 );
2193 }
2194
2195 #[test]
2196 fn direct_requests_report_structured_patch_graph_schema_versions() {
2197 let schema_version = "9.9.9";
2198 let expected_code = "project.unsupported-schema-version";
2199 let mut patch = identity_patch();
2200 patch.graph.schema_version = schema_version.to_owned();
2201 let request = ProjectRequestCurrent {
2202 document: None,
2203 graph: render_graph(),
2204 nodes: vec![clear_definition(), output_definition(), pass_definition()],
2205 patch_library: vec![patch],
2206 view_state: None,
2207 };
2208
2209 let validation_diagnostics = validate_project_request_current(&request)
2210 .expect_err("patch graph schema mismatch should fail request validation");
2211 assert_patch_graph_schema_diagnostic(
2212 &validation_diagnostics,
2213 expected_code,
2214 schema_version,
2215 );
2216
2217 let planning_diagnostics = build_execution_plan_request_current(&request)
2218 .expect_err("patch graph schema mismatch should fail request planning");
2219 assert_patch_graph_schema_diagnostic(&planning_diagnostics, expected_code, schema_version);
2220 }
2221
2222 #[test]
2223 fn rejects_invalid_graph_definitions_and_snapshots() {
2224 let graph = render_graph();
2225 let missing = validate_project_current(&graph, &[]).expect_err("missing definitions fail");
2226 assert_eq!(missing[0].code.as_deref(), Some("node-definition.missing"));
2227 assert_eq!(
2228 missing[0].details.as_ref().unwrap()["surface"],
2229 "node-definition"
2230 );
2231
2232 let mut unsupported_graph = render_graph();
2233 unsupported_graph.schema_version = "9.9.9".to_owned();
2234 let unsupported_graph_result = validate_project_current(
2235 &unsupported_graph,
2236 &[clear_definition(), output_definition()],
2237 )
2238 .expect_err("unsupported graph schema should fail");
2239 assert_eq!(
2240 unsupported_graph_result[0].code.as_deref(),
2241 Some("graph.invalid-contract")
2242 );
2243 assert_eq!(
2244 unsupported_graph_result[0].details.as_ref().unwrap()["surface"],
2245 "graph"
2246 );
2247 assert_eq!(
2248 unsupported_graph_result[0].details.as_ref().unwrap()["expectedSchemaVersion"],
2249 "0.1.0"
2250 );
2251 assert_eq!(
2252 unsupported_graph_result[0].details.as_ref().unwrap()["receivedSchemaVersion"],
2253 "9.9.9"
2254 );
2255
2256 let mut invalid_definition = clear_definition();
2257 invalid_definition.permissions.push("network".to_owned());
2258 let invalid_definition_result =
2259 validate_project_current(&graph, &[invalid_definition, output_definition()])
2260 .expect_err("invalid definition should fail");
2261 let invalid_definition_diagnostic = invalid_definition_result
2262 .iter()
2263 .find(|diagnostic| {
2264 diagnostic
2265 .message
2266 .contains("unsupported permission: network")
2267 })
2268 .expect("unsupported permission should be reported");
2269 assert_eq!(
2270 invalid_definition_diagnostic.code.as_deref(),
2271 Some("node-definition.invalid-contract")
2272 );
2273 assert_eq!(
2274 invalid_definition_diagnostic.details.as_ref().unwrap()["surface"],
2275 "node-definition"
2276 );
2277 assert_eq!(
2278 invalid_definition_diagnostic.details.as_ref().unwrap()["expectedSchemaVersion"],
2279 "0.1.0"
2280 );
2281 assert_eq!(
2282 invalid_definition_diagnostic.details.as_ref().unwrap()["receivedSchemaVersion"],
2283 "0.1.0"
2284 );
2285
2286 let mut mismatch = render_graph();
2287 mismatch.nodes[0].ports.clear();
2288 mismatch.nodes[1].ports[0].direction = PortDirectionCurrent::Output;
2289 mismatch.nodes[1].ports[0].port_type = "value.number".to_owned();
2290 mismatch.nodes[1].ports.push(PortSpecCurrent {
2291 id: "extra".to_owned(),
2292 direction: PortDirectionCurrent::Input,
2293 port_type: "render.frame".to_owned(),
2294 label: None,
2295 rate: None,
2296 accepts: None,
2297 min_connections: None,
2298 max_connections: None,
2299 merge_policy: None,
2300 fan_out_policy: None,
2301 trigger_mode: None,
2302 default_value: None,
2303 latch: None,
2304 required: None,
2305 style_key: None,
2306 group: None,
2307 description: None,
2308 });
2309 let mismatch_result =
2310 validate_project_current(&mismatch, &[clear_definition(), output_definition()])
2311 .expect_err("snapshot mismatch should fail");
2312 let messages = mismatch_result
2313 .iter()
2314 .map(|diagnostic| diagnostic.message.as_str())
2315 .collect::<Vec<_>>()
2316 .join("\n");
2317 assert!(
2318 mismatch_result
2319 .iter()
2320 .all(|diagnostic| diagnostic.code.is_some()),
2321 "current 0.1 project diagnostics should be structured"
2322 );
2323 assert!(messages.contains("missing manifest port"));
2324 assert!(messages.contains("direction differs from definition"));
2325 assert!(messages.contains("type value.number"));
2326 assert!(messages.contains("missing source port"));
2327 assert!(messages.contains("missing manifest port: output.extra"));
2328 }
2329
2330 #[test]
2331 fn labels_all_current_policy_and_execution_variants() {
2332 for (policy, expected) in [
2333 (Some(MergePolicyCurrent::Forbid), "forbid"),
2334 (Some(MergePolicyCurrent::OrderedEvents), "ordered-events"),
2335 (Some(MergePolicyCurrent::Mix), "mix"),
2336 (Some(MergePolicyCurrent::Array), "array"),
2337 (Some(MergePolicyCurrent::Latest), "latest"),
2338 (Some(MergePolicyCurrent::First), "first"),
2339 (Some(MergePolicyCurrent::Custom), "custom"),
2340 (None, "forbid"),
2341 ] {
2342 assert_eq!(merge_policy_label(policy.as_ref()), expected);
2343 }
2344
2345 for (policy, expected) in [
2346 (Some(FanOutPolicyCurrent::Allow), "allow"),
2347 (Some(FanOutPolicyCurrent::Forbid), "forbid"),
2348 (Some(FanOutPolicyCurrent::Copy), "copy"),
2349 (Some(FanOutPolicyCurrent::Share), "share"),
2350 (None, "allow"),
2351 ] {
2352 assert_eq!(fan_out_policy_label(policy.as_ref()), expected);
2353 }
2354
2355 for (classification, expected) in [
2356 (CycleValidationCurrent::NoCycle, "no-cycle"),
2357 (CycleValidationCurrent::ValidFeedback, "valid-feedback"),
2358 (CycleValidationCurrent::RiskyFeedback, "risky-feedback"),
2359 (
2360 CycleValidationCurrent::AmbiguousAlgebraicLoop,
2361 "ambiguous-algebraic-loop",
2362 ),
2363 (CycleValidationCurrent::InvalidCycle, "invalid-cycle"),
2364 ] {
2365 assert_eq!(cycle_validation_label(&classification), expected);
2366 }
2367
2368 for (model, expected) in [
2369 (ExecutionModelCurrent::Event, ExecutionModel::Event),
2370 (ExecutionModelCurrent::Value, ExecutionModel::Value),
2371 (ExecutionModelCurrent::Frame, ExecutionModel::Frame),
2372 (
2373 ExecutionModelCurrent::AudioBlock,
2374 ExecutionModel::AudioBlock,
2375 ),
2376 (
2377 ExecutionModelCurrent::VideoFrame,
2378 ExecutionModel::VideoFrame,
2379 ),
2380 (ExecutionModelCurrent::GpuPass, ExecutionModel::GpuPass),
2381 (
2382 ExecutionModelCurrent::AsyncResource,
2383 ExecutionModel::AsyncResource,
2384 ),
2385 (
2386 ExecutionModelCurrent::ScriptControl,
2387 ExecutionModel::ScriptControl,
2388 ),
2389 (
2390 ExecutionModelCurrent::NativePlugin,
2391 ExecutionModel::NativePlugin,
2392 ),
2393 ] {
2394 assert_eq!(map_execution_model_current(&model), expected);
2395 }
2396 }
2397}