Skip to main content

hydro_lang/viz/
render.rs

1use std::collections::{HashMap, HashSet};
2use std::error::Error;
3use std::fmt::{Display, Write};
4use std::num::ParseIntError;
5use std::sync::OnceLock;
6
7use auto_impl::auto_impl;
8use slotmap::{Key, SecondaryMap, SlotMap};
9
10pub use super::graphviz::{HydroDot, escape_dot};
11pub use super::json::HydroJson;
12// Re-export specific implementations
13pub use super::mermaid::{HydroMermaid, escape_mermaid};
14use crate::compile::ir::backtrace::Backtrace;
15use crate::compile::ir::{DebugExpr, HydroIrMetadata, HydroNode, HydroRoot, HydroSource};
16use crate::location::dynamic::LocationId;
17use crate::location::{LocationKey, LocationType};
18
19/// Label for a graph node - can be either a static string or contain expressions.
20#[derive(Debug, Clone)]
21pub enum NodeLabel {
22    /// A static string label
23    Static(String),
24    /// A label with an operation name and expression arguments
25    WithExprs {
26        op_name: String,
27        exprs: Vec<DebugExpr>,
28    },
29}
30
31impl NodeLabel {
32    /// Create a static label
33    pub fn static_label(s: String) -> Self {
34        Self::Static(s)
35    }
36
37    /// Create a label for an operation with multiple expression
38    pub fn with_exprs(op_name: String, exprs: Vec<DebugExpr>) -> Self {
39        Self::WithExprs { op_name, exprs }
40    }
41}
42
43impl Display for NodeLabel {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::Static(s) => write!(f, "{}", s),
47            Self::WithExprs { op_name, exprs } => {
48                if exprs.is_empty() {
49                    write!(f, "{}()", op_name)
50                } else {
51                    let expr_strs: Vec<_> = exprs.iter().map(|e| e.to_string()).collect();
52                    write!(f, "{}({})", op_name, expr_strs.join(", "))
53                }
54            }
55        }
56    }
57}
58
59/// Base struct for text-based graph writers that use indentation.
60/// Contains common fields shared by DOT and Mermaid writers.
61pub struct IndentedGraphWriter<'a, W> {
62    pub write: W,
63    pub indent: usize,
64    pub config: HydroWriteConfig<'a>,
65}
66
67impl<'a, W> IndentedGraphWriter<'a, W> {
68    /// Create a new writer with default configuration.
69    pub fn new(write: W) -> Self {
70        Self {
71            write,
72            indent: 0,
73            config: HydroWriteConfig::default(),
74        }
75    }
76
77    /// Create a new writer with the given configuration.
78    pub fn new_with_config(write: W, config: HydroWriteConfig<'a>) -> Self {
79        Self {
80            write,
81            indent: 0,
82            config,
83        }
84    }
85}
86
87impl<W: Write> IndentedGraphWriter<'_, W> {
88    /// Write an indented line using the current indentation level.
89    pub fn writeln_indented(&mut self, content: &str) -> Result<(), std::fmt::Error> {
90        writeln!(self.write, "{b:i$}{content}", b = "", i = self.indent)
91    }
92}
93
94/// Common error type used by all graph writers.
95pub type GraphWriteError = std::fmt::Error;
96
97/// Trait for writing textual representations of Hydro IR graphs, i.e. mermaid or dot graphs.
98#[auto_impl(&mut, Box)]
99pub trait HydroGraphWrite {
100    /// Error type emitted by writing.
101    type Err: Error;
102
103    /// Begin the graph. First method called.
104    fn write_prologue(&mut self) -> Result<(), Self::Err>;
105
106    /// Write a node definition with styling.
107    fn write_node_definition(
108        &mut self,
109        node_id: VizNodeKey,
110        node_label: &NodeLabel,
111        node_type: HydroNodeType,
112        location_key: Option<LocationKey>,
113        location_type: Option<LocationType>,
114        backtrace: Option<&Backtrace>,
115    ) -> Result<(), Self::Err>;
116
117    /// Write an edge between nodes with optional labeling.
118    fn write_edge(
119        &mut self,
120        src_id: VizNodeKey,
121        dst_id: VizNodeKey,
122        edge_properties: &HashSet<HydroEdgeProp>,
123        label: Option<&str>,
124    ) -> Result<(), Self::Err>;
125
126    /// Begin writing a location grouping (process/cluster).
127    fn write_location_start(
128        &mut self,
129        location_key: LocationKey,
130        location_type: LocationType,
131    ) -> Result<(), Self::Err>;
132
133    /// Write a node within a location.
134    fn write_node(&mut self, node_id: VizNodeKey) -> Result<(), Self::Err>;
135
136    /// End writing a location grouping.
137    fn write_location_end(&mut self) -> Result<(), Self::Err>;
138
139    /// End the graph. Last method called.
140    fn write_epilogue(&mut self) -> Result<(), Self::Err>;
141}
142
143/// Node type utilities - centralized handling of `HydroNodeType` operations
144pub mod node_type_utils {
145    use super::HydroNodeType;
146
147    /// All node types with their string names
148    const NODE_TYPE_DATA: &[(HydroNodeType, &str)] = &[
149        (HydroNodeType::Source, "Source"),
150        (HydroNodeType::Transform, "Transform"),
151        (HydroNodeType::Join, "Join"),
152        (HydroNodeType::Aggregation, "Aggregation"),
153        (HydroNodeType::Network, "Network"),
154        (HydroNodeType::Sink, "Sink"),
155        (HydroNodeType::Tee, "Tee"),
156        (HydroNodeType::NonDeterministic, "NonDeterministic"),
157    ];
158
159    /// Convert `HydroNodeType` to string representation (used by JSON format)
160    pub fn to_string(node_type: HydroNodeType) -> &'static str {
161        NODE_TYPE_DATA
162            .iter()
163            .find(|(nt, _)| *nt == node_type)
164            .map(|(_, name)| *name)
165            .unwrap_or("Unknown")
166    }
167
168    /// Get all node types with their string representations (used by JSON format)
169    pub fn all_types_with_strings() -> Vec<(HydroNodeType, &'static str)> {
170        NODE_TYPE_DATA.to_vec()
171    }
172}
173
174/// Types of nodes in Hydro IR for styling purposes.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum HydroNodeType {
177    Source,
178    Transform,
179    Join,
180    Aggregation,
181    Network,
182    Sink,
183    Tee,
184    NonDeterministic,
185}
186
187/// Types of edges in Hydro IR representing stream properties.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum HydroEdgeProp {
190    Bounded,
191    Unbounded,
192    TotalOrder,
193    NoOrder,
194    Keyed,
195    // Collection type tags for styling
196    Stream,
197    KeyedSingleton,
198    KeyedStream,
199    Singleton,
200    Optional,
201    Network,
202    Cycle,
203}
204
205/// Unified edge style representation for all graph formats.
206/// This intermediate format allows consistent styling across JSON, DOT, and Mermaid.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct UnifiedEdgeStyle {
209    /// Line pattern (solid, dashed)
210    pub line_pattern: LinePattern,
211    /// Line width (1 = thin, 3 = thick)
212    pub line_width: u8,
213    /// Arrowhead style
214    pub arrowhead: ArrowheadStyle,
215    /// Line style (single plain line, or line with hash marks/dots for keyed streams)
216    pub line_style: LineStyle,
217    /// Halo/background effect for boundedness
218    pub halo: HaloStyle,
219    /// Line waviness for ordering information
220    pub waviness: WavinessStyle,
221    /// Whether animation is enabled (JSON only)
222    pub animation: AnimationStyle,
223    /// Color for the edge
224    pub color: &'static str,
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub enum LinePattern {
229    Solid,
230    Dotted,
231    Dashed,
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum ArrowheadStyle {
236    TriangleFilled,
237    CircleFilled,
238    DiamondOpen,
239    Default,
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub enum LineStyle {
244    /// Plain single line
245    Single,
246    /// Single line with hash marks/dots (for keyed streams)
247    HashMarks,
248}
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum HaloStyle {
252    None,
253    LightBlue,
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub enum WavinessStyle {
258    None,
259    Wavy,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub enum AnimationStyle {
264    Static,
265    Animated,
266}
267
268impl Default for UnifiedEdgeStyle {
269    fn default() -> Self {
270        Self {
271            line_pattern: LinePattern::Solid,
272            line_width: 1,
273            arrowhead: ArrowheadStyle::Default,
274            line_style: LineStyle::Single,
275            halo: HaloStyle::None,
276            waviness: WavinessStyle::None,
277            animation: AnimationStyle::Static,
278            color: "#666666",
279        }
280    }
281}
282
283/// Convert `HydroEdgeType` properties to unified edge style.
284/// This is the core logic for determining edge visual properties.
285///
286/// # Visual Encoding Mapping
287///
288/// | Semantic Property | Visual Channel | Values |
289/// |------------------|----------------|---------|
290/// | Network | Line Pattern + Animation | Local (solid, static), Network (dashed, animated) |
291/// | Ordering | Waviness | TotalOrder (straight), NoOrder (wavy) |
292/// | Boundedness | Halo | Bounded (none), Unbounded (light-blue transparent) |
293/// | Keyedness | Line Style | NotKeyed (plain line), Keyed (line with hash marks/dots) |
294/// | Collection Type | Color + Arrowhead | Stream (blue #2563eb, triangle), Singleton (black, circle), Optional (gray, diamond) |
295pub fn get_unified_edge_style(
296    edge_properties: &HashSet<HydroEdgeProp>,
297    src_location: Option<usize>,
298    dst_location: Option<usize>,
299) -> UnifiedEdgeStyle {
300    let mut style = UnifiedEdgeStyle::default();
301
302    // Network communication group - controls line pattern AND animation
303    let is_network = edge_properties.contains(&HydroEdgeProp::Network)
304        || (src_location.is_some() && dst_location.is_some() && src_location != dst_location);
305
306    if is_network {
307        style.line_pattern = LinePattern::Dashed;
308        style.animation = AnimationStyle::Animated;
309    } else {
310        style.line_pattern = LinePattern::Solid;
311        style.animation = AnimationStyle::Static;
312    }
313
314    // Boundedness group - controls halo
315    if edge_properties.contains(&HydroEdgeProp::Unbounded) {
316        style.halo = HaloStyle::LightBlue;
317    } else {
318        style.halo = HaloStyle::None;
319    }
320
321    // Collection type group - controls arrowhead and color
322    if edge_properties.contains(&HydroEdgeProp::Stream) {
323        style.arrowhead = ArrowheadStyle::TriangleFilled;
324        style.color = "#2563eb"; // Bright blue for Stream
325    } else if edge_properties.contains(&HydroEdgeProp::KeyedStream) {
326        style.arrowhead = ArrowheadStyle::TriangleFilled;
327        style.color = "#2563eb"; // Bright blue for Stream (keyed variant)
328    } else if edge_properties.contains(&HydroEdgeProp::KeyedSingleton) {
329        style.arrowhead = ArrowheadStyle::TriangleFilled;
330        style.color = "#000000"; // Black for Singleton (keyed variant)
331    } else if edge_properties.contains(&HydroEdgeProp::Singleton) {
332        style.arrowhead = ArrowheadStyle::CircleFilled;
333        style.color = "#000000"; // Black for Singleton
334    } else if edge_properties.contains(&HydroEdgeProp::Optional) {
335        style.arrowhead = ArrowheadStyle::DiamondOpen;
336        style.color = "#6b7280"; // Gray for Optional
337    }
338
339    // Keyedness group - controls hash marks on the line
340    if edge_properties.contains(&HydroEdgeProp::Keyed) {
341        style.line_style = LineStyle::HashMarks; // Renders as hash marks/dots on the line in hydroscope
342    } else {
343        style.line_style = LineStyle::Single;
344    }
345
346    // Ordering group - waviness channel
347    if edge_properties.contains(&HydroEdgeProp::NoOrder) {
348        style.waviness = WavinessStyle::Wavy;
349    } else if edge_properties.contains(&HydroEdgeProp::TotalOrder) {
350        style.waviness = WavinessStyle::None;
351    }
352
353    style
354}
355
356/// Extract semantic edge properties from `CollectionKind` metadata.
357/// This function analyzes the collection type and extracts relevant semantic tags
358/// for visualization purposes.
359pub fn extract_edge_properties_from_collection_kind(
360    collection_kind: &crate::compile::ir::CollectionKind,
361) -> HashSet<HydroEdgeProp> {
362    use crate::compile::ir::CollectionKind;
363
364    let mut properties = HashSet::new();
365
366    match collection_kind {
367        CollectionKind::Stream { bound, order, .. } => {
368            properties.insert(HydroEdgeProp::Stream);
369            add_bound_property(&mut properties, bound);
370            add_order_property(&mut properties, order);
371        }
372        CollectionKind::KeyedStream {
373            bound, value_order, ..
374        } => {
375            properties.insert(HydroEdgeProp::KeyedStream);
376            properties.insert(HydroEdgeProp::Keyed);
377            add_bound_property(&mut properties, bound);
378            add_order_property(&mut properties, value_order);
379        }
380        CollectionKind::Singleton { bound, .. } => {
381            properties.insert(HydroEdgeProp::Singleton);
382            add_singleton_bound_property(&mut properties, bound);
383            // Singletons have implicit TotalOrder
384            properties.insert(HydroEdgeProp::TotalOrder);
385        }
386        CollectionKind::Optional { bound, .. } => {
387            properties.insert(HydroEdgeProp::Optional);
388            add_optional_bound_property(&mut properties, bound);
389            // Optionals have implicit TotalOrder
390            properties.insert(HydroEdgeProp::TotalOrder);
391        }
392        CollectionKind::KeyedSingleton { bound, .. } => {
393            properties.insert(HydroEdgeProp::Singleton);
394            properties.insert(HydroEdgeProp::Keyed);
395            // KeyedSingletons boundedness depends on the bound kind
396            add_keyed_singleton_bound_property(&mut properties, bound);
397            properties.insert(HydroEdgeProp::TotalOrder);
398        }
399    }
400
401    properties
402}
403
404/// Helper function to add bound property based on `BoundKind`.
405fn add_bound_property(
406    properties: &mut HashSet<HydroEdgeProp>,
407    bound: &crate::compile::ir::BoundKind,
408) {
409    use crate::compile::ir::BoundKind;
410
411    match bound {
412        BoundKind::Bounded => {
413            properties.insert(HydroEdgeProp::Bounded);
414        }
415        BoundKind::Unbounded => {
416            properties.insert(HydroEdgeProp::Unbounded);
417        }
418    }
419}
420
421/// Helper function to add bound property for Optional based on `OptionalBoundKind`.
422fn add_optional_bound_property(
423    properties: &mut HashSet<HydroEdgeProp>,
424    bound: &crate::compile::ir::OptionalBoundKind,
425) {
426    use crate::compile::ir::OptionalBoundKind;
427
428    match bound {
429        OptionalBoundKind::Bounded => {
430            properties.insert(HydroEdgeProp::Bounded);
431        }
432        OptionalBoundKind::InitNone | OptionalBoundKind::Unbounded => {
433            properties.insert(HydroEdgeProp::Unbounded);
434        }
435    }
436}
437
438/// Helper function to add bound property for Singleton based on `SingletonBoundKind`.
439fn add_singleton_bound_property(
440    properties: &mut HashSet<HydroEdgeProp>,
441    bound: &crate::compile::ir::SingletonBoundKind,
442) {
443    use crate::compile::ir::SingletonBoundKind;
444
445    match bound {
446        SingletonBoundKind::Bounded => {
447            properties.insert(HydroEdgeProp::Bounded);
448        }
449        SingletonBoundKind::Monotonic | SingletonBoundKind::Unbounded => {
450            properties.insert(HydroEdgeProp::Unbounded);
451        }
452    }
453}
454
455/// Helper function to add bound property for `KeyedSingleton` based on `KeyedSingletonBoundKind`.
456fn add_keyed_singleton_bound_property(
457    properties: &mut HashSet<HydroEdgeProp>,
458    bound: &crate::compile::ir::KeyedSingletonBoundKind,
459) {
460    use crate::compile::ir::KeyedSingletonBoundKind;
461
462    match bound {
463        KeyedSingletonBoundKind::Bounded => {
464            properties.insert(HydroEdgeProp::Bounded);
465        }
466        KeyedSingletonBoundKind::BoundedValue
467        | KeyedSingletonBoundKind::MonotonicKeys
468        | KeyedSingletonBoundKind::MonotonicValue
469        | KeyedSingletonBoundKind::Unbounded => {
470            properties.insert(HydroEdgeProp::Unbounded);
471        }
472    }
473}
474
475/// Helper function to add order property based on `StreamOrder`.
476fn add_order_property(
477    properties: &mut HashSet<HydroEdgeProp>,
478    order: &crate::compile::ir::StreamOrder,
479) {
480    use crate::compile::ir::StreamOrder;
481
482    match order {
483        StreamOrder::TotalOrder => {
484            properties.insert(HydroEdgeProp::TotalOrder);
485        }
486        StreamOrder::NoOrder => {
487            properties.insert(HydroEdgeProp::NoOrder);
488        }
489    }
490}
491
492/// Detect if an edge crosses network boundaries by comparing source and destination locations.
493/// Returns true if the edge represents network communication between different locations.
494pub fn is_network_edge(src_location: &LocationId, dst_location: &LocationId) -> bool {
495    // Compare the root locations to determine if they differ
496    src_location.root() != dst_location.root()
497}
498
499/// Add network edge tag if source and destination locations differ.
500pub fn add_network_edge_tag(
501    properties: &mut HashSet<HydroEdgeProp>,
502    src_location: &LocationId,
503    dst_location: &LocationId,
504) {
505    if is_network_edge(src_location, dst_location) {
506        properties.insert(HydroEdgeProp::Network);
507    }
508}
509
510/// Configuration for graph writing.
511#[derive(Debug, Clone, Copy)]
512pub struct HydroWriteConfig<'a> {
513    pub show_metadata: bool,
514    pub show_location_groups: bool,
515    pub use_short_labels: bool,
516    pub location_names: &'a SecondaryMap<LocationKey, String>,
517}
518
519impl Default for HydroWriteConfig<'_> {
520    fn default() -> Self {
521        static EMPTY: OnceLock<SecondaryMap<LocationKey, String>> = OnceLock::new();
522        Self {
523            show_metadata: false,
524            show_location_groups: true,
525            use_short_labels: true, // Default to short labels for all renderers
526            location_names: EMPTY.get_or_init(SecondaryMap::new),
527        }
528    }
529}
530
531/// Node information in the Hydro graph.
532#[derive(Clone)]
533pub struct HydroGraphNode {
534    pub label: NodeLabel,
535    pub node_type: HydroNodeType,
536    pub location_key: Option<LocationKey>,
537    pub backtrace: Option<Backtrace>,
538}
539
540slotmap::new_key_type! {
541    /// Unique identifier for nodes in the visualization graph.
542    ///
543    /// This is counted/allocated separately from any other IDs within `hydro_lang`.
544    pub struct VizNodeKey;
545}
546
547impl Display for VizNodeKey {
548    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
549        write!(f, "viz{:?}", self.data()) // `"viz1v1"``
550    }
551}
552
553/// This is used by the visualizer
554/// TODO(mingwei): Make this more robust?
555impl std::str::FromStr for VizNodeKey {
556    type Err = Option<ParseIntError>;
557
558    fn from_str(s: &str) -> Result<Self, Self::Err> {
559        let nvn = s.strip_prefix("viz").ok_or(None)?;
560        let (idx, ver) = nvn.split_once('v').ok_or(None)?;
561        let idx: u64 = idx.parse()?;
562        let ver: u64 = ver.parse()?;
563        Ok(slotmap::KeyData::from_ffi((ver << 32) | idx).into())
564    }
565}
566
567impl VizNodeKey {
568    /// A key for testing with index 1.
569    #[cfg(test)]
570    pub const TEST_KEY_1: Self = Self(slotmap::KeyData::from_ffi(0x0000008F00000001)); // `1v143`
571
572    /// A key for testing with index 2.
573    #[cfg(test)]
574    pub const TEST_KEY_2: Self = Self(slotmap::KeyData::from_ffi(0x0000008F00000002)); // `2v143`
575}
576
577/// Edge information in the Hydro graph.
578#[derive(Debug, Clone)]
579pub struct HydroGraphEdge {
580    pub src: VizNodeKey,
581    pub dst: VizNodeKey,
582    pub edge_properties: HashSet<HydroEdgeProp>,
583    pub label: Option<String>,
584}
585
586/// Graph structure tracker for Hydro IR rendering.
587#[derive(Default)]
588pub struct HydroGraphStructure {
589    pub nodes: SlotMap<VizNodeKey, HydroGraphNode>,
590    pub edges: Vec<HydroGraphEdge>,
591    pub locations: SecondaryMap<LocationKey, LocationType>,
592}
593
594impl HydroGraphStructure {
595    pub fn new() -> Self {
596        Self::default()
597    }
598
599    pub fn add_node(
600        &mut self,
601        label: NodeLabel,
602        node_type: HydroNodeType,
603        location_key: Option<LocationKey>,
604    ) -> VizNodeKey {
605        self.add_node_with_backtrace(label, node_type, location_key, None)
606    }
607
608    pub fn add_node_with_backtrace(
609        &mut self,
610        label: NodeLabel,
611        node_type: HydroNodeType,
612        location_key: Option<LocationKey>,
613        backtrace: Option<Backtrace>,
614    ) -> VizNodeKey {
615        self.nodes.insert(HydroGraphNode {
616            label,
617            node_type,
618            location_key,
619            backtrace,
620        })
621    }
622
623    /// Add a node with metadata, extracting backtrace automatically
624    pub fn add_node_with_metadata(
625        &mut self,
626        label: NodeLabel,
627        node_type: HydroNodeType,
628        metadata: &HydroIrMetadata,
629    ) -> VizNodeKey {
630        let location_key = Some(setup_location(self, metadata));
631        let backtrace = Some(metadata.op.backtrace.clone());
632        self.add_node_with_backtrace(label, node_type, location_key, backtrace)
633    }
634
635    pub fn add_edge(
636        &mut self,
637        src: VizNodeKey,
638        dst: VizNodeKey,
639        edge_properties: HashSet<HydroEdgeProp>,
640        label: Option<String>,
641    ) {
642        self.edges.push(HydroGraphEdge {
643            src,
644            dst,
645            edge_properties,
646            label,
647        });
648    }
649
650    // Legacy method for backward compatibility
651    pub fn add_edge_single(
652        &mut self,
653        src: VizNodeKey,
654        dst: VizNodeKey,
655        edge_type: HydroEdgeProp,
656        label: Option<String>,
657    ) {
658        let mut properties = HashSet::new();
659        properties.insert(edge_type);
660        self.edges.push(HydroGraphEdge {
661            src,
662            dst,
663            edge_properties: properties,
664            label,
665        });
666    }
667
668    pub fn add_location(&mut self, location_key: LocationKey, location_type: LocationType) {
669        self.locations.insert(location_key, location_type);
670    }
671}
672
673/// Function to extract an `op_name` from a `print_root()` result for use in labels.
674pub fn extract_op_name(full_label: String) -> String {
675    full_label
676        .split('(')
677        .next()
678        .unwrap_or("unknown")
679        .to_lowercase()
680}
681
682/// Extract a short, readable label from the full token stream label using `print_root()` style naming
683pub fn extract_short_label(full_label: &str) -> String {
684    // Use the same logic as extract_op_name but handle the specific cases we need for UI display
685    if let Some(op_name) = full_label.split('(').next() {
686        let base_name = op_name.to_lowercase();
687        match base_name.as_str() {
688            // Handle special cases for UI display
689            "source" => {
690                if full_label.contains("Iter") {
691                    "source_iter".to_owned()
692                } else if full_label.contains("Stream") {
693                    "source_stream".to_owned()
694                } else if full_label.contains("ExternalNetwork") {
695                    "external_network".to_owned()
696                } else if full_label.contains("Spin") {
697                    "spin".to_owned()
698                } else {
699                    "source".to_owned()
700                }
701            }
702            "network" => {
703                if full_label.contains("deser") {
704                    "network(recv)".to_owned()
705                } else if full_label.contains("ser") {
706                    "network(send)".to_owned()
707                } else {
708                    "network".to_owned()
709                }
710            }
711            // For all other cases, just use the lowercase base name (same as extract_op_name)
712            _ => base_name,
713        }
714    } else {
715        // Fallback for labels that don't follow the pattern
716        if full_label.len() > 20 {
717            format!("{}...", &full_label[..17])
718        } else {
719            full_label.to_owned()
720        }
721    }
722}
723
724/// Helper function to set up location in structure from metadata.
725fn setup_location(structure: &mut HydroGraphStructure, metadata: &HydroIrMetadata) -> LocationKey {
726    let root = metadata.location_id.root();
727    let location_key = root.key();
728    let location_type = root.location_type().unwrap();
729    structure.add_location(location_key, location_type);
730    location_key
731}
732
733/// Helper function to add an edge with semantic tags extracted from metadata.
734/// This function combines collection kind extraction with network detection.
735fn add_edge_with_metadata(
736    structure: &mut HydroGraphStructure,
737    src_id: VizNodeKey,
738    dst_id: VizNodeKey,
739    src_metadata: Option<&HydroIrMetadata>,
740    dst_metadata: Option<&HydroIrMetadata>,
741    label: Option<String>,
742) {
743    let mut properties = HashSet::new();
744
745    // Extract semantic tags from source metadata's collection kind
746    if let Some(metadata) = src_metadata {
747        properties.extend(extract_edge_properties_from_collection_kind(
748            &metadata.collection_kind,
749        ));
750    }
751
752    // Add network edge tag if locations differ
753    if let (Some(src_meta), Some(dst_meta)) = (src_metadata, dst_metadata) {
754        add_network_edge_tag(
755            &mut properties,
756            &src_meta.location_id,
757            &dst_meta.location_id,
758        );
759    }
760
761    // If no properties were extracted, default to Stream
762    if properties.is_empty() {
763        properties.insert(HydroEdgeProp::Stream);
764    }
765
766    structure.add_edge(src_id, dst_id, properties, label);
767}
768
769/// Helper function to write a graph structure using any `GraphWrite` implementation
770fn write_graph_structure<W>(
771    structure: &HydroGraphStructure,
772    graph_write: W,
773    config: HydroWriteConfig<'_>,
774) -> Result<(), W::Err>
775where
776    W: HydroGraphWrite,
777{
778    let mut graph_write = graph_write;
779    // Write the graph
780    graph_write.write_prologue()?;
781
782    // Write node definitions
783    for (node_id, node) in structure.nodes.iter() {
784        let location_type = node
785            .location_key
786            .and_then(|loc_key| structure.locations.get(loc_key))
787            .copied();
788
789        graph_write.write_node_definition(
790            node_id,
791            &node.label,
792            node.node_type,
793            node.location_key,
794            location_type,
795            node.backtrace.as_ref(),
796        )?;
797    }
798
799    // Group nodes by location if requested
800    if config.show_location_groups {
801        let mut nodes_by_location = SecondaryMap::<LocationKey, Vec<VizNodeKey>>::new();
802        for (node_id, node) in structure.nodes.iter() {
803            if let Some(location_key) = node.location_key {
804                nodes_by_location
805                    .entry(location_key)
806                    .expect("location was removed")
807                    .or_default()
808                    .push(node_id);
809            }
810        }
811
812        for (location_key, node_ids) in nodes_by_location.iter() {
813            if let Some(&location_type) = structure.locations.get(location_key) {
814                graph_write.write_location_start(location_key, location_type)?;
815                for &node_id in node_ids.iter() {
816                    graph_write.write_node(node_id)?;
817                }
818                graph_write.write_location_end()?;
819            }
820        }
821    }
822
823    // Write edges
824    for edge in structure.edges.iter() {
825        graph_write.write_edge(
826            edge.src,
827            edge.dst,
828            &edge.edge_properties,
829            edge.label.as_deref(),
830        )?;
831    }
832
833    graph_write.write_epilogue()?;
834    Ok(())
835}
836
837impl HydroRoot {
838    /// Build the graph structure by traversing the IR tree.
839    pub fn build_graph_structure(
840        &self,
841        structure: &mut HydroGraphStructure,
842        seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
843        config: HydroWriteConfig<'_>,
844    ) -> VizNodeKey {
845        // Helper function for sink nodes to reduce duplication
846        fn build_sink_node(
847            structure: &mut HydroGraphStructure,
848            seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
849            config: HydroWriteConfig<'_>,
850            input: &HydroNode,
851            sink_metadata: Option<&HydroIrMetadata>,
852            label: NodeLabel,
853        ) -> VizNodeKey {
854            let input_id = input.build_graph_structure(structure, seen_tees, config);
855
856            // If no explicit metadata is provided, extract it from the input node
857            let effective_metadata = if let Some(meta) = sink_metadata {
858                Some(meta)
859            } else {
860                match input {
861                    HydroNode::Placeholder => None,
862                    // All other variants have metadata
863                    _ => Some(input.metadata()),
864                }
865            };
866
867            let location_key = effective_metadata.map(|m| setup_location(structure, m));
868            let sink_id = structure.add_node_with_backtrace(
869                label,
870                HydroNodeType::Sink,
871                location_key,
872                effective_metadata.map(|m| m.op.backtrace.clone()),
873            );
874
875            // Extract semantic tags from input metadata
876            let input_metadata = input.metadata();
877            add_edge_with_metadata(
878                structure,
879                input_id,
880                sink_id,
881                Some(input_metadata),
882                sink_metadata,
883                None,
884            );
885
886            sink_id
887        }
888
889        match self {
890            // Sink operations - semantic tags extracted from input metadata
891            HydroRoot::ForEach { f, input, .. } => build_sink_node(
892                structure,
893                seen_tees,
894                config,
895                input,
896                None,
897                NodeLabel::with_exprs("for_each".to_owned(), vec![f.expr.clone()]),
898            ),
899
900            HydroRoot::SendExternal {
901                to_external_key,
902                to_port_id,
903                input,
904                ..
905            } => build_sink_node(
906                structure,
907                seen_tees,
908                config,
909                input,
910                None,
911                NodeLabel::with_exprs(
912                    format!("send_external({}:{})", to_external_key, to_port_id),
913                    vec![],
914                ),
915            ),
916
917            HydroRoot::DestSink { sink, input, .. } => build_sink_node(
918                structure,
919                seen_tees,
920                config,
921                input,
922                None,
923                NodeLabel::with_exprs("dest_sink".to_owned(), vec![sink.clone()]),
924            ),
925
926            HydroRoot::CycleSink {
927                cycle_id, input, ..
928            } => build_sink_node(
929                structure,
930                seen_tees,
931                config,
932                input,
933                None,
934                NodeLabel::static_label(format!("cycle_sink({})", cycle_id)),
935            ),
936
937            HydroRoot::EmbeddedOutput { ident, input, .. } => build_sink_node(
938                structure,
939                seen_tees,
940                config,
941                input,
942                None,
943                NodeLabel::static_label(format!("embedded_output({})", ident)),
944            ),
945
946            HydroRoot::Null { input, .. } => build_sink_node(
947                structure,
948                seen_tees,
949                config,
950                input,
951                None,
952                NodeLabel::static_label("null".to_owned()),
953            ),
954        }
955    }
956}
957
958impl HydroNode {
959    /// Build the graph structure recursively for this node.
960    pub fn build_graph_structure(
961        &self,
962        structure: &mut HydroGraphStructure,
963        seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
964        config: HydroWriteConfig<'_>,
965    ) -> VizNodeKey {
966        // Helper functions to reduce duplication, categorized by input/expression patterns
967
968        /// Common parameters for transform builder functions to reduce argument count
969        struct TransformParams<'a> {
970            structure: &'a mut HydroGraphStructure,
971            seen_tees: &'a mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
972            config: HydroWriteConfig<'a>,
973            input: &'a HydroNode,
974            metadata: &'a HydroIrMetadata,
975            op_name: String,
976            node_type: HydroNodeType,
977        }
978
979        // Single-input transform with no expressions
980        fn build_simple_transform(params: TransformParams<'_>) -> VizNodeKey {
981            let input_id = params.input.build_graph_structure(
982                params.structure,
983                params.seen_tees,
984                params.config,
985            );
986            let node_id = params.structure.add_node_with_metadata(
987                NodeLabel::Static(params.op_name.clone()),
988                params.node_type,
989                params.metadata,
990            );
991
992            // Extract semantic tags from input metadata
993            let input_metadata = params.input.metadata();
994            add_edge_with_metadata(
995                params.structure,
996                input_id,
997                node_id,
998                Some(input_metadata),
999                Some(params.metadata),
1000                None,
1001            );
1002
1003            node_id
1004        }
1005
1006        // Single-input transform with one expression
1007        fn build_single_expr_transform(
1008            params: TransformParams<'_>,
1009            expr: &DebugExpr,
1010        ) -> VizNodeKey {
1011            let input_id = params.input.build_graph_structure(
1012                params.structure,
1013                params.seen_tees,
1014                params.config,
1015            );
1016            let node_id = params.structure.add_node_with_metadata(
1017                NodeLabel::with_exprs(params.op_name.clone(), vec![expr.clone()]),
1018                params.node_type,
1019                params.metadata,
1020            );
1021
1022            // Extract semantic tags from input metadata
1023            let input_metadata = params.input.metadata();
1024            add_edge_with_metadata(
1025                params.structure,
1026                input_id,
1027                node_id,
1028                Some(input_metadata),
1029                Some(params.metadata),
1030                None,
1031            );
1032
1033            node_id
1034        }
1035
1036        // Single-input transform with two expressions
1037        fn build_dual_expr_transform(
1038            params: TransformParams<'_>,
1039            expr1: &DebugExpr,
1040            expr2: &DebugExpr,
1041        ) -> VizNodeKey {
1042            let input_id = params.input.build_graph_structure(
1043                params.structure,
1044                params.seen_tees,
1045                params.config,
1046            );
1047            let node_id = params.structure.add_node_with_metadata(
1048                NodeLabel::with_exprs(params.op_name.clone(), vec![expr1.clone(), expr2.clone()]),
1049                params.node_type,
1050                params.metadata,
1051            );
1052
1053            // Extract semantic tags from input metadata
1054            let input_metadata = params.input.metadata();
1055            add_edge_with_metadata(
1056                params.structure,
1057                input_id,
1058                node_id,
1059                Some(input_metadata),
1060                Some(params.metadata),
1061                None,
1062            );
1063
1064            node_id
1065        }
1066
1067        // Helper function for source nodes
1068        fn build_source_node(
1069            structure: &mut HydroGraphStructure,
1070            metadata: &HydroIrMetadata,
1071            label: String,
1072        ) -> VizNodeKey {
1073            structure.add_node_with_metadata(
1074                NodeLabel::Static(label),
1075                HydroNodeType::Source,
1076                metadata,
1077            )
1078        }
1079
1080        match self {
1081            HydroNode::Placeholder => structure.add_node(
1082                NodeLabel::Static("PLACEHOLDER".to_owned()),
1083                HydroNodeType::Transform,
1084                None,
1085            ),
1086
1087            HydroNode::Source {
1088                source, metadata, ..
1089            } => {
1090                let label = match source {
1091                    HydroSource::Stream(expr) => format!("source_stream({})", expr),
1092                    HydroSource::ExternalNetwork() => "external_network()".to_owned(),
1093                    HydroSource::Iter(expr) => format!("source_iter({})", expr),
1094                    HydroSource::Spin() => "spin()".to_owned(),
1095                    HydroSource::ClusterMembers(location_id, _) => {
1096                        format!(
1097                            "source_stream(cluster_membership_stream({:?}))",
1098                            location_id
1099                        )
1100                    }
1101                    HydroSource::Embedded(ident) => {
1102                        format!("embedded_input({})", ident)
1103                    }
1104                    HydroSource::EmbeddedSingleton(ident) => {
1105                        format!("embedded_singleton_input({})", ident)
1106                    }
1107                };
1108                build_source_node(structure, metadata, label)
1109            }
1110
1111            HydroNode::SingletonSource {
1112                value,
1113                first_tick_only,
1114                metadata,
1115            } => {
1116                let label = if *first_tick_only {
1117                    format!("singleton_first_tick({})", value)
1118                } else {
1119                    format!("singleton({})", value)
1120                };
1121                build_source_node(structure, metadata, label)
1122            }
1123
1124            HydroNode::ExternalInput {
1125                from_external_key,
1126                from_port_id,
1127                metadata,
1128                ..
1129            } => build_source_node(
1130                structure,
1131                metadata,
1132                format!("external_input({}:{})", from_external_key, from_port_id),
1133            ),
1134
1135            HydroNode::CycleSource {
1136                cycle_id, metadata, ..
1137            } => build_source_node(structure, metadata, format!("cycle_source({})", cycle_id)),
1138
1139            HydroNode::Tee { inner, metadata }
1140            | HydroNode::Reference {
1141                inner, metadata, ..
1142            } => {
1143                let ptr = inner.as_ptr();
1144                if let Some(&existing_id) = seen_tees.get(&ptr) {
1145                    return existing_id;
1146                }
1147
1148                let input_id = inner
1149                    .0
1150                    .borrow()
1151                    .build_graph_structure(structure, seen_tees, config);
1152                let node_type = if matches!(self, HydroNode::Reference { .. }) {
1153                    HydroNodeType::Aggregation
1154                } else {
1155                    HydroNodeType::Tee
1156                };
1157                let tee_id = structure.add_node_with_metadata(
1158                    NodeLabel::Static(extract_op_name(self.print_root())),
1159                    node_type,
1160                    metadata,
1161                );
1162
1163                seen_tees.insert(ptr, tee_id);
1164
1165                // Extract semantic tags from input
1166                let inner_borrow = inner.0.borrow();
1167                let input_metadata = inner_borrow.metadata();
1168                add_edge_with_metadata(
1169                    structure,
1170                    input_id,
1171                    tee_id,
1172                    Some(input_metadata),
1173                    Some(metadata),
1174                    None,
1175                );
1176                drop(inner_borrow);
1177
1178                tee_id
1179            }
1180
1181            HydroNode::PartitionSide {
1182                inner, metadata, ..
1183            } => {
1184                let ptr = inner.as_ptr();
1185                if let Some(&existing_id) = seen_tees.get(&ptr) {
1186                    return existing_id;
1187                }
1188
1189                let input_id = inner
1190                    .0
1191                    .borrow()
1192                    .build_graph_structure(structure, seen_tees, config);
1193                let partition_id = structure.add_node_with_metadata(
1194                    NodeLabel::Static(extract_op_name(self.print_root())),
1195                    HydroNodeType::Tee,
1196                    metadata,
1197                );
1198
1199                seen_tees.insert(ptr, partition_id);
1200
1201                // Extract semantic tags from input
1202                let inner_borrow = inner.0.borrow();
1203                let input_metadata = inner_borrow.metadata();
1204                add_edge_with_metadata(
1205                    structure,
1206                    input_id,
1207                    partition_id,
1208                    Some(input_metadata),
1209                    Some(metadata),
1210                    None,
1211                );
1212                drop(inner_borrow);
1213
1214                partition_id
1215            }
1216            HydroNode::PartitionShared { input, .. } => {
1217                // Transparent pass-thru.
1218                input.build_graph_structure(structure, seen_tees, config)
1219            }
1220
1221            // Non-deterministic operation
1222            HydroNode::ObserveNonDet {
1223                inner, metadata, ..
1224            } => build_simple_transform(TransformParams {
1225                structure,
1226                seen_tees,
1227                config,
1228                input: inner,
1229                metadata,
1230                op_name: extract_op_name(self.print_root()),
1231                node_type: HydroNodeType::NonDeterministic,
1232            }),
1233
1234            // Transform operations with Stream edges - grouped by node/edge type
1235            HydroNode::Cast { inner, metadata }
1236            | HydroNode::CastUpdateStream { inner, metadata }
1237            | HydroNode::AssertIsConsistent {
1238                inner, metadata, ..
1239            }
1240            | HydroNode::DeferTick {
1241                input: inner,
1242                metadata,
1243            }
1244            | HydroNode::Enumerate {
1245                input: inner,
1246                metadata,
1247                ..
1248            }
1249            | HydroNode::Unique {
1250                input: inner,
1251                metadata,
1252            }
1253            | HydroNode::ResolveFutures {
1254                input: inner,
1255                metadata,
1256            }
1257            | HydroNode::ResolveFuturesBlocking {
1258                input: inner,
1259                metadata,
1260            }
1261            | HydroNode::ResolveFuturesOrdered {
1262                input: inner,
1263                metadata,
1264            } => build_simple_transform(TransformParams {
1265                structure,
1266                seen_tees,
1267                config,
1268                input: inner,
1269                metadata,
1270                op_name: extract_op_name(self.print_root()),
1271                node_type: HydroNodeType::Transform,
1272            }),
1273
1274            // Aggregation operation - semantic tags extracted from metadata
1275            HydroNode::Sort {
1276                input: inner,
1277                metadata,
1278            } => build_simple_transform(TransformParams {
1279                structure,
1280                seen_tees,
1281                config,
1282                input: inner,
1283                metadata,
1284                op_name: extract_op_name(self.print_root()),
1285                node_type: HydroNodeType::Aggregation,
1286            }),
1287
1288            // Single-expression Transform operations - grouped by node type
1289            HydroNode::Map {
1290                f, input, metadata, ..
1291            }
1292            | HydroNode::Filter { f, input, metadata }
1293            | HydroNode::FlatMap { f, input, metadata }
1294            | HydroNode::FlatMapStreamBlocking { f, input, metadata }
1295            | HydroNode::FilterMap { f, input, metadata }
1296            | HydroNode::Inspect { f, input, metadata } => build_single_expr_transform(
1297                TransformParams {
1298                    structure,
1299                    seen_tees,
1300                    config,
1301                    input,
1302                    metadata,
1303                    op_name: extract_op_name(self.print_root()),
1304                    node_type: HydroNodeType::Transform,
1305                },
1306                &f.expr,
1307            ),
1308
1309            // Single-expression Aggregation operations - grouped by node type
1310            HydroNode::Reduce { f, input, metadata }
1311            | HydroNode::ReduceKeyed { f, input, metadata } => build_single_expr_transform(
1312                TransformParams {
1313                    structure,
1314                    seen_tees,
1315                    config,
1316                    input,
1317                    metadata,
1318                    op_name: extract_op_name(self.print_root()),
1319                    node_type: HydroNodeType::Aggregation,
1320                },
1321                &f.expr,
1322            ),
1323
1324            // Join-like operations with left/right edge labels - grouped by edge labeling
1325            HydroNode::Join {
1326                left,
1327                right,
1328                metadata,
1329            }
1330            | HydroNode::JoinHalf {
1331                left,
1332                right,
1333                metadata,
1334            }
1335            | HydroNode::CrossProduct {
1336                left,
1337                right,
1338                metadata,
1339            }
1340            | HydroNode::CrossSingleton {
1341                left,
1342                right,
1343                metadata,
1344            } => {
1345                let left_id = left.build_graph_structure(structure, seen_tees, config);
1346                let right_id = right.build_graph_structure(structure, seen_tees, config);
1347                let node_id = structure.add_node_with_metadata(
1348                    NodeLabel::Static(extract_op_name(self.print_root())),
1349                    HydroNodeType::Join,
1350                    metadata,
1351                );
1352
1353                // Extract semantic tags for left edge
1354                let left_metadata = left.metadata();
1355                add_edge_with_metadata(
1356                    structure,
1357                    left_id,
1358                    node_id,
1359                    Some(left_metadata),
1360                    Some(metadata),
1361                    Some("left".to_owned()),
1362                );
1363
1364                // Extract semantic tags for right edge
1365                let right_metadata = right.metadata();
1366                add_edge_with_metadata(
1367                    structure,
1368                    right_id,
1369                    node_id,
1370                    Some(right_metadata),
1371                    Some(metadata),
1372                    Some("right".to_owned()),
1373                );
1374
1375                node_id
1376            }
1377
1378            // Join-like operations with pos/neg edge labels - grouped by edge labeling
1379            HydroNode::Difference {
1380                pos: left,
1381                neg: right,
1382                metadata,
1383            }
1384            | HydroNode::AntiJoin {
1385                pos: left,
1386                neg: right,
1387                metadata,
1388            } => {
1389                let left_id = left.build_graph_structure(structure, seen_tees, config);
1390                let right_id = right.build_graph_structure(structure, seen_tees, config);
1391                let node_id = structure.add_node_with_metadata(
1392                    NodeLabel::Static(extract_op_name(self.print_root())),
1393                    HydroNodeType::Join,
1394                    metadata,
1395                );
1396
1397                // Extract semantic tags for pos edge
1398                let left_metadata = left.metadata();
1399                add_edge_with_metadata(
1400                    structure,
1401                    left_id,
1402                    node_id,
1403                    Some(left_metadata),
1404                    Some(metadata),
1405                    Some("pos".to_owned()),
1406                );
1407
1408                // Extract semantic tags for neg edge
1409                let right_metadata = right.metadata();
1410                add_edge_with_metadata(
1411                    structure,
1412                    right_id,
1413                    node_id,
1414                    Some(right_metadata),
1415                    Some(metadata),
1416                    Some("neg".to_owned()),
1417                );
1418
1419                node_id
1420            }
1421
1422            // Dual expression transforms - consolidated using pattern matching
1423            HydroNode::Fold {
1424                init,
1425                acc,
1426                input,
1427                metadata,
1428                ..
1429            }
1430            | HydroNode::FoldKeyed {
1431                init,
1432                acc,
1433                input,
1434                metadata,
1435                ..
1436            }
1437            | HydroNode::Scan {
1438                init,
1439                acc,
1440                input,
1441                metadata,
1442            }
1443            | HydroNode::ScanAsyncBlocking {
1444                init,
1445                acc,
1446                input,
1447                metadata,
1448            } => {
1449                let node_type = HydroNodeType::Aggregation; // All are aggregation operations
1450
1451                build_dual_expr_transform(
1452                    TransformParams {
1453                        structure,
1454                        seen_tees,
1455                        config,
1456                        input,
1457                        metadata,
1458                        op_name: extract_op_name(self.print_root()),
1459                        node_type,
1460                    },
1461                    &init.expr,
1462                    &acc.expr,
1463                )
1464            }
1465
1466            // Combination of join and transform
1467            HydroNode::ReduceKeyedWatermark {
1468                f,
1469                input,
1470                watermark,
1471                metadata,
1472            } => {
1473                let input_id = input.build_graph_structure(structure, seen_tees, config);
1474                let watermark_id = watermark.build_graph_structure(structure, seen_tees, config);
1475                let location_key = Some(setup_location(structure, metadata));
1476                let join_node_id = structure.add_node_with_backtrace(
1477                    NodeLabel::Static(extract_op_name(self.print_root())),
1478                    HydroNodeType::Join,
1479                    location_key,
1480                    Some(metadata.op.backtrace.clone()),
1481                );
1482
1483                // Extract semantic tags for input edge
1484                let input_metadata = input.metadata();
1485                add_edge_with_metadata(
1486                    structure,
1487                    input_id,
1488                    join_node_id,
1489                    Some(input_metadata),
1490                    Some(metadata),
1491                    Some("input".to_owned()),
1492                );
1493
1494                // Extract semantic tags for watermark edge
1495                let watermark_metadata = watermark.metadata();
1496                add_edge_with_metadata(
1497                    structure,
1498                    watermark_id,
1499                    join_node_id,
1500                    Some(watermark_metadata),
1501                    Some(metadata),
1502                    Some("watermark".to_owned()),
1503                );
1504
1505                let node_id = structure.add_node_with_backtrace(
1506                    NodeLabel::with_exprs(extract_op_name(self.print_root()), vec![f.expr.clone()]),
1507                    HydroNodeType::Aggregation,
1508                    location_key,
1509                    Some(metadata.op.backtrace.clone()),
1510                );
1511
1512                // Edge from join to aggregation node
1513                let join_metadata = metadata; // Use the same metadata
1514                add_edge_with_metadata(
1515                    structure,
1516                    join_node_id,
1517                    node_id,
1518                    Some(join_metadata),
1519                    Some(metadata),
1520                    None,
1521                );
1522
1523                node_id
1524            }
1525
1526            HydroNode::Network {
1527                serialize,
1528                deserialize,
1529                input,
1530                metadata,
1531                ..
1532            } => {
1533                let input_id = input.build_graph_structure(structure, seen_tees, config);
1534                let _from_location_key = setup_location(structure, metadata);
1535
1536                let root = metadata.location_id.root();
1537                let to_location_key = root.key();
1538                let to_location_type = root.location_type().unwrap();
1539                structure.add_location(to_location_key, to_location_type);
1540
1541                let has_serialize = match serialize {
1542                    crate::compile::ir::NetworkSend::Custom { serialize_fn } => {
1543                        serialize_fn.is_some()
1544                    }
1545                    // Embedded channels still convert member-id tags on the send side.
1546                    crate::compile::ir::NetworkSend::Embedded { .. } => true,
1547                };
1548                let has_deserialize = match deserialize {
1549                    crate::compile::ir::NetworkRecv::Custom { deserialize_fn } => {
1550                        deserialize_fn.is_some()
1551                    }
1552                    crate::compile::ir::NetworkRecv::Embedded { .. } => true,
1553                };
1554
1555                let mut label = "network(".to_owned();
1556                if has_serialize {
1557                    label.push_str("send");
1558                }
1559                if has_deserialize {
1560                    if has_serialize {
1561                        label.push_str(" + ");
1562                    }
1563                    label.push_str("recv");
1564                }
1565                label.push(')');
1566
1567                let network_id = structure.add_node_with_backtrace(
1568                    NodeLabel::Static(label),
1569                    HydroNodeType::Network,
1570                    Some(to_location_key),
1571                    Some(metadata.op.backtrace.clone()),
1572                );
1573
1574                // Extract semantic tags for network edge
1575                let input_metadata = input.metadata();
1576                add_edge_with_metadata(
1577                    structure,
1578                    input_id,
1579                    network_id,
1580                    Some(input_metadata),
1581                    Some(metadata),
1582                    Some(format!("to {:?}({})", to_location_type, to_location_key)),
1583                );
1584
1585                network_id
1586            }
1587
1588            // Non-deterministic batch / snapshot operations
1589            HydroNode::Batch { inner, metadata } | HydroNode::Snapshot { inner, metadata } => {
1590                build_simple_transform(TransformParams {
1591                    structure,
1592                    seen_tees,
1593                    config,
1594                    input: inner,
1595                    metadata,
1596                    op_name: extract_op_name(self.print_root()),
1597                    node_type: HydroNodeType::NonDeterministic,
1598                })
1599            }
1600
1601            HydroNode::YieldConcat { inner, .. } => {
1602                // Unpersist is typically optimized away, just pass through
1603                inner.build_graph_structure(structure, seen_tees, config)
1604            }
1605
1606            HydroNode::UnboundSingleton { inner, .. } => {
1607                inner.build_graph_structure(structure, seen_tees, config)
1608            }
1609
1610            HydroNode::BeginAtomic { inner, .. } => {
1611                inner.build_graph_structure(structure, seen_tees, config)
1612            }
1613
1614            HydroNode::EndAtomic { inner, .. } => {
1615                inner.build_graph_structure(structure, seen_tees, config)
1616            }
1617
1618            HydroNode::Chain {
1619                first,
1620                second,
1621                metadata,
1622            }
1623            | HydroNode::MergeOrdered {
1624                first,
1625                second,
1626                metadata,
1627            } => {
1628                let first_id = first.build_graph_structure(structure, seen_tees, config);
1629                let second_id = second.build_graph_structure(structure, seen_tees, config);
1630                let location_key = Some(setup_location(structure, metadata));
1631                let chain_id = structure.add_node_with_backtrace(
1632                    NodeLabel::Static(extract_op_name(self.print_root())),
1633                    HydroNodeType::Transform,
1634                    location_key,
1635                    Some(metadata.op.backtrace.clone()),
1636                );
1637
1638                // Extract semantic tags for first edge
1639                let first_metadata = first.metadata();
1640                add_edge_with_metadata(
1641                    structure,
1642                    first_id,
1643                    chain_id,
1644                    Some(first_metadata),
1645                    Some(metadata),
1646                    Some("first".to_owned()),
1647                );
1648
1649                // Extract semantic tags for second edge
1650                let second_metadata = second.metadata();
1651                add_edge_with_metadata(
1652                    structure,
1653                    second_id,
1654                    chain_id,
1655                    Some(second_metadata),
1656                    Some(metadata),
1657                    Some("second".to_owned()),
1658                );
1659
1660                chain_id
1661            }
1662
1663            HydroNode::VersionedNetworkFork {
1664                senders, metadata, ..
1665            } => {
1666                let location_key = Some(setup_location(structure, metadata));
1667                let fork_id = structure.add_node_with_backtrace(
1668                    NodeLabel::Static(extract_op_name(self.print_root())),
1669                    HydroNodeType::NonDeterministic,
1670                    location_key,
1671                    Some(metadata.op.backtrace.clone()),
1672                );
1673
1674                for (version, sender, _serialize) in senders {
1675                    let sender_id = sender.build_graph_structure(structure, seen_tees, config);
1676                    let sender_metadata = sender.metadata();
1677                    add_edge_with_metadata(
1678                        structure,
1679                        sender_id,
1680                        fork_id,
1681                        Some(sender_metadata),
1682                        Some(metadata),
1683                        Some(format!("send v{version}")),
1684                    );
1685                }
1686
1687                fork_id
1688            }
1689
1690            HydroNode::VersionedNetwork {
1691                fork,
1692                version,
1693                metadata,
1694                ..
1695            } => {
1696                let ptr = fork.as_ptr();
1697                let fork_id = if let Some(&existing_id) = seen_tees.get(&ptr) {
1698                    existing_id
1699                } else {
1700                    let built = fork
1701                        .0
1702                        .borrow()
1703                        .build_graph_structure(structure, seen_tees, config);
1704                    seen_tees.insert(ptr, built);
1705                    built
1706                };
1707
1708                let branch_location = Some(setup_location(structure, metadata));
1709                let branch_id = structure.add_node_with_backtrace(
1710                    NodeLabel::Static(extract_op_name(self.print_root())),
1711                    HydroNodeType::NonDeterministic,
1712                    branch_location,
1713                    Some(metadata.op.backtrace.clone()),
1714                );
1715
1716                add_edge_with_metadata(
1717                    structure,
1718                    fork_id,
1719                    branch_id,
1720                    Some(metadata),
1721                    Some(metadata),
1722                    Some(format!("recv v{version}")),
1723                );
1724
1725                branch_id
1726            }
1727
1728            HydroNode::ChainFirst {
1729                first,
1730                second,
1731                metadata,
1732            } => {
1733                let first_id = first.build_graph_structure(structure, seen_tees, config);
1734                let second_id = second.build_graph_structure(structure, seen_tees, config);
1735                let location_key = Some(setup_location(structure, metadata));
1736                let chain_id = structure.add_node_with_backtrace(
1737                    NodeLabel::Static(extract_op_name(self.print_root())),
1738                    HydroNodeType::Transform,
1739                    location_key,
1740                    Some(metadata.op.backtrace.clone()),
1741                );
1742
1743                // Extract semantic tags for first edge
1744                let first_metadata = first.metadata();
1745                add_edge_with_metadata(
1746                    structure,
1747                    first_id,
1748                    chain_id,
1749                    Some(first_metadata),
1750                    Some(metadata),
1751                    Some("first".to_owned()),
1752                );
1753
1754                // Extract semantic tags for second edge
1755                let second_metadata = second.metadata();
1756                add_edge_with_metadata(
1757                    structure,
1758                    second_id,
1759                    chain_id,
1760                    Some(second_metadata),
1761                    Some(metadata),
1762                    Some("second".to_owned()),
1763                );
1764
1765                chain_id
1766            }
1767
1768            HydroNode::Counter {
1769                tag: _,
1770                prefix: _,
1771                duration,
1772                input,
1773                metadata,
1774            } => build_single_expr_transform(
1775                TransformParams {
1776                    structure,
1777                    seen_tees,
1778                    config,
1779                    input,
1780                    metadata,
1781                    op_name: extract_op_name(self.print_root()),
1782                    node_type: HydroNodeType::Transform,
1783                },
1784                duration,
1785            ),
1786        }
1787    }
1788}
1789
1790/// Utility functions for rendering multiple roots as a single graph.
1791/// Macro to reduce duplication in render functions.
1792macro_rules! render_hydro_ir {
1793    ($name:ident, $write_fn:ident) => {
1794        pub fn $name(roots: &[HydroRoot], config: HydroWriteConfig<'_>) -> String {
1795            let mut output = String::new();
1796            $write_fn(&mut output, roots, config).unwrap();
1797            output
1798        }
1799    };
1800}
1801
1802/// Macro to reduce duplication in write functions.
1803macro_rules! write_hydro_ir {
1804    ($name:ident, $writer_type:ty, $constructor:expr) => {
1805        pub fn $name(
1806            output: impl std::fmt::Write,
1807            roots: &[HydroRoot],
1808            config: HydroWriteConfig<'_>,
1809        ) -> std::fmt::Result {
1810            let mut graph_write: $writer_type = $constructor(output, config);
1811            write_hydro_ir_graph(&mut graph_write, roots, config)
1812        }
1813    };
1814}
1815
1816render_hydro_ir!(render_hydro_ir_mermaid, write_hydro_ir_mermaid);
1817write_hydro_ir!(
1818    write_hydro_ir_mermaid,
1819    HydroMermaid<'_, _>,
1820    HydroMermaid::new_with_config
1821);
1822
1823render_hydro_ir!(render_hydro_ir_dot, write_hydro_ir_dot);
1824write_hydro_ir!(
1825    write_hydro_ir_dot,
1826    HydroDot<'_, _>,
1827    HydroDot::new_with_config
1828);
1829
1830// Legacy hydroscope function - now uses HydroJson for consistency
1831render_hydro_ir!(render_hydro_ir_hydroscope, write_hydro_ir_json);
1832
1833// JSON rendering
1834render_hydro_ir!(render_hydro_ir_json, write_hydro_ir_json);
1835write_hydro_ir!(write_hydro_ir_json, HydroJson<'_, _>, HydroJson::new);
1836
1837fn write_hydro_ir_graph<W>(
1838    graph_write: W,
1839    roots: &[HydroRoot],
1840    config: HydroWriteConfig<'_>,
1841) -> Result<(), W::Err>
1842where
1843    W: HydroGraphWrite,
1844{
1845    let mut structure = HydroGraphStructure::new();
1846    let mut seen_tees = HashMap::new();
1847
1848    // Build the graph structure for all roots
1849    for leaf in roots {
1850        leaf.build_graph_structure(&mut structure, &mut seen_tees, config);
1851    }
1852
1853    write_graph_structure(&structure, graph_write, config)
1854}