1use std::collections::{HashMap, HashSet, VecDeque};
13use std::fmt;
14use std::hash::{Hash, Hasher};
15use std::sync::Arc;
16
17use crate::dsl::{NodeDoc, NodePolicy, Workflow};
18use crate::node::{ConfigError, Node, NodeRole, Registry};
19
20pub const SOURCE_HANDLE: &str = "source";
22pub const FAIL_BRANCH: &str = "fail-branch";
24
25pub type NodeIx = usize;
27pub type EdgeIx = usize;
29
30pub struct GraphNode {
32 pub id: Arc<str>,
33 pub kind: Arc<str>,
35 pub title: Arc<str>,
36 pub parent: Option<NodeIx>,
38 pub policy: NodePolicy,
39 pub role: NodeRole,
40 pub node: Arc<dyn Node>,
41 pub doc: NodeDoc,
43}
44
45impl fmt::Debug for GraphNode {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.debug_struct("GraphNode").field("id", &self.id).field("kind", &self.kind).field("role", &self.role).finish()
48 }
49}
50
51#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct GraphEdge {
54 pub id: Arc<str>,
55 pub source: NodeIx,
56 pub target: NodeIx,
57 pub handle: Arc<str>,
58}
59
60#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct Scope {
63 pub owner: Option<NodeIx>,
65 pub entry: NodeIx,
67 pub nodes: Vec<NodeIx>,
69}
70
71#[derive(Debug, thiserror::Error)]
73#[non_exhaustive]
74pub enum GraphError {
75 #[error(transparent)]
76 Config(#[from] ConfigError),
77 #[error("duplicate node id `{0}`")]
78 DuplicateNode(String),
79 #[error("duplicate edge id `{0}`")]
80 DuplicateEdge(String),
81 #[error("edge `{edge}` references unknown node `{node}`{}", did_you_mean(.suggestion))]
82 MissingNode { edge: String, node: String, suggestion: Option<String> },
83 #[error("node `{node}` references unknown parent `{parent}`{}", did_you_mean(.suggestion))]
84 MissingParent { node: String, parent: String, suggestion: Option<String> },
85 #[error("node `{0}` has a parent that is not a container node")]
86 ParentNotContainer(String),
87 #[error("container nesting cycle at node `{0}`")]
88 ParentCycle(String),
89 #[error("edge `{edge}` crosses scopes (`{source_node}` -> `{target}`)")]
90 CrossScopeEdge { edge: String, source_node: String, target: String },
91 #[error("cycle detected in scope `{scope}` involving node `{node}`")]
92 Cycle { scope: String, node: String },
93 #[error("scope `{scope}` has no entry node")]
94 NoEntry { scope: String },
95 #[error("scope `{scope}` has multiple entry nodes: {nodes:?}")]
96 MultipleEntries { scope: String, nodes: Vec<String> },
97 #[error("graph has no nodes")]
98 Empty,
99 #[error("workflow cannot be serialized: {0}")]
100 Unserializable(String),
101 #[error("invalid node id `{id}`: {reason}")]
102 InvalidNodeId { id: String, reason: String },
103 #[error(
104 "node `{node}` references `{selector}`, but no node or variable namespace `{namespace}` exists{}",
105 did_you_mean(.suggestion)
106 )]
107 UnknownReference { node: String, selector: String, namespace: String, suggestion: Option<String> },
108 #[error("node `{node}`: {message}")]
111 InvalidField { node: String, path: String, message: String },
112 #[error("edge `{edge}`: {message}")]
114 UnknownHandle { edge: String, message: String },
115}
116
117use crate::validate::did_you_mean;
118
119pub(crate) const RESERVED_NAMESPACES: &[&str] = &[crate::pool::SYS, crate::pool::ENV, crate::pool::CONVERSATION];
121
122pub(crate) fn validate_node_id(id: &str) -> Result<(), GraphError> {
123 let reason = if id.is_empty() {
124 Some("must not be empty")
125 } else if RESERVED_NAMESPACES.contains(&id) {
126 Some("is a reserved variable namespace")
127 } else if id.contains('.') {
128 Some("must not contain `.` (it separates selector parts)")
129 } else if id.chars().any(char::is_whitespace) {
130 Some("must not contain whitespace")
131 } else {
132 None
133 };
134 match reason {
135 Some(reason) => Err(GraphError::InvalidNodeId { id: id.to_owned(), reason: reason.to_owned() }),
136 None => Ok(()),
137 }
138}
139
140pub struct Graph {
142 nodes: Vec<GraphNode>,
143 edges: Vec<GraphEdge>,
144 index: HashMap<Arc<str>, NodeIx>,
145 outgoing: Vec<Vec<EdgeIx>>,
146 incoming: Vec<Vec<EdgeIx>>,
147 scopes: HashMap<Option<NodeIx>, Scope>,
148 warnings: Vec<String>,
149 fingerprint: std::sync::OnceLock<String>,
152 workflow: Workflow,
153}
154
155impl fmt::Debug for Graph {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.debug_struct("Graph")
158 .field("nodes", &self.nodes.len())
159 .field("edges", &self.edges.len())
160 .field("fingerprint", &self.fingerprint.get())
161 .finish()
162 }
163}
164
165impl Graph {
166 pub fn build(workflow: Workflow, registry: &Registry) -> Result<Self, GraphError> {
168 Self::build_inner(workflow, registry, None)
169 }
170
171 pub(crate) fn build_checked(
177 workflow: Workflow,
178 registry: &Registry,
179 checked: Vec<Arc<dyn Node>>,
180 ) -> Result<Self, GraphError> {
181 Self::build_inner(workflow, registry, Some(checked))
182 }
183
184 fn build_inner(
185 workflow: Workflow,
186 registry: &Registry,
187 checked: Option<Vec<Arc<dyn Node>>>,
188 ) -> Result<Self, GraphError> {
189 let docs = &workflow.graph.nodes;
190 let mut checked = checked.filter(|nodes| nodes.len() == docs.len()).map(Vec::into_iter);
192 if docs.is_empty() {
193 return Err(GraphError::Empty);
194 }
195
196 let mut index: HashMap<Arc<str>, NodeIx> = HashMap::with_capacity(docs.len());
198 for (ix, doc) in docs.iter().enumerate() {
199 validate_node_id(&doc.id)?;
200 if index.insert(Arc::from(doc.id.as_str()), ix).is_some() {
201 return Err(GraphError::DuplicateNode(doc.id.clone()));
202 }
203 }
204 let mut nodes = Vec::with_capacity(docs.len());
205 for doc in docs {
206 let parent = match &doc.parent {
207 Some(p) => Some(*index.get(p.as_str()).ok_or_else(|| GraphError::MissingParent {
208 node: doc.id.clone(),
209 parent: p.clone(),
210 suggestion: crate::validate::suggest(p, docs.iter().map(|d| d.id.as_str())),
211 })?),
212 None => None,
213 };
214 let node = match checked.as_mut().and_then(Iterator::next) {
215 Some(node) => node,
216 None => {
217 let node = registry.build(doc)?;
218 if doc.strict {
219 check_fields(doc, registry)?;
220 }
221 node
222 }
223 };
224 nodes.push(GraphNode {
225 id: Arc::from(doc.id.as_str()),
226 kind: Arc::from(doc.kind.as_str()),
227 title: Arc::from(doc.label()),
228 parent,
229 policy: doc.policy.clone(),
230 role: node.role(),
231 node,
232 doc: doc.clone(),
233 });
234 }
235
236 for (ix, n) in nodes.iter().enumerate() {
238 if let Some(p) = n.parent
239 && nodes.get(p).map(|pn| pn.role) != Some(NodeRole::Container)
240 {
241 return Err(GraphError::ParentNotContainer(n.id.to_string()));
242 }
243 let mut seen = HashSet::new();
244 let mut cur = Some(ix);
245 while let Some(c) = cur {
246 if !seen.insert(c) {
247 return Err(GraphError::ParentCycle(n.id.to_string()));
248 }
249 cur = nodes.get(c).and_then(|x| x.parent);
250 }
251 }
252
253 let mut edges = Vec::with_capacity(workflow.graph.edges.len());
255 let mut dead_edges = Vec::new();
256 let mut edge_ids = HashSet::new();
257 let mut outgoing = vec![Vec::new(); nodes.len()];
258 let mut incoming = vec![Vec::new(); nodes.len()];
259 for (i, e) in workflow.graph.edges.iter().enumerate() {
260 let id: Arc<str> = Arc::from(e.id.clone().unwrap_or_else(|| format!("{}-{}-{i}", e.source, e.target)));
261 if !edge_ids.insert(id.clone()) {
262 return Err(GraphError::DuplicateEdge(id.to_string()));
263 }
264 let lookup = |n: &str| {
265 index.get(n).copied().ok_or_else(|| GraphError::MissingNode {
266 edge: id.to_string(),
267 node: n.to_owned(),
268 suggestion: crate::validate::suggest(n, docs.iter().map(|d| d.id.as_str())),
269 })
270 };
271 let source = lookup(&e.source)?;
272 let target = lookup(&e.target)?;
273 let (sp, tp) = (nodes.get(source).and_then(|n| n.parent), nodes.get(target).and_then(|n| n.parent));
274 if sp != tp {
275 return Err(GraphError::CrossScopeEdge {
276 edge: id.to_string(),
277 source_node: e.source.clone(),
278 target: e.target.clone(),
279 });
280 }
281 let handle = e.handle.as_deref().filter(|h| !h.is_empty()).unwrap_or(SOURCE_HANDLE);
282 if let Some(n) = nodes.get(source) {
283 let descriptor = registry.descriptor_ref(&n.doc.kind);
284 if let Some(message) = crate::validate::dead_fail_branch(&n.doc, handle) {
285 dead_edges.push(message);
286 }
287 if let Some(allowed) = crate::validate::allowed_handles(n.node.as_ref(), descriptor)
288 && !allowed.iter().any(|h| h == handle)
289 {
290 let mut message = crate::validate::handle_message(&n.doc, handle, &allowed);
291 message
292 .push_str(&did_you_mean(&crate::validate::suggest(handle, allowed.iter().map(String::as_str))));
293 return Err(GraphError::UnknownHandle { edge: id.to_string(), message });
294 }
295 }
296 let ex = edges.len();
297 edges.push(GraphEdge { id, source, target, handle: Arc::from(handle) });
298 if let Some(o) = outgoing.get_mut(source) {
299 o.push(ex);
300 }
301 if let Some(inc) = incoming.get_mut(target) {
302 inc.push(ex);
303 }
304 }
305
306 let mut members: HashMap<Option<NodeIx>, Vec<NodeIx>> = HashMap::new();
308 for (ix, n) in nodes.iter().enumerate() {
309 members.entry(n.parent).or_default().push(ix);
310 }
311 for (ix, n) in nodes.iter().enumerate() {
313 if n.role == NodeRole::Container {
314 members.entry(Some(ix)).or_default();
315 }
316 }
317
318 let mut warnings = dead_edges;
319 let mut scopes = HashMap::new();
320 for (owner, scope_nodes) in members {
321 let scope_name =
322 owner.and_then(|o| nodes.get(o)).map(|n| n.id.to_string()).unwrap_or_else(|| "root".into());
323 let entry = find_entry(&nodes, &incoming, owner, &scope_nodes, &scope_name)?;
324 let order = topo_order(&scope_nodes, &outgoing, &incoming, &edges, &nodes, &scope_name)?;
325 let reachable = reachable_from(entry, &outgoing, &edges);
327 for &ix in &scope_nodes {
328 if !reachable.contains(&ix)
329 && let Some(n) = nodes.get(ix)
330 {
331 warnings.push(format!("node `{}` is not reachable from the entry of scope `{scope_name}`", n.id));
332 }
333 }
334 scopes.insert(owner, Scope { owner, entry, nodes: order });
335 }
336
337 validate_references(&nodes, &index, &mut warnings)?;
338
339 let fingerprint = std::sync::OnceLock::new();
340 Ok(Self { nodes, edges, index, outgoing, incoming, scopes, warnings, fingerprint, workflow })
341 }
342
343 pub fn from_text(text: &str, registry: &Registry) -> Result<Self, crate::Error> {
345 let wf = Workflow::parse(text)?;
346 Ok(Self::build(wf, registry)?)
347 }
348
349 pub fn nodes(&self) -> &[GraphNode] {
350 &self.nodes
351 }
352
353 pub fn edges(&self) -> &[GraphEdge] {
354 &self.edges
355 }
356
357 pub fn node(&self, ix: NodeIx) -> Option<&GraphNode> {
358 self.nodes.get(ix)
359 }
360
361 pub fn edge(&self, ix: EdgeIx) -> Option<&GraphEdge> {
362 self.edges.get(ix)
363 }
364
365 pub fn index_of(&self, id: &str) -> Option<NodeIx> {
367 self.index.get(id).copied()
368 }
369
370 pub fn node_by_id(&self, id: &str) -> Option<&GraphNode> {
371 self.index_of(id).and_then(|ix| self.nodes.get(ix))
372 }
373
374 pub fn outgoing(&self, ix: NodeIx) -> &[EdgeIx] {
375 self.outgoing.get(ix).map(Vec::as_slice).unwrap_or_default()
376 }
377
378 pub fn incoming(&self, ix: NodeIx) -> &[EdgeIx] {
379 self.incoming.get(ix).map(Vec::as_slice).unwrap_or_default()
380 }
381
382 pub fn root_scope(&self) -> Option<&Scope> {
384 self.scopes.get(&None)
385 }
386
387 pub fn scope_of(&self, container: NodeIx) -> Option<&Scope> {
389 self.scopes.get(&Some(container))
390 }
391
392 pub fn is_descendant(&self, ix: NodeIx, ancestor: NodeIx) -> bool {
394 let mut cur = self.nodes.get(ix).and_then(|n| n.parent);
395 while let Some(c) = cur {
396 if c == ancestor {
397 return true;
398 }
399 cur = self.nodes.get(c).and_then(|n| n.parent);
400 }
401 false
402 }
403
404 pub fn warnings(&self) -> &[String] {
406 &self.warnings
407 }
408
409 pub fn fingerprint(&self) -> &str {
415 self.fingerprint.get_or_init(|| {
416 fingerprint(&self.workflow).unwrap_or_else(|error| fnv_hex(format!("unserializable: {error}").as_bytes()))
417 })
418 }
419
420 pub fn workflow(&self) -> &Workflow {
422 &self.workflow
423 }
424}
425
426fn validate_references(
436 nodes: &[GraphNode],
437 index: &HashMap<Arc<str>, NodeIx>,
438 warnings: &mut Vec<String>,
439) -> Result<(), GraphError> {
440 for (ix, n) in nodes.iter().enumerate() {
441 for selector in n.node.inputs() {
442 let namespace = selector.namespace();
443 if RESERVED_NAMESPACES.contains(&namespace) {
444 continue;
445 }
446 let Some(&target) = index.get(namespace) else {
447 let candidates = nodes.iter().map(|n| &*n.id).chain(RESERVED_NAMESPACES.iter().copied());
448 return Err(GraphError::UnknownReference {
449 node: n.id.to_string(),
450 selector: selector.to_string(),
451 namespace: namespace.to_owned(),
452 suggestion: crate::validate::suggest(namespace, candidates),
453 });
454 };
455 if !is_visible(nodes, ix, target) {
456 warnings.push(format!(
457 "node `{}` references `{selector}` from a different container body; it will resolve to null",
458 n.id
459 ));
460 }
461 }
462 }
463 Ok(())
464}
465
466fn check_fields(doc: &NodeDoc, registry: &Registry) -> Result<(), GraphError> {
469 let Some(descriptor) = registry.descriptor_ref(&doc.kind) else { return Ok(()) };
470 let base = crate::source_map::DocPath::root();
471 match crate::validate::config_diagnostics(doc, descriptor, &base).into_iter().find(|d| d.is_error()) {
472 None => Ok(()),
473 Some(d) => Err(GraphError::InvalidField {
474 node: doc.id.clone(),
475 path: d.path.to_string(),
476 message: format!("{}{}", d.message, did_you_mean(&d.suggestion)),
477 }),
478 }
479}
480
481fn is_visible(nodes: &[GraphNode], from: NodeIx, target: NodeIx) -> bool {
483 let parent_of = |ix: NodeIx| nodes.get(ix).and_then(|n| n.parent);
484 let target_scope = parent_of(target);
485 let mut scope = parent_of(from);
487 loop {
488 if scope == target_scope {
489 return true;
490 }
491 match scope {
492 Some(s) => scope = parent_of(s),
493 None => break,
494 }
495 }
496 let mut cur = target_scope;
498 while let Some(c) = cur {
499 if c == from {
500 return true;
501 }
502 cur = parent_of(c);
503 }
504 false
505}
506
507fn find_entry(
508 nodes: &[GraphNode],
509 incoming: &[Vec<EdgeIx>],
510 owner: Option<NodeIx>,
511 scope_nodes: &[NodeIx],
512 scope_name: &str,
513) -> Result<NodeIx, GraphError> {
514 let wanted = if owner.is_some() { NodeRole::ScopeStart } else { NodeRole::Root };
515 let explicit: Vec<NodeIx> =
516 scope_nodes.iter().copied().filter(|&ix| nodes.get(ix).map(|n| n.role) == Some(wanted)).collect();
517 let candidates = if explicit.is_empty() {
518 scope_nodes.iter().copied().filter(|&ix| incoming.get(ix).is_none_or(Vec::is_empty)).collect()
520 } else {
521 explicit
522 };
523 match candidates.as_slice() {
524 [] => Err(GraphError::NoEntry { scope: scope_name.to_owned() }),
525 [one] => Ok(*one),
526 many => Err(GraphError::MultipleEntries {
527 scope: scope_name.to_owned(),
528 nodes: many.iter().filter_map(|&ix| nodes.get(ix)).map(|n| n.id.to_string()).collect(),
529 }),
530 }
531}
532
533fn topo_order(
534 scope_nodes: &[NodeIx],
535 outgoing: &[Vec<EdgeIx>],
536 incoming: &[Vec<EdgeIx>],
537 edges: &[GraphEdge],
538 nodes: &[GraphNode],
539 scope_name: &str,
540) -> Result<Vec<NodeIx>, GraphError> {
541 let mut indeg: HashMap<NodeIx, usize> =
542 scope_nodes.iter().map(|&ix| (ix, incoming.get(ix).map_or(0, Vec::len))).collect();
543 let mut queue: VecDeque<NodeIx> = scope_nodes.iter().copied().filter(|ix| indeg.get(ix) == Some(&0)).collect();
544 let mut order = Vec::with_capacity(scope_nodes.len());
545 while let Some(ix) = queue.pop_front() {
546 order.push(ix);
547 for &ex in outgoing.get(ix).map(Vec::as_slice).unwrap_or_default() {
548 if let Some(e) = edges.get(ex)
549 && let Some(d) = indeg.get_mut(&e.target)
550 {
551 *d = d.saturating_sub(1);
552 if *d == 0 {
553 queue.push_back(e.target);
554 }
555 }
556 }
557 }
558 if order.len() != scope_nodes.len() {
559 let stuck = scope_nodes
560 .iter()
561 .find(|ix| indeg.get(ix).is_some_and(|d| *d > 0))
562 .and_then(|&ix| nodes.get(ix))
563 .map(|n| n.id.to_string())
564 .unwrap_or_default();
565 return Err(GraphError::Cycle { scope: scope_name.to_owned(), node: stuck });
566 }
567 Ok(order)
568}
569
570fn reachable_from(entry: NodeIx, outgoing: &[Vec<EdgeIx>], edges: &[GraphEdge]) -> HashSet<NodeIx> {
571 let mut seen = HashSet::from([entry]);
572 let mut stack = vec![entry];
573 while let Some(ix) = stack.pop() {
574 for &ex in outgoing.get(ix).map(Vec::as_slice).unwrap_or_default() {
575 if let Some(e) = edges.get(ex)
576 && seen.insert(e.target)
577 {
578 stack.push(e.target);
579 }
580 }
581 }
582 seen
583}
584
585fn fingerprint(workflow: &Workflow) -> Result<String, GraphError> {
588 let text = workflow.canonical_graph_json().map_err(|e| GraphError::Unserializable(e.to_string()))?;
589 let mut h = Fnv(FNV_OFFSET);
590 text.hash(&mut h);
591 Ok(format!("{:016x}", h.finish()))
592}
593
594fn fnv_hex(bytes: &[u8]) -> String {
596 let mut h = Fnv(FNV_OFFSET);
597 h.write(bytes);
598 format!("{:016x}", h.finish())
599}
600
601const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
602
603struct Fnv(u64);
605
606impl Hasher for Fnv {
607 fn finish(&self) -> u64 {
608 self.0
609 }
610 fn write(&mut self, bytes: &[u8]) {
611 for b in bytes {
612 self.0 ^= u64::from(*b);
613 self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
614 }
615 }
616}