hydro_lang 0.16.0

A Rust framework for correct and performant distributed systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt::{Display, Write};
use std::num::ParseIntError;
use std::sync::OnceLock;

use auto_impl::auto_impl;
use slotmap::{Key, SecondaryMap, SlotMap};

pub use super::graphviz::{HydroDot, escape_dot};
pub use super::json::HydroJson;
// Re-export specific implementations
pub use super::mermaid::{HydroMermaid, escape_mermaid};
use crate::compile::ir::backtrace::Backtrace;
use crate::compile::ir::{DebugExpr, HydroIrMetadata, HydroNode, HydroRoot, HydroSource};
use crate::location::dynamic::LocationId;
use crate::location::{LocationKey, LocationType};

/// Label for a graph node - can be either a static string or contain expressions.
#[derive(Debug, Clone)]
pub enum NodeLabel {
    /// A static string label
    Static(String),
    /// A label with an operation name and expression arguments
    WithExprs {
        op_name: String,
        exprs: Vec<DebugExpr>,
    },
}

impl NodeLabel {
    /// Create a static label
    pub fn static_label(s: String) -> Self {
        Self::Static(s)
    }

    /// Create a label for an operation with multiple expression
    pub fn with_exprs(op_name: String, exprs: Vec<DebugExpr>) -> Self {
        Self::WithExprs { op_name, exprs }
    }
}

impl Display for NodeLabel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Static(s) => write!(f, "{}", s),
            Self::WithExprs { op_name, exprs } => {
                if exprs.is_empty() {
                    write!(f, "{}()", op_name)
                } else {
                    let expr_strs: Vec<_> = exprs.iter().map(|e| e.to_string()).collect();
                    write!(f, "{}({})", op_name, expr_strs.join(", "))
                }
            }
        }
    }
}

/// Base struct for text-based graph writers that use indentation.
/// Contains common fields shared by DOT and Mermaid writers.
pub struct IndentedGraphWriter<'a, W> {
    pub write: W,
    pub indent: usize,
    pub config: HydroWriteConfig<'a>,
}

impl<'a, W> IndentedGraphWriter<'a, W> {
    /// Create a new writer with default configuration.
    pub fn new(write: W) -> Self {
        Self {
            write,
            indent: 0,
            config: HydroWriteConfig::default(),
        }
    }

    /// Create a new writer with the given configuration.
    pub fn new_with_config(write: W, config: HydroWriteConfig<'a>) -> Self {
        Self {
            write,
            indent: 0,
            config,
        }
    }
}

impl<W: Write> IndentedGraphWriter<'_, W> {
    /// Write an indented line using the current indentation level.
    pub fn writeln_indented(&mut self, content: &str) -> Result<(), std::fmt::Error> {
        writeln!(self.write, "{b:i$}{content}", b = "", i = self.indent)
    }
}

/// Common error type used by all graph writers.
pub type GraphWriteError = std::fmt::Error;

/// Trait for writing textual representations of Hydro IR graphs, i.e. mermaid or dot graphs.
#[auto_impl(&mut, Box)]
pub trait HydroGraphWrite {
    /// Error type emitted by writing.
    type Err: Error;

    /// Begin the graph. First method called.
    fn write_prologue(&mut self) -> Result<(), Self::Err>;

    /// Write a node definition with styling.
    fn write_node_definition(
        &mut self,
        node_id: VizNodeKey,
        node_label: &NodeLabel,
        node_type: HydroNodeType,
        location_key: Option<LocationKey>,
        location_type: Option<LocationType>,
        backtrace: Option<&Backtrace>,
    ) -> Result<(), Self::Err>;

    /// Write an edge between nodes with optional labeling.
    fn write_edge(
        &mut self,
        src_id: VizNodeKey,
        dst_id: VizNodeKey,
        edge_properties: &HashSet<HydroEdgeProp>,
        label: Option<&str>,
    ) -> Result<(), Self::Err>;

    /// Begin writing a location grouping (process/cluster).
    fn write_location_start(
        &mut self,
        location_key: LocationKey,
        location_type: LocationType,
    ) -> Result<(), Self::Err>;

    /// Write a node within a location.
    fn write_node(&mut self, node_id: VizNodeKey) -> Result<(), Self::Err>;

    /// End writing a location grouping.
    fn write_location_end(&mut self) -> Result<(), Self::Err>;

    /// End the graph. Last method called.
    fn write_epilogue(&mut self) -> Result<(), Self::Err>;
}

/// Node type utilities - centralized handling of HydroNodeType operations
pub mod node_type_utils {
    use super::HydroNodeType;

    /// All node types with their string names
    const NODE_TYPE_DATA: &[(HydroNodeType, &str)] = &[
        (HydroNodeType::Source, "Source"),
        (HydroNodeType::Transform, "Transform"),
        (HydroNodeType::Join, "Join"),
        (HydroNodeType::Aggregation, "Aggregation"),
        (HydroNodeType::Network, "Network"),
        (HydroNodeType::Sink, "Sink"),
        (HydroNodeType::Tee, "Tee"),
        (HydroNodeType::NonDeterministic, "NonDeterministic"),
    ];

    /// Convert HydroNodeType to string representation (used by JSON format)
    pub fn to_string(node_type: HydroNodeType) -> &'static str {
        NODE_TYPE_DATA
            .iter()
            .find(|(nt, _)| *nt == node_type)
            .map(|(_, name)| *name)
            .unwrap_or("Unknown")
    }

    /// Get all node types with their string representations (used by JSON format)
    pub fn all_types_with_strings() -> Vec<(HydroNodeType, &'static str)> {
        NODE_TYPE_DATA.to_vec()
    }
}

/// Types of nodes in Hydro IR for styling purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HydroNodeType {
    Source,
    Transform,
    Join,
    Aggregation,
    Network,
    Sink,
    Tee,
    NonDeterministic,
}

/// Types of edges in Hydro IR representing stream properties.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HydroEdgeProp {
    Bounded,
    Unbounded,
    TotalOrder,
    NoOrder,
    Keyed,
    // Collection type tags for styling
    Stream,
    KeyedSingleton,
    KeyedStream,
    Singleton,
    Optional,
    Network,
    Cycle,
}

/// Unified edge style representation for all graph formats.
/// This intermediate format allows consistent styling across JSON, DOT, and Mermaid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnifiedEdgeStyle {
    /// Line pattern (solid, dashed)
    pub line_pattern: LinePattern,
    /// Line width (1 = thin, 3 = thick)
    pub line_width: u8,
    /// Arrowhead style
    pub arrowhead: ArrowheadStyle,
    /// Line style (single plain line, or line with hash marks/dots for keyed streams)
    pub line_style: LineStyle,
    /// Halo/background effect for boundedness
    pub halo: HaloStyle,
    /// Line waviness for ordering information
    pub waviness: WavinessStyle,
    /// Whether animation is enabled (JSON only)
    pub animation: AnimationStyle,
    /// Color for the edge
    pub color: &'static str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinePattern {
    Solid,
    Dotted,
    Dashed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrowheadStyle {
    TriangleFilled,
    CircleFilled,
    DiamondOpen,
    Default,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineStyle {
    /// Plain single line
    Single,
    /// Single line with hash marks/dots (for keyed streams)
    HashMarks,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HaloStyle {
    None,
    LightBlue,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WavinessStyle {
    None,
    Wavy,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationStyle {
    Static,
    Animated,
}

impl Default for UnifiedEdgeStyle {
    fn default() -> Self {
        Self {
            line_pattern: LinePattern::Solid,
            line_width: 1,
            arrowhead: ArrowheadStyle::Default,
            line_style: LineStyle::Single,
            halo: HaloStyle::None,
            waviness: WavinessStyle::None,
            animation: AnimationStyle::Static,
            color: "#666666",
        }
    }
}

/// Convert HydroEdgeType properties to unified edge style.
/// This is the core logic for determining edge visual properties.
///
/// # Visual Encoding Mapping
///
/// | Semantic Property | Visual Channel | Values |
/// |------------------|----------------|---------|
/// | Network | Line Pattern + Animation | Local (solid, static), Network (dashed, animated) |
/// | Ordering | Waviness | TotalOrder (straight), NoOrder (wavy) |
/// | Boundedness | Halo | Bounded (none), Unbounded (light-blue transparent) |
/// | Keyedness | Line Style | NotKeyed (plain line), Keyed (line with hash marks/dots) |
/// | Collection Type | Color + Arrowhead | Stream (blue #2563eb, triangle), Singleton (black, circle), Optional (gray, diamond) |
pub fn get_unified_edge_style(
    edge_properties: &HashSet<HydroEdgeProp>,
    src_location: Option<usize>,
    dst_location: Option<usize>,
) -> UnifiedEdgeStyle {
    let mut style = UnifiedEdgeStyle::default();

    // Network communication group - controls line pattern AND animation
    let is_network = edge_properties.contains(&HydroEdgeProp::Network)
        || (src_location.is_some() && dst_location.is_some() && src_location != dst_location);

    if is_network {
        style.line_pattern = LinePattern::Dashed;
        style.animation = AnimationStyle::Animated;
    } else {
        style.line_pattern = LinePattern::Solid;
        style.animation = AnimationStyle::Static;
    }

    // Boundedness group - controls halo
    if edge_properties.contains(&HydroEdgeProp::Unbounded) {
        style.halo = HaloStyle::LightBlue;
    } else {
        style.halo = HaloStyle::None;
    }

    // Collection type group - controls arrowhead and color
    if edge_properties.contains(&HydroEdgeProp::Stream) {
        style.arrowhead = ArrowheadStyle::TriangleFilled;
        style.color = "#2563eb"; // Bright blue for Stream
    } else if edge_properties.contains(&HydroEdgeProp::KeyedStream) {
        style.arrowhead = ArrowheadStyle::TriangleFilled;
        style.color = "#2563eb"; // Bright blue for Stream (keyed variant)
    } else if edge_properties.contains(&HydroEdgeProp::KeyedSingleton) {
        style.arrowhead = ArrowheadStyle::TriangleFilled;
        style.color = "#000000"; // Black for Singleton (keyed variant)
    } else if edge_properties.contains(&HydroEdgeProp::Singleton) {
        style.arrowhead = ArrowheadStyle::CircleFilled;
        style.color = "#000000"; // Black for Singleton
    } else if edge_properties.contains(&HydroEdgeProp::Optional) {
        style.arrowhead = ArrowheadStyle::DiamondOpen;
        style.color = "#6b7280"; // Gray for Optional
    }

    // Keyedness group - controls hash marks on the line
    if edge_properties.contains(&HydroEdgeProp::Keyed) {
        style.line_style = LineStyle::HashMarks; // Renders as hash marks/dots on the line in hydroscope
    } else {
        style.line_style = LineStyle::Single;
    }

    // Ordering group - waviness channel
    if edge_properties.contains(&HydroEdgeProp::NoOrder) {
        style.waviness = WavinessStyle::Wavy;
    } else if edge_properties.contains(&HydroEdgeProp::TotalOrder) {
        style.waviness = WavinessStyle::None;
    }

    style
}

/// Extract semantic edge properties from CollectionKind metadata.
/// This function analyzes the collection type and extracts relevant semantic tags
/// for visualization purposes.
pub fn extract_edge_properties_from_collection_kind(
    collection_kind: &crate::compile::ir::CollectionKind,
) -> HashSet<HydroEdgeProp> {
    use crate::compile::ir::CollectionKind;

    let mut properties = HashSet::new();

    match collection_kind {
        CollectionKind::Stream { bound, order, .. } => {
            properties.insert(HydroEdgeProp::Stream);
            add_bound_property(&mut properties, bound);
            add_order_property(&mut properties, order);
        }
        CollectionKind::KeyedStream {
            bound, value_order, ..
        } => {
            properties.insert(HydroEdgeProp::KeyedStream);
            properties.insert(HydroEdgeProp::Keyed);
            add_bound_property(&mut properties, bound);
            add_order_property(&mut properties, value_order);
        }
        CollectionKind::Singleton { bound, .. } => {
            properties.insert(HydroEdgeProp::Singleton);
            add_singleton_bound_property(&mut properties, bound);
            // Singletons have implicit TotalOrder
            properties.insert(HydroEdgeProp::TotalOrder);
        }
        CollectionKind::Optional { bound, .. } => {
            properties.insert(HydroEdgeProp::Optional);
            add_bound_property(&mut properties, bound);
            // Optionals have implicit TotalOrder
            properties.insert(HydroEdgeProp::TotalOrder);
        }
        CollectionKind::KeyedSingleton { bound, .. } => {
            properties.insert(HydroEdgeProp::Singleton);
            properties.insert(HydroEdgeProp::Keyed);
            // KeyedSingletons boundedness depends on the bound kind
            add_keyed_singleton_bound_property(&mut properties, bound);
            properties.insert(HydroEdgeProp::TotalOrder);
        }
    }

    properties
}

/// Helper function to add bound property based on BoundKind.
fn add_bound_property(
    properties: &mut HashSet<HydroEdgeProp>,
    bound: &crate::compile::ir::BoundKind,
) {
    use crate::compile::ir::BoundKind;

    match bound {
        BoundKind::Bounded => {
            properties.insert(HydroEdgeProp::Bounded);
        }
        BoundKind::Unbounded => {
            properties.insert(HydroEdgeProp::Unbounded);
        }
    }
}

/// Helper function to add bound property for Singleton based on SingletonBoundKind.
fn add_singleton_bound_property(
    properties: &mut HashSet<HydroEdgeProp>,
    bound: &crate::compile::ir::SingletonBoundKind,
) {
    use crate::compile::ir::SingletonBoundKind;

    match bound {
        SingletonBoundKind::Bounded => {
            properties.insert(HydroEdgeProp::Bounded);
        }
        SingletonBoundKind::Monotonic | SingletonBoundKind::Unbounded => {
            properties.insert(HydroEdgeProp::Unbounded);
        }
    }
}

/// Helper function to add bound property for KeyedSingleton based on KeyedSingletonBoundKind.
fn add_keyed_singleton_bound_property(
    properties: &mut HashSet<HydroEdgeProp>,
    bound: &crate::compile::ir::KeyedSingletonBoundKind,
) {
    use crate::compile::ir::KeyedSingletonBoundKind;

    match bound {
        KeyedSingletonBoundKind::Bounded => {
            properties.insert(HydroEdgeProp::Bounded);
        }
        KeyedSingletonBoundKind::BoundedValue
        | KeyedSingletonBoundKind::MonotonicValue
        | KeyedSingletonBoundKind::Unbounded => {
            properties.insert(HydroEdgeProp::Unbounded);
        }
    }
}

/// Helper function to add order property based on StreamOrder.
fn add_order_property(
    properties: &mut HashSet<HydroEdgeProp>,
    order: &crate::compile::ir::StreamOrder,
) {
    use crate::compile::ir::StreamOrder;

    match order {
        StreamOrder::TotalOrder => {
            properties.insert(HydroEdgeProp::TotalOrder);
        }
        StreamOrder::NoOrder => {
            properties.insert(HydroEdgeProp::NoOrder);
        }
    }
}

/// Detect if an edge crosses network boundaries by comparing source and destination locations.
/// Returns true if the edge represents network communication between different locations.
pub fn is_network_edge(src_location: &LocationId, dst_location: &LocationId) -> bool {
    // Compare the root locations to determine if they differ
    src_location.root() != dst_location.root()
}

/// Add network edge tag if source and destination locations differ.
pub fn add_network_edge_tag(
    properties: &mut HashSet<HydroEdgeProp>,
    src_location: &LocationId,
    dst_location: &LocationId,
) {
    if is_network_edge(src_location, dst_location) {
        properties.insert(HydroEdgeProp::Network);
    }
}

/// Configuration for graph writing.
#[derive(Debug, Clone, Copy)]
pub struct HydroWriteConfig<'a> {
    pub show_metadata: bool,
    pub show_location_groups: bool,
    pub use_short_labels: bool,
    pub location_names: &'a SecondaryMap<LocationKey, String>,
}

impl Default for HydroWriteConfig<'_> {
    fn default() -> Self {
        static EMPTY: OnceLock<SecondaryMap<LocationKey, String>> = OnceLock::new();
        Self {
            show_metadata: false,
            show_location_groups: true,
            use_short_labels: true, // Default to short labels for all renderers
            location_names: EMPTY.get_or_init(SecondaryMap::new),
        }
    }
}

/// Node information in the Hydro graph.
#[derive(Clone)]
pub struct HydroGraphNode {
    pub label: NodeLabel,
    pub node_type: HydroNodeType,
    pub location_key: Option<LocationKey>,
    pub backtrace: Option<Backtrace>,
}

slotmap::new_key_type! {
    /// Unique identifier for nodes in the visualization graph.
    ///
    /// This is counted/allocated separately from any other IDs within `hydro_lang`.
    pub struct VizNodeKey;
}

impl Display for VizNodeKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "viz{:?}", self.data()) // `"viz1v1"``
    }
}

/// This is used by the visualizer
/// TODO(mingwei): Make this more robust?
impl std::str::FromStr for VizNodeKey {
    type Err = Option<ParseIntError>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let nvn = s.strip_prefix("viz").ok_or(None)?;
        let (idx, ver) = nvn.split_once("v").ok_or(None)?;
        let idx: u64 = idx.parse()?;
        let ver: u64 = ver.parse()?;
        Ok(slotmap::KeyData::from_ffi((ver << 32) | idx).into())
    }
}

impl VizNodeKey {
    /// A key for testing with index 1.
    #[cfg(test)]
    pub const TEST_KEY_1: Self = Self(slotmap::KeyData::from_ffi(0x0000008F00000001)); // `1v143`

    /// A key for testing with index 2.
    #[cfg(test)]
    pub const TEST_KEY_2: Self = Self(slotmap::KeyData::from_ffi(0x0000008F00000002)); // `2v143`
}

/// Edge information in the Hydro graph.
#[derive(Debug, Clone)]
pub struct HydroGraphEdge {
    pub src: VizNodeKey,
    pub dst: VizNodeKey,
    pub edge_properties: HashSet<HydroEdgeProp>,
    pub label: Option<String>,
}

/// Graph structure tracker for Hydro IR rendering.
#[derive(Default)]
pub struct HydroGraphStructure {
    pub nodes: SlotMap<VizNodeKey, HydroGraphNode>,
    pub edges: Vec<HydroGraphEdge>,
    pub locations: SecondaryMap<LocationKey, LocationType>,
}

impl HydroGraphStructure {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_node(
        &mut self,
        label: NodeLabel,
        node_type: HydroNodeType,
        location_key: Option<LocationKey>,
    ) -> VizNodeKey {
        self.add_node_with_backtrace(label, node_type, location_key, None)
    }

    pub fn add_node_with_backtrace(
        &mut self,
        label: NodeLabel,
        node_type: HydroNodeType,
        location_key: Option<LocationKey>,
        backtrace: Option<Backtrace>,
    ) -> VizNodeKey {
        self.nodes.insert(HydroGraphNode {
            label,
            node_type,
            location_key,
            backtrace,
        })
    }

    /// Add a node with metadata, extracting backtrace automatically
    pub fn add_node_with_metadata(
        &mut self,
        label: NodeLabel,
        node_type: HydroNodeType,
        metadata: &HydroIrMetadata,
    ) -> VizNodeKey {
        let location_key = Some(setup_location(self, metadata));
        let backtrace = Some(metadata.op.backtrace.clone());
        self.add_node_with_backtrace(label, node_type, location_key, backtrace)
    }

    pub fn add_edge(
        &mut self,
        src: VizNodeKey,
        dst: VizNodeKey,
        edge_properties: HashSet<HydroEdgeProp>,
        label: Option<String>,
    ) {
        self.edges.push(HydroGraphEdge {
            src,
            dst,
            edge_properties,
            label,
        });
    }

    // Legacy method for backward compatibility
    pub fn add_edge_single(
        &mut self,
        src: VizNodeKey,
        dst: VizNodeKey,
        edge_type: HydroEdgeProp,
        label: Option<String>,
    ) {
        let mut properties = HashSet::new();
        properties.insert(edge_type);
        self.edges.push(HydroGraphEdge {
            src,
            dst,
            edge_properties: properties,
            label,
        });
    }

    pub fn add_location(&mut self, location_key: LocationKey, location_type: LocationType) {
        self.locations.insert(location_key, location_type);
    }
}

/// Function to extract an op_name from a print_root() result for use in labels.
pub fn extract_op_name(full_label: String) -> String {
    full_label
        .split('(')
        .next()
        .unwrap_or("unknown")
        .to_lowercase()
}

/// Extract a short, readable label from the full token stream label using print_root() style naming
pub fn extract_short_label(full_label: &str) -> String {
    // Use the same logic as extract_op_name but handle the specific cases we need for UI display
    if let Some(op_name) = full_label.split('(').next() {
        let base_name = op_name.to_lowercase();
        match base_name.as_str() {
            // Handle special cases for UI display
            "source" => {
                if full_label.contains("Iter") {
                    "source_iter".to_owned()
                } else if full_label.contains("Stream") {
                    "source_stream".to_owned()
                } else if full_label.contains("ExternalNetwork") {
                    "external_network".to_owned()
                } else if full_label.contains("Spin") {
                    "spin".to_owned()
                } else {
                    "source".to_owned()
                }
            }
            "network" => {
                if full_label.contains("deser") {
                    "network(recv)".to_owned()
                } else if full_label.contains("ser") {
                    "network(send)".to_owned()
                } else {
                    "network".to_owned()
                }
            }
            // For all other cases, just use the lowercase base name (same as extract_op_name)
            _ => base_name,
        }
    } else {
        // Fallback for labels that don't follow the pattern
        if full_label.len() > 20 {
            format!("{}...", &full_label[..17])
        } else {
            full_label.to_owned()
        }
    }
}

/// Helper function to set up location in structure from metadata.
fn setup_location(structure: &mut HydroGraphStructure, metadata: &HydroIrMetadata) -> LocationKey {
    let root = metadata.location_id.root();
    let location_key = root.key();
    let location_type = root.location_type().unwrap();
    structure.add_location(location_key, location_type);
    location_key
}

/// Helper function to add an edge with semantic tags extracted from metadata.
/// This function combines collection kind extraction with network detection.
fn add_edge_with_metadata(
    structure: &mut HydroGraphStructure,
    src_id: VizNodeKey,
    dst_id: VizNodeKey,
    src_metadata: Option<&HydroIrMetadata>,
    dst_metadata: Option<&HydroIrMetadata>,
    label: Option<String>,
) {
    let mut properties = HashSet::new();

    // Extract semantic tags from source metadata's collection kind
    if let Some(metadata) = src_metadata {
        properties.extend(extract_edge_properties_from_collection_kind(
            &metadata.collection_kind,
        ));
    }

    // Add network edge tag if locations differ
    if let (Some(src_meta), Some(dst_meta)) = (src_metadata, dst_metadata) {
        add_network_edge_tag(
            &mut properties,
            &src_meta.location_id,
            &dst_meta.location_id,
        );
    }

    // If no properties were extracted, default to Stream
    if properties.is_empty() {
        properties.insert(HydroEdgeProp::Stream);
    }

    structure.add_edge(src_id, dst_id, properties, label);
}

/// Helper function to write a graph structure using any GraphWrite implementation
fn write_graph_structure<W>(
    structure: &HydroGraphStructure,
    graph_write: W,
    config: HydroWriteConfig<'_>,
) -> Result<(), W::Err>
where
    W: HydroGraphWrite,
{
    let mut graph_write = graph_write;
    // Write the graph
    graph_write.write_prologue()?;

    // Write node definitions
    for (node_id, node) in structure.nodes.iter() {
        let location_type = node
            .location_key
            .and_then(|loc_key| structure.locations.get(loc_key))
            .copied();

        graph_write.write_node_definition(
            node_id,
            &node.label,
            node.node_type,
            node.location_key,
            location_type,
            node.backtrace.as_ref(),
        )?;
    }

    // Group nodes by location if requested
    if config.show_location_groups {
        let mut nodes_by_location = SecondaryMap::<LocationKey, Vec<VizNodeKey>>::new();
        for (node_id, node) in structure.nodes.iter() {
            if let Some(location_key) = node.location_key {
                nodes_by_location
                    .entry(location_key)
                    .expect("location was removed")
                    .or_default()
                    .push(node_id);
            }
        }

        for (location_key, node_ids) in nodes_by_location.iter() {
            if let Some(&location_type) = structure.locations.get(location_key) {
                graph_write.write_location_start(location_key, location_type)?;
                for &node_id in node_ids.iter() {
                    graph_write.write_node(node_id)?;
                }
                graph_write.write_location_end()?;
            }
        }
    }

    // Write edges
    for edge in structure.edges.iter() {
        graph_write.write_edge(
            edge.src,
            edge.dst,
            &edge.edge_properties,
            edge.label.as_deref(),
        )?;
    }

    graph_write.write_epilogue()?;
    Ok(())
}

impl HydroRoot {
    /// Build the graph structure by traversing the IR tree.
    pub fn build_graph_structure(
        &self,
        structure: &mut HydroGraphStructure,
        seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
        config: HydroWriteConfig<'_>,
    ) -> VizNodeKey {
        // Helper function for sink nodes to reduce duplication
        fn build_sink_node(
            structure: &mut HydroGraphStructure,
            seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
            config: HydroWriteConfig<'_>,
            input: &HydroNode,
            sink_metadata: Option<&HydroIrMetadata>,
            label: NodeLabel,
        ) -> VizNodeKey {
            let input_id = input.build_graph_structure(structure, seen_tees, config);

            // If no explicit metadata is provided, extract it from the input node
            let effective_metadata = if let Some(meta) = sink_metadata {
                Some(meta)
            } else {
                match input {
                    HydroNode::Placeholder => None,
                    // All other variants have metadata
                    _ => Some(input.metadata()),
                }
            };

            let location_key = effective_metadata.map(|m| setup_location(structure, m));
            let sink_id = structure.add_node_with_backtrace(
                label,
                HydroNodeType::Sink,
                location_key,
                effective_metadata.map(|m| m.op.backtrace.clone()),
            );

            // Extract semantic tags from input metadata
            let input_metadata = input.metadata();
            add_edge_with_metadata(
                structure,
                input_id,
                sink_id,
                Some(input_metadata),
                sink_metadata,
                None,
            );

            sink_id
        }

        match self {
            // Sink operations - semantic tags extracted from input metadata
            HydroRoot::ForEach { f, input, .. } => build_sink_node(
                structure,
                seen_tees,
                config,
                input,
                None,
                NodeLabel::with_exprs("for_each".to_owned(), vec![f.clone()]),
            ),

            HydroRoot::SendExternal {
                to_external_key,
                to_port_id,
                input,
                ..
            } => build_sink_node(
                structure,
                seen_tees,
                config,
                input,
                None,
                NodeLabel::with_exprs(
                    format!("send_external({}:{})", to_external_key, to_port_id),
                    vec![],
                ),
            ),

            HydroRoot::DestSink { sink, input, .. } => build_sink_node(
                structure,
                seen_tees,
                config,
                input,
                None,
                NodeLabel::with_exprs("dest_sink".to_owned(), vec![sink.clone()]),
            ),

            HydroRoot::CycleSink {
                cycle_id, input, ..
            } => build_sink_node(
                structure,
                seen_tees,
                config,
                input,
                None,
                NodeLabel::static_label(format!("cycle_sink({})", cycle_id)),
            ),

            HydroRoot::EmbeddedOutput { ident, input, .. } => build_sink_node(
                structure,
                seen_tees,
                config,
                input,
                None,
                NodeLabel::static_label(format!("embedded_output({})", ident)),
            ),

            HydroRoot::Null { input, .. } => build_sink_node(
                structure,
                seen_tees,
                config,
                input,
                None,
                NodeLabel::static_label("null".to_owned()),
            ),
        }
    }
}

impl HydroNode {
    /// Build the graph structure recursively for this node.
    pub fn build_graph_structure(
        &self,
        structure: &mut HydroGraphStructure,
        seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
        config: HydroWriteConfig<'_>,
    ) -> VizNodeKey {
        // Helper functions to reduce duplication, categorized by input/expression patterns

        /// Common parameters for transform builder functions to reduce argument count
        struct TransformParams<'a> {
            structure: &'a mut HydroGraphStructure,
            seen_tees: &'a mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
            config: HydroWriteConfig<'a>,
            input: &'a HydroNode,
            metadata: &'a HydroIrMetadata,
            op_name: String,
            node_type: HydroNodeType,
        }

        // Single-input transform with no expressions
        fn build_simple_transform(params: TransformParams) -> VizNodeKey {
            let input_id = params.input.build_graph_structure(
                params.structure,
                params.seen_tees,
                params.config,
            );
            let node_id = params.structure.add_node_with_metadata(
                NodeLabel::Static(params.op_name.to_string()),
                params.node_type,
                params.metadata,
            );

            // Extract semantic tags from input metadata
            let input_metadata = params.input.metadata();
            add_edge_with_metadata(
                params.structure,
                input_id,
                node_id,
                Some(input_metadata),
                Some(params.metadata),
                None,
            );

            node_id
        }

        // Single-input transform with one expression
        fn build_single_expr_transform(params: TransformParams, expr: &DebugExpr) -> VizNodeKey {
            let input_id = params.input.build_graph_structure(
                params.structure,
                params.seen_tees,
                params.config,
            );
            let node_id = params.structure.add_node_with_metadata(
                NodeLabel::with_exprs(params.op_name.to_string(), vec![expr.clone()]),
                params.node_type,
                params.metadata,
            );

            // Extract semantic tags from input metadata
            let input_metadata = params.input.metadata();
            add_edge_with_metadata(
                params.structure,
                input_id,
                node_id,
                Some(input_metadata),
                Some(params.metadata),
                None,
            );

            node_id
        }

        // Single-input transform with two expressions
        fn build_dual_expr_transform(
            params: TransformParams,
            expr1: &DebugExpr,
            expr2: &DebugExpr,
        ) -> VizNodeKey {
            let input_id = params.input.build_graph_structure(
                params.structure,
                params.seen_tees,
                params.config,
            );
            let node_id = params.structure.add_node_with_metadata(
                NodeLabel::with_exprs(
                    params.op_name.to_string(),
                    vec![expr1.clone(), expr2.clone()],
                ),
                params.node_type,
                params.metadata,
            );

            // Extract semantic tags from input metadata
            let input_metadata = params.input.metadata();
            add_edge_with_metadata(
                params.structure,
                input_id,
                node_id,
                Some(input_metadata),
                Some(params.metadata),
                None,
            );

            node_id
        }

        // Helper function for source nodes
        fn build_source_node(
            structure: &mut HydroGraphStructure,
            metadata: &HydroIrMetadata,
            label: String,
        ) -> VizNodeKey {
            structure.add_node_with_metadata(
                NodeLabel::Static(label),
                HydroNodeType::Source,
                metadata,
            )
        }

        match self {
            HydroNode::Placeholder => structure.add_node(
                NodeLabel::Static("PLACEHOLDER".to_owned()),
                HydroNodeType::Transform,
                None,
            ),

            HydroNode::Source {
                source, metadata, ..
            } => {
                let label = match source {
                    HydroSource::Stream(expr) => format!("source_stream({})", expr),
                    HydroSource::ExternalNetwork() => "external_network()".to_owned(),
                    HydroSource::Iter(expr) => format!("source_iter({})", expr),
                    HydroSource::Spin() => "spin()".to_owned(),
                    HydroSource::ClusterMembers(location_id, _) => {
                        format!(
                            "source_stream(cluster_membership_stream({:?}))",
                            location_id
                        )
                    }
                    HydroSource::Embedded(ident) => {
                        format!("embedded_input({})", ident)
                    }
                    HydroSource::EmbeddedSingleton(ident) => {
                        format!("embedded_singleton_input({})", ident)
                    }
                };
                build_source_node(structure, metadata, label)
            }

            HydroNode::SingletonSource {
                value,
                first_tick_only,
                metadata,
            } => {
                let label = if *first_tick_only {
                    format!("singleton_first_tick({})", value)
                } else {
                    format!("singleton({})", value)
                };
                build_source_node(structure, metadata, label)
            }

            HydroNode::ExternalInput {
                from_external_key,
                from_port_id,
                metadata,
                ..
            } => build_source_node(
                structure,
                metadata,
                format!("external_input({}:{})", from_external_key, from_port_id),
            ),

            HydroNode::CycleSource {
                cycle_id, metadata, ..
            } => build_source_node(structure, metadata, format!("cycle_source({})", cycle_id)),

            HydroNode::Tee { inner, metadata } => {
                let ptr = inner.as_ptr();
                if let Some(&existing_id) = seen_tees.get(&ptr) {
                    return existing_id;
                }

                let input_id = inner
                    .0
                    .borrow()
                    .build_graph_structure(structure, seen_tees, config);
                let tee_id = structure.add_node_with_metadata(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Tee,
                    metadata,
                );

                seen_tees.insert(ptr, tee_id);

                // Extract semantic tags from input
                let inner_borrow = inner.0.borrow();
                let input_metadata = inner_borrow.metadata();
                add_edge_with_metadata(
                    structure,
                    input_id,
                    tee_id,
                    Some(input_metadata),
                    Some(metadata),
                    None,
                );
                drop(inner_borrow);

                tee_id
            }

            HydroNode::Partition {
                inner, metadata, ..
            } => {
                let ptr = inner.as_ptr();
                if let Some(&existing_id) = seen_tees.get(&ptr) {
                    return existing_id;
                }

                let input_id = inner
                    .0
                    .borrow()
                    .build_graph_structure(structure, seen_tees, config);
                let partition_id = structure.add_node_with_metadata(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Tee,
                    metadata,
                );

                seen_tees.insert(ptr, partition_id);

                // Extract semantic tags from input
                let inner_borrow = inner.0.borrow();
                let input_metadata = inner_borrow.metadata();
                add_edge_with_metadata(
                    structure,
                    input_id,
                    partition_id,
                    Some(input_metadata),
                    Some(metadata),
                    None,
                );
                drop(inner_borrow);

                partition_id
            }

            // Non-deterministic operation
            HydroNode::ObserveNonDet {
                inner, metadata, ..
            } => build_simple_transform(TransformParams {
                structure,
                seen_tees,
                config,
                input: inner,
                metadata,
                op_name: extract_op_name(self.print_root()),
                node_type: HydroNodeType::NonDeterministic,
            }),

            // Transform operations with Stream edges - grouped by node/edge type
            HydroNode::Cast { inner, metadata }
            | HydroNode::DeferTick {
                input: inner,
                metadata,
            }
            | HydroNode::Enumerate {
                input: inner,
                metadata,
                ..
            }
            | HydroNode::Unique {
                input: inner,
                metadata,
            }
            | HydroNode::ResolveFutures {
                input: inner,
                metadata,
            }
            | HydroNode::ResolveFuturesBlocking {
                input: inner,
                metadata,
            }
            | HydroNode::ResolveFuturesOrdered {
                input: inner,
                metadata,
            } => build_simple_transform(TransformParams {
                structure,
                seen_tees,
                config,
                input: inner,
                metadata,
                op_name: extract_op_name(self.print_root()),
                node_type: HydroNodeType::Transform,
            }),

            // Aggregation operation - semantic tags extracted from metadata
            HydroNode::Sort {
                input: inner,
                metadata,
            } => build_simple_transform(TransformParams {
                structure,
                seen_tees,
                config,
                input: inner,
                metadata,
                op_name: extract_op_name(self.print_root()),
                node_type: HydroNodeType::Aggregation,
            }),

            // Single-expression Transform operations - grouped by node type
            HydroNode::Map { f, input, metadata }
            | HydroNode::Filter { f, input, metadata }
            | HydroNode::FlatMap { f, input, metadata }
            | HydroNode::FlatMapStreamBlocking { f, input, metadata }
            | HydroNode::FilterMap { f, input, metadata }
            | HydroNode::Inspect { f, input, metadata } => build_single_expr_transform(
                TransformParams {
                    structure,
                    seen_tees,
                    config,
                    input,
                    metadata,
                    op_name: extract_op_name(self.print_root()),
                    node_type: HydroNodeType::Transform,
                },
                f,
            ),

            // Single-expression Aggregation operations - grouped by node type
            HydroNode::Reduce { f, input, metadata }
            | HydroNode::ReduceKeyed { f, input, metadata } => build_single_expr_transform(
                TransformParams {
                    structure,
                    seen_tees,
                    config,
                    input,
                    metadata,
                    op_name: extract_op_name(self.print_root()),
                    node_type: HydroNodeType::Aggregation,
                },
                f,
            ),

            // Join-like operations with left/right edge labels - grouped by edge labeling
            HydroNode::Join {
                left,
                right,
                metadata,
            }
            | HydroNode::JoinHalf {
                left,
                right,
                metadata,
            }
            | HydroNode::CrossProduct {
                left,
                right,
                metadata,
            }
            | HydroNode::CrossSingleton {
                left,
                right,
                metadata,
            } => {
                let left_id = left.build_graph_structure(structure, seen_tees, config);
                let right_id = right.build_graph_structure(structure, seen_tees, config);
                let node_id = structure.add_node_with_metadata(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Join,
                    metadata,
                );

                // Extract semantic tags for left edge
                let left_metadata = left.metadata();
                add_edge_with_metadata(
                    structure,
                    left_id,
                    node_id,
                    Some(left_metadata),
                    Some(metadata),
                    Some("left".to_owned()),
                );

                // Extract semantic tags for right edge
                let right_metadata = right.metadata();
                add_edge_with_metadata(
                    structure,
                    right_id,
                    node_id,
                    Some(right_metadata),
                    Some(metadata),
                    Some("right".to_owned()),
                );

                node_id
            }

            // Join-like operations with pos/neg edge labels - grouped by edge labeling
            HydroNode::Difference {
                pos: left,
                neg: right,
                metadata,
            }
            | HydroNode::AntiJoin {
                pos: left,
                neg: right,
                metadata,
            } => {
                let left_id = left.build_graph_structure(structure, seen_tees, config);
                let right_id = right.build_graph_structure(structure, seen_tees, config);
                let node_id = structure.add_node_with_metadata(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Join,
                    metadata,
                );

                // Extract semantic tags for pos edge
                let left_metadata = left.metadata();
                add_edge_with_metadata(
                    structure,
                    left_id,
                    node_id,
                    Some(left_metadata),
                    Some(metadata),
                    Some("pos".to_owned()),
                );

                // Extract semantic tags for neg edge
                let right_metadata = right.metadata();
                add_edge_with_metadata(
                    structure,
                    right_id,
                    node_id,
                    Some(right_metadata),
                    Some(metadata),
                    Some("neg".to_owned()),
                );

                node_id
            }

            // Dual expression transforms - consolidated using pattern matching
            HydroNode::Fold {
                init,
                acc,
                input,
                metadata,
            }
            | HydroNode::FoldKeyed {
                init,
                acc,
                input,
                metadata,
            }
            | HydroNode::Scan {
                init,
                acc,
                input,
                metadata,
            }
            | HydroNode::ScanAsyncBlocking {
                init,
                acc,
                input,
                metadata,
            } => {
                let node_type = HydroNodeType::Aggregation; // All are aggregation operations

                build_dual_expr_transform(
                    TransformParams {
                        structure,
                        seen_tees,
                        config,
                        input,
                        metadata,
                        op_name: extract_op_name(self.print_root()),
                        node_type,
                    },
                    init,
                    acc,
                )
            }

            // Combination of join and transform
            HydroNode::ReduceKeyedWatermark {
                f,
                input,
                watermark,
                metadata,
            } => {
                let input_id = input.build_graph_structure(structure, seen_tees, config);
                let watermark_id = watermark.build_graph_structure(structure, seen_tees, config);
                let location_key = Some(setup_location(structure, metadata));
                let join_node_id = structure.add_node_with_backtrace(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Join,
                    location_key,
                    Some(metadata.op.backtrace.clone()),
                );

                // Extract semantic tags for input edge
                let input_metadata = input.metadata();
                add_edge_with_metadata(
                    structure,
                    input_id,
                    join_node_id,
                    Some(input_metadata),
                    Some(metadata),
                    Some("input".to_owned()),
                );

                // Extract semantic tags for watermark edge
                let watermark_metadata = watermark.metadata();
                add_edge_with_metadata(
                    structure,
                    watermark_id,
                    join_node_id,
                    Some(watermark_metadata),
                    Some(metadata),
                    Some("watermark".to_owned()),
                );

                let node_id = structure.add_node_with_backtrace(
                    NodeLabel::with_exprs(extract_op_name(self.print_root()), vec![f.clone()]),
                    HydroNodeType::Aggregation,
                    location_key,
                    Some(metadata.op.backtrace.clone()),
                );

                // Edge from join to aggregation node
                let join_metadata = metadata; // Use the same metadata
                add_edge_with_metadata(
                    structure,
                    join_node_id,
                    node_id,
                    Some(join_metadata),
                    Some(metadata),
                    None,
                );

                node_id
            }

            HydroNode::Network {
                serialize_fn,
                deserialize_fn,
                input,
                metadata,
                ..
            } => {
                let input_id = input.build_graph_structure(structure, seen_tees, config);
                let _from_location_key = setup_location(structure, metadata);

                let root = metadata.location_id.root();
                let to_location_key = root.key();
                let to_location_type = root.location_type().unwrap();
                structure.add_location(to_location_key, to_location_type);

                let mut label = "network(".to_owned();
                if serialize_fn.is_some() {
                    label.push_str("send");
                }
                if deserialize_fn.is_some() {
                    if serialize_fn.is_some() {
                        label.push_str(" + ");
                    }
                    label.push_str("recv");
                }
                label.push(')');

                let network_id = structure.add_node_with_backtrace(
                    NodeLabel::Static(label),
                    HydroNodeType::Network,
                    Some(to_location_key),
                    Some(metadata.op.backtrace.clone()),
                );

                // Extract semantic tags for network edge
                let input_metadata = input.metadata();
                add_edge_with_metadata(
                    structure,
                    input_id,
                    network_id,
                    Some(input_metadata),
                    Some(metadata),
                    Some(format!("to {:?}({})", to_location_type, to_location_key)),
                );

                network_id
            }

            // Non-deterministic batch operation
            HydroNode::Batch { inner, metadata } => build_simple_transform(TransformParams {
                structure,
                seen_tees,
                config,
                input: inner,
                metadata,
                op_name: extract_op_name(self.print_root()),
                node_type: HydroNodeType::NonDeterministic,
            }),

            HydroNode::YieldConcat { inner, .. } => {
                // Unpersist is typically optimized away, just pass through
                inner.build_graph_structure(structure, seen_tees, config)
            }

            HydroNode::BeginAtomic { inner, .. } => {
                inner.build_graph_structure(structure, seen_tees, config)
            }

            HydroNode::EndAtomic { inner, .. } => {
                inner.build_graph_structure(structure, seen_tees, config)
            }

            HydroNode::Chain {
                first,
                second,
                metadata,
            } => {
                let first_id = first.build_graph_structure(structure, seen_tees, config);
                let second_id = second.build_graph_structure(structure, seen_tees, config);
                let location_key = Some(setup_location(structure, metadata));
                let chain_id = structure.add_node_with_backtrace(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Transform,
                    location_key,
                    Some(metadata.op.backtrace.clone()),
                );

                // Extract semantic tags for first edge
                let first_metadata = first.metadata();
                add_edge_with_metadata(
                    structure,
                    first_id,
                    chain_id,
                    Some(first_metadata),
                    Some(metadata),
                    Some("first".to_owned()),
                );

                // Extract semantic tags for second edge
                let second_metadata = second.metadata();
                add_edge_with_metadata(
                    structure,
                    second_id,
                    chain_id,
                    Some(second_metadata),
                    Some(metadata),
                    Some("second".to_owned()),
                );

                chain_id
            }

            HydroNode::ChainFirst {
                first,
                second,
                metadata,
            } => {
                let first_id = first.build_graph_structure(structure, seen_tees, config);
                let second_id = second.build_graph_structure(structure, seen_tees, config);
                let location_key = Some(setup_location(structure, metadata));
                let chain_id = structure.add_node_with_backtrace(
                    NodeLabel::Static(extract_op_name(self.print_root())),
                    HydroNodeType::Transform,
                    location_key,
                    Some(metadata.op.backtrace.clone()),
                );

                // Extract semantic tags for first edge
                let first_metadata = first.metadata();
                add_edge_with_metadata(
                    structure,
                    first_id,
                    chain_id,
                    Some(first_metadata),
                    Some(metadata),
                    Some("first".to_owned()),
                );

                // Extract semantic tags for second edge
                let second_metadata = second.metadata();
                add_edge_with_metadata(
                    structure,
                    second_id,
                    chain_id,
                    Some(second_metadata),
                    Some(metadata),
                    Some("second".to_owned()),
                );

                chain_id
            }

            HydroNode::Counter {
                tag: _,
                prefix: _,
                duration,
                input,
                metadata,
            } => build_single_expr_transform(
                TransformParams {
                    structure,
                    seen_tees,
                    config,
                    input,
                    metadata,
                    op_name: extract_op_name(self.print_root()),
                    node_type: HydroNodeType::Transform,
                },
                duration,
            ),
        }
    }
}

/// Utility functions for rendering multiple roots as a single graph.
/// Macro to reduce duplication in render functions.
macro_rules! render_hydro_ir {
    ($name:ident, $write_fn:ident) => {
        pub fn $name(roots: &[HydroRoot], config: HydroWriteConfig<'_>) -> String {
            let mut output = String::new();
            $write_fn(&mut output, roots, config).unwrap();
            output
        }
    };
}

/// Macro to reduce duplication in write functions.
macro_rules! write_hydro_ir {
    ($name:ident, $writer_type:ty, $constructor:expr) => {
        pub fn $name(
            output: impl std::fmt::Write,
            roots: &[HydroRoot],
            config: HydroWriteConfig<'_>,
        ) -> std::fmt::Result {
            let mut graph_write: $writer_type = $constructor(output, config);
            write_hydro_ir_graph(&mut graph_write, roots, config)
        }
    };
}

render_hydro_ir!(render_hydro_ir_mermaid, write_hydro_ir_mermaid);
write_hydro_ir!(
    write_hydro_ir_mermaid,
    HydroMermaid<_>,
    HydroMermaid::new_with_config
);

render_hydro_ir!(render_hydro_ir_dot, write_hydro_ir_dot);
write_hydro_ir!(write_hydro_ir_dot, HydroDot<_>, HydroDot::new_with_config);

// Legacy hydroscope function - now uses HydroJson for consistency
render_hydro_ir!(render_hydro_ir_hydroscope, write_hydro_ir_json);

// JSON rendering
render_hydro_ir!(render_hydro_ir_json, write_hydro_ir_json);
write_hydro_ir!(write_hydro_ir_json, HydroJson<_>, HydroJson::new);

fn write_hydro_ir_graph<W>(
    graph_write: W,
    roots: &[HydroRoot],
    config: HydroWriteConfig<'_>,
) -> Result<(), W::Err>
where
    W: HydroGraphWrite,
{
    let mut structure = HydroGraphStructure::new();
    let mut seen_tees = HashMap::new();

    // Build the graph structure for all roots
    for leaf in roots {
        leaf.build_graph_structure(&mut structure, &mut seen_tees, config);
    }

    write_graph_structure(&structure, graph_write, config)
}