interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
//! Aggregation steps for grouping and counting traversers.
//!
//! This module provides steps for aggregating traversers into groups:
//! - `GroupStep` - groups traversers by key and collects values
//! - `GroupCountStep` - counts traversers by group key
//!
//! Both steps are "barrier" steps that collect all input before producing output.

use std::collections::HashMap;
use std::marker::PhantomData;

use crate::traversal::step::{execute_traversal_from, DynStep, Step};
use crate::traversal::{ExecutionContext, Traversal, Traverser};
use crate::value::Value;

/// Convert a Value to a string key for use in Value::Map.
///
/// Value::Map uses String keys, so when we want to output a grouped result
/// as a Value::Map, we need to convert the grouped Value keys to strings.
/// This conversion happens only at the output stage, not during grouping.
#[inline]
fn value_to_map_key(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        Value::Int(n) => n.to_string(),
        Value::Float(f) => f.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Vertex(id) => format!("v[{}]", id.0),
        Value::Edge(id) => format!("e[{}]", id.0),
        Value::Null => "null".to_string(),
        Value::List(_) => "[list]".to_string(),
        Value::Map(_) => "[map]".to_string(),
        Value::Point(p) => p.to_string(),
        Value::Polygon(p) => p.to_string(),
    }
}

/// Specification for how to extract the grouping key from a traverser.
///
/// Used by `GroupStep` and `GroupCountStep` to determine which group
/// a traverser belongs to.
#[derive(Clone, Debug)]
pub enum GroupKey {
    /// Group by element label (vertex or edge label).
    Label,

    /// Group by a property value.
    Property(String),

    /// Group by the result of a traversal.
    Traversal(Box<Traversal<crate::Value, crate::Value>>),
}

impl GroupKey {
    /// Create a GroupKey that groups by label.
    #[inline]
    pub fn by_label() -> Self {
        GroupKey::Label
    }

    /// Create a GroupKey that groups by a property.
    #[inline]
    pub fn by_property(key: impl Into<String>) -> Self {
        GroupKey::Property(key.into())
    }

    /// Create a GroupKey that groups by a traversal result.
    #[inline]
    pub fn by_traversal(traversal: Traversal<crate::Value, crate::Value>) -> Self {
        GroupKey::Traversal(Box::new(traversal))
    }
}

/// Specification for how to collect values within a group.
///
/// Used by `GroupStep` to determine what value to store for each
/// traverser in a group.
#[derive(Clone, Debug)]
pub enum GroupValue {
    /// Use the traverser's current value directly (identity).
    Identity,

    /// Extract a property value from the traverser.
    Property(String),

    /// Apply a traversal to compute the group value (per-element).
    /// Each traverser's value is computed independently.
    Traversal(Box<Traversal<crate::Value, crate::Value>>),

    /// Apply a reducing/folding traversal to the entire group.
    /// All traversers in the group are fed into the traversal together,
    /// and the final result (e.g., from count(), sum(), dedup()) is used.
    /// This enables patterns like `.by(select('x').dedup().count())`.
    Fold(Box<Traversal<crate::Value, crate::Value>>),
}

impl GroupValue {
    /// Create a GroupValue that uses the identity (current value).
    pub fn identity() -> Self {
        GroupValue::Identity
    }

    /// Create a GroupValue that extracts a property.
    pub fn by_property(key: impl Into<String>) -> Self {
        GroupValue::Property(key.into())
    }

    /// Create a GroupValue that applies a traversal.
    pub fn by_traversal(traversal: Traversal<crate::Value, crate::Value>) -> Self {
        GroupValue::Traversal(Box::new(traversal))
    }
}

// -----------------------------------------------------------------------------
// GroupStep - barrier step that groups traversers
// -----------------------------------------------------------------------------

/// Barrier step that groups traversers by a key and collects values.
///
/// This is a **barrier step** - it collects ALL input before producing grouped output.
/// The result is a single traverser containing a `Value::Map` where:
/// - Keys are the grouping keys (as Values)
/// - Values are lists of collected values for each group
///
/// # Memory Warning
///
/// **This step requires O(n) memory** where n is the total number of input
/// traversers. All input values must be collected and stored in the group map.
/// For very large traversals with high cardinality grouping keys, this may
/// cause significant memory usage. Consider using `limit()` before `group()`
/// or filtering the traversal to reduce input size.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().group().by(label).by(values("name"))  // Group by label, collect names
/// g.V().group().by("age")  // Group by age property, collect vertices (identity)
/// ```
///
/// # Example
///
/// ```ignore
/// // Group vertices by label
/// let groups = g.v()
///     .group().by_label().by_value().build()
///     .next();
/// // Returns: Map { "person" -> [vertex1, vertex2], "software" -> [vertex3] }
///
/// // Group by property
/// let groups = g.v().has_label("person")
///     .group().by_key("age").by_value_key("name").build()
///     .next();
/// // Returns: Map { 29 -> ["Alice", "Bob"], 30 -> ["Charlie"] }
/// ```
#[derive(Clone)]
pub struct GroupStep {
    key_selector: GroupKey,
    value_collector: GroupValue,
}

impl GroupStep {
    /// Create a new GroupStep with default selectors (identity key, identity value).
    pub fn new() -> Self {
        Self {
            key_selector: GroupKey::Label,
            value_collector: GroupValue::Identity,
        }
    }

    /// Create a GroupStep with custom selectors.
    pub fn with_selectors(key_selector: GroupKey, value_collector: GroupValue) -> Self {
        Self {
            key_selector,
            value_collector,
        }
    }

    /// Extract the grouping key from a traverser.
    fn get_key(&self, ctx: &ExecutionContext, traverser: &Traverser) -> Option<Value> {
        match &self.key_selector {
            GroupKey::Label => {
                // Extract label from vertex or edge
                match &traverser.value {
                    Value::Vertex(id) => ctx
                        .storage()
                        .get_vertex(*id)
                        .map(|v| Value::String(v.label.clone())),
                    Value::Edge(id) => ctx
                        .storage()
                        .get_edge(*id)
                        .map(|e| Value::String(e.label.clone())),
                    _ => None,
                }
            }
            GroupKey::Property(key) => {
                // Extract property value
                match &traverser.value {
                    Value::Vertex(id) => ctx
                        .storage()
                        .get_vertex(*id)
                        .and_then(|v| v.properties.get(key).cloned()),
                    Value::Edge(id) => ctx
                        .storage()
                        .get_edge(*id)
                        .and_then(|e| e.properties.get(key).cloned()),
                    _ => None,
                }
            }
            GroupKey::Traversal(sub) => {
                // Execute sub-traversal and get first result
                execute_traversal_from(ctx, sub, Box::new(std::iter::once(traverser.clone())))
                    .next()
                    .map(|t| t.value)
            }
        }
    }

    /// Extract the value to collect from a traverser.
    fn get_value(&self, ctx: &ExecutionContext, traverser: &Traverser) -> Option<Value> {
        match &self.value_collector {
            GroupValue::Identity => {
                // Use the current value directly
                Some(traverser.value.clone())
            }
            GroupValue::Property(key) => {
                // Extract property value
                match &traverser.value {
                    Value::Vertex(id) => ctx
                        .storage()
                        .get_vertex(*id)
                        .and_then(|v| v.properties.get(key).cloned()),
                    Value::Edge(id) => ctx
                        .storage()
                        .get_edge(*id)
                        .and_then(|e| e.properties.get(key).cloned()),
                    _ => None,
                }
            }
            GroupValue::Traversal(sub) => {
                // Execute sub-traversal and collect all results
                let results: Vec<Value> =
                    execute_traversal_from(ctx, sub, Box::new(std::iter::once(traverser.clone())))
                        .map(|t| t.value)
                        .collect();

                if results.is_empty() {
                    None
                } else if results.len() == 1 {
                    Some(results.into_iter().next().unwrap())
                } else {
                    Some(Value::List(results))
                }
            }
            GroupValue::Fold(_) => {
                // Fold is handled specially in apply_with_fold, not here
                // If we get here, just use identity as fallback
                Some(traverser.value.clone())
            }
        }
    }

    /// Apply grouping with per-element value collection.
    /// Used for Identity, Property, and Traversal value collectors.
    fn apply_per_element<'a>(
        &'a self,
        ctx: &'a ExecutionContext<'a>,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> std::iter::Once<Traverser> {
        // Collect all input into groups (barrier)
        let mut groups: HashMap<Value, Vec<Value>> = HashMap::new();
        let mut last_path = None;

        for traverser in input {
            last_path = Some(traverser.path.clone());

            // Get the grouping key
            if let Some(key) = self.get_key(ctx, &traverser) {
                // Skip non-hashable keys (List, Map)
                if matches!(key, Value::List(_) | Value::Map(_)) {
                    continue;
                }

                // Get the value to collect
                if let Some(value) = self.get_value(ctx, &traverser) {
                    groups.entry(key).or_default().push(value);
                }
            }
        }

        // Convert groups to a single Value::Map
        let mut result_map: crate::value::ValueMap = crate::value::ValueMap::new();
        for (key, values) in groups {
            let key_str = value_to_map_key(&key);
            result_map.insert(key_str, Value::List(values));
        }

        // Emit a single traverser with the grouped result
        let result_value = Value::Map(result_map);
        let result_traverser = Traverser {
            value: result_value,
            path: last_path.unwrap_or_default(),
            loops: 0,
            sack: None,
            bulk: 1,
        };

        std::iter::once(result_traverser)
    }

    /// Apply grouping with a reducing/folding traversal per group.
    /// Used for Fold value collector - runs the traversal on ALL traversers in each group.
    fn apply_with_fold<'a>(
        &'a self,
        ctx: &'a ExecutionContext<'a>,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> std::iter::Once<Traverser> {
        // First, collect all traversers by their grouping key
        let mut groups: HashMap<Value, Vec<Traverser>> = HashMap::new();
        let mut last_path = None;

        for traverser in input {
            last_path = Some(traverser.path.clone());

            // Get the grouping key
            if let Some(key) = self.get_key(ctx, &traverser) {
                // Skip non-hashable keys (List, Map)
                if matches!(key, Value::List(_) | Value::Map(_)) {
                    continue;
                }

                groups.entry(key).or_default().push(traverser);
            }
        }

        // Now run the fold traversal on each group
        let fold_traversal = match &self.value_collector {
            GroupValue::Fold(t) => t.as_ref(),
            _ => unreachable!("apply_with_fold called without Fold value collector"),
        };

        let mut result_map: crate::value::ValueMap = crate::value::ValueMap::new();

        for (key, traversers) in groups {
            let key_str = value_to_map_key(&key);

            // Run the fold traversal on ALL traversers in this group
            let fold_input = Box::new(traversers.into_iter());
            let fold_results: Vec<Value> = execute_traversal_from(ctx, fold_traversal, fold_input)
                .map(|t| t.value)
                .collect();

            // The fold result is typically a single value (from count(), sum(), etc.)
            // but could be multiple values - in that case, wrap in a List
            let fold_result = if fold_results.is_empty() {
                Value::Null
            } else if fold_results.len() == 1 {
                fold_results.into_iter().next().unwrap()
            } else {
                Value::List(fold_results)
            };

            result_map.insert(key_str, fold_result);
        }

        // Emit a single traverser with the grouped result
        let result_value = Value::Map(result_map);
        let result_traverser = Traverser {
            value: result_value,
            path: last_path.unwrap_or_default(),
            loops: 0,
            sack: None,
            bulk: 1,
        };

        std::iter::once(result_traverser)
    }
}

impl Default for GroupStep {
    fn default() -> Self {
        Self::new()
    }
}

impl Step for GroupStep {
    type Iter<'a>
        = std::iter::Once<Traverser>
    where
        Self: 'a;

    fn apply<'a>(
        &'a self,
        ctx: &'a ExecutionContext<'a>,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> Self::Iter<'a> {
        // Check if we're using a Fold value collector - requires different grouping strategy
        let is_fold = matches!(self.value_collector, GroupValue::Fold(_));

        if is_fold {
            // For Fold: collect traversers by key, then run fold traversal per group
            self.apply_with_fold(ctx, input)
        } else {
            // For Identity/Property/Traversal: collect values per-element
            self.apply_per_element(ctx, input)
        }
    }

    fn name(&self) -> &'static str {
        "group"
    }

    fn is_barrier(&self) -> bool {
        true
    }

    fn category(&self) -> crate::traversal::explain::StepCategory {
        crate::traversal::explain::StepCategory::Aggregation
    }

    fn apply_streaming(
        &self,
        _ctx: crate::traversal::context::StreamingContext,
        input: Traverser,
    ) -> Box<dyn Iterator<Item = Traverser> + Send + 'static> {
        // BARRIER STEP: GroupStep cannot truly stream because it must collect ALL inputs
        // before producing any output. Grouping requires seeing every value to know which
        // group it belongs to. The output is a single Map containing all groups.
        // This is fundamentally incompatible with O(1) streaming semantics.
        // Current behavior: pass-through (incorrect but safe for pipeline compatibility).
        Box::new(std::iter::once(input))
    }
}

// -----------------------------------------------------------------------------
// GroupBuilder - fluent API for building GroupStep
// -----------------------------------------------------------------------------

/// Fluent builder for creating GroupStep.
///
/// The builder allows configuring both the grouping key and the value collector
/// using `by` methods.
///
/// # Example
///
/// ```ignore
/// // Group by label, collect identity values
/// let groups = g.v()
///     .group().by_label().by_value().build()
///     .next();
///
/// // Group by property, collect other property
/// let groups = g.v().has_label("person")
///     .group().by_key("age").by_value_key("name").build()
///     .next();
/// ```
pub struct GroupBuilder<In> {
    steps: Vec<Box<dyn DynStep>>,
    key_selector: Option<GroupKey>,
    value_collector: Option<GroupValue>,
    _phantom: PhantomData<In>,
}

impl<In> GroupBuilder<In> {
    /// Create a new GroupBuilder with existing steps.
    pub(crate) fn new(steps: Vec<Box<dyn DynStep>>) -> Self {
        Self {
            steps,
            key_selector: None,
            value_collector: None,
            _phantom: PhantomData,
        }
    }

    /// Group by element label.
    pub fn by_label(mut self) -> Self {
        self.key_selector = Some(GroupKey::Label);
        self
    }

    /// Group by a property value.
    pub fn by_key(mut self, key: &str) -> Self {
        self.key_selector = Some(GroupKey::Property(key.to_string()));
        self
    }

    /// Group by the result of a sub-traversal.
    pub fn by_traversal(mut self, t: Traversal<Value, Value>) -> Self {
        self.key_selector = Some(GroupKey::Traversal(Box::new(t)));
        self
    }

    /// Collect identity values (the traverser's current value).
    pub fn by_value(mut self) -> Self {
        self.value_collector = Some(GroupValue::Identity);
        self
    }

    /// Collect property values.
    pub fn by_value_key(mut self, key: &str) -> Self {
        self.value_collector = Some(GroupValue::Property(key.to_string()));
        self
    }

    /// Collect values from a sub-traversal.
    pub fn by_value_traversal(mut self, t: Traversal<Value, Value>) -> Self {
        self.value_collector = Some(GroupValue::Traversal(Box::new(t)));
        self
    }

    /// Collect values using a reducing/folding traversal.
    ///
    /// Unlike `by_value_traversal()` which applies the traversal to each element
    /// independently, `by_value_fold()` runs the traversal on ALL traversers in
    /// each group together. This enables patterns like:
    ///
    /// ```groovy
    /// .group().by(select('key')).by(select('categories').dedup().count())
    /// ```
    ///
    /// The fold traversal typically ends with a reducing step like `count()`,
    /// `sum()`, `min()`, `max()`, or uses `dedup()` to aggregate unique values.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Count unique categories per customer
    /// g.v().has_label("Person")
    ///     .group()
    ///     .by_traversal(__.select_one("customer"))
    ///     .by_value_fold(__.select_one("category").dedup().count())
    ///     .build()
    /// ```
    pub fn by_value_fold(mut self, t: Traversal<Value, Value>) -> Self {
        self.value_collector = Some(GroupValue::Fold(Box::new(t)));
        self
    }

    /// Build the final traversal with the GroupStep.
    pub fn build(mut self) -> Traversal<In, Value> {
        // Default to label for key, identity for value
        let key_selector = self.key_selector.unwrap_or(GroupKey::Label);
        let value_collector = self.value_collector.unwrap_or(GroupValue::Identity);

        let group_step = GroupStep::with_selectors(key_selector, value_collector);
        self.steps.push(Box::new(group_step));

        Traversal {
            steps: self.steps,
            source: None,
            _phantom: PhantomData,
        }
    }
}

// -----------------------------------------------------------------------------
// BoundGroupBuilder - fluent API for bound traversals
// -----------------------------------------------------------------------------

/// Fluent builder for creating GroupStep for bound traversals.
///
/// This builder is returned from `BoundTraversal::group()` and allows chaining
/// configuration methods before calling `build()` to get back a `BoundTraversal`.
///
/// # Example
///
/// ```ignore
/// let groups = g.v().has_label("person")
///     .group()
///     .by_key("age")
///     .by_value_key("name")
///     .build()
///     .next();
/// ```
pub struct BoundGroupBuilder<'g, In> {
    snapshot: &'g dyn crate::traversal::SnapshotLike,
    source: Option<crate::traversal::TraversalSource>,
    steps: Vec<Box<dyn DynStep>>,
    key_selector: Option<GroupKey>,
    value_collector: Option<GroupValue>,
    track_paths: bool,
    _phantom: PhantomData<In>,
}

impl<'g, In> BoundGroupBuilder<'g, In> {
    /// Create a new BoundGroupBuilder with existing steps and graph references.
    pub(crate) fn new(
        snapshot: &'g dyn crate::traversal::SnapshotLike,
        source: Option<crate::traversal::TraversalSource>,
        steps: Vec<Box<dyn DynStep>>,
        track_paths: bool,
    ) -> Self {
        Self {
            snapshot,
            source,
            steps,
            key_selector: None,
            value_collector: None,
            track_paths,
            _phantom: PhantomData,
        }
    }

    /// Group by element label.
    pub fn by_label(mut self) -> Self {
        self.key_selector = Some(GroupKey::Label);
        self
    }

    /// Group by a property value.
    pub fn by_key(mut self, key: &str) -> Self {
        self.key_selector = Some(GroupKey::Property(key.to_string()));
        self
    }

    /// Group by the result of a sub-traversal.
    pub fn by_traversal(mut self, t: Traversal<Value, Value>) -> Self {
        self.key_selector = Some(GroupKey::Traversal(Box::new(t)));
        self
    }

    /// Collect identity values (the traverser's current value).
    pub fn by_value(mut self) -> Self {
        self.value_collector = Some(GroupValue::Identity);
        self
    }

    /// Collect property values.
    pub fn by_value_key(mut self, key: &str) -> Self {
        self.value_collector = Some(GroupValue::Property(key.to_string()));
        self
    }

    /// Collect values from a sub-traversal.
    pub fn by_value_traversal(mut self, t: Traversal<Value, Value>) -> Self {
        self.value_collector = Some(GroupValue::Traversal(Box::new(t)));
        self
    }

    /// Collect values using a reducing/folding traversal.
    ///
    /// Unlike `by_value_traversal()` which applies the traversal to each element
    /// independently, `by_value_fold()` runs the traversal on ALL traversers in
    /// each group together. This enables patterns like:
    ///
    /// ```groovy
    /// .group().by(select('key')).by(select('categories').dedup().count())
    /// ```
    ///
    /// The fold traversal typically ends with a reducing step like `count()`,
    /// `sum()`, `min()`, `max()`, or uses `dedup()` to aggregate unique values.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Count unique categories per customer
    /// g.v().has_label("Person")
    ///     .group()
    ///     .by_traversal(__.select_one("customer"))
    ///     .by_value_fold(__.select_one("category").dedup().count())
    ///     .build()
    /// ```
    pub fn by_value_fold(mut self, t: Traversal<Value, Value>) -> Self {
        self.value_collector = Some(GroupValue::Fold(Box::new(t)));
        self
    }

    /// Build the final bound traversal with the GroupStep.
    pub fn build(mut self) -> crate::traversal::source::BoundTraversal<'g, In, Value> {
        // Default to label for key, identity for value
        let key_selector = self.key_selector.unwrap_or(GroupKey::Label);
        let value_collector = self.value_collector.unwrap_or(GroupValue::Identity);

        let group_step = GroupStep::with_selectors(key_selector, value_collector);
        self.steps.push(Box::new(group_step));

        let traversal = Traversal {
            steps: self.steps,
            source: self.source,
            _phantom: PhantomData,
        };

        let mut bound = crate::traversal::source::BoundTraversal::new(self.snapshot, traversal);

        // Preserve track_paths by conditionally calling with_path()
        if self.track_paths {
            bound = bound.with_path();
        }

        bound
    }
}

// -----------------------------------------------------------------------------
// GroupCountStep - barrier step that counts traversers by key
// -----------------------------------------------------------------------------

/// Barrier step that counts traversers grouped by a key.
///
/// This is a **barrier step** - it collects ALL input before producing counted output.
/// The result is a single traverser containing a `Value::Map` where:
/// - Keys are the grouping keys (as Values)
/// - Values are integer counts (respecting traverser bulk)
///
/// # Memory Usage
///
/// **This step requires O(k) memory** where k is the number of unique keys,
/// not the total input size. Unlike `GroupStep`, only counts are stored per
/// key (not all values), making it more memory-efficient for large traversals.
/// However, for high-cardinality keys (many unique values), memory usage will
/// still scale with the number of unique keys.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().groupCount().by(label)      // Count vertices by label
/// g.V().groupCount().by("age")      // Count vertices by age property
/// g.E().groupCount().by(label)      // Count edges by label
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::*;
/// use interstellar::traversal::__; // Anonymous traversal factory
///
/// let graph = Graph::new(/* ... */);
/// let snapshot = graph.snapshot();
/// let g = snapshot.gremlin();
///
/// // Count vertices by label
/// let counts = g.v().group_count().by_label().build().to_list();
/// // => [Map {"person" => 3, "software" => 1}]
///
/// // Count vertices by age property
/// let age_counts = g.v().has_label("person").group_count().by_key("age").build().to_list();
/// // => [Map {29 => 2, 30 => 1}]
/// ```
#[derive(Clone, Debug)]
pub struct GroupCountStep {
    key_selector: GroupKey,
}

impl GroupCountStep {
    /// Create a new GroupCountStep with the specified key selector.
    pub fn new(key_selector: GroupKey) -> Self {
        GroupCountStep { key_selector }
    }

    /// Extract the grouping key from a traverser.
    ///
    /// Returns `None` if the key cannot be extracted or is not hashable.
    fn get_key(&self, ctx: &ExecutionContext, traverser: &Traverser) -> Option<Value> {
        match &self.key_selector {
            GroupKey::Label => match &traverser.value {
                Value::Vertex(id) => ctx
                    .storage()
                    .get_vertex(*id)
                    .map(|v| Value::String(v.label.clone())),
                Value::Edge(id) => ctx
                    .storage()
                    .get_edge(*id)
                    .map(|e| Value::String(e.label.clone())),
                _ => None,
            },
            GroupKey::Property(key) => match &traverser.value {
                Value::Vertex(id) => ctx
                    .storage()
                    .get_vertex(*id)
                    .and_then(|v| v.properties.get(key).cloned()),
                Value::Edge(id) => ctx
                    .storage()
                    .get_edge(*id)
                    .and_then(|e| e.properties.get(key).cloned()),
                _ => None,
            },
            GroupKey::Traversal(t) => {
                // Execute the traversal on the current traverser
                let results =
                    execute_traversal_from(ctx, t, Box::new(std::iter::once(traverser.clone())));
                results.into_iter().next().map(|t| t.value)
            }
        }
    }
}

impl Step for GroupCountStep {
    type Iter<'a>
        = std::iter::Once<Traverser>
    where
        Self: 'a;

    fn apply<'a>(
        &'a self,
        ctx: &'a ExecutionContext,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> Self::Iter<'a> {
        // Collect all input and count by group key
        // Use Value directly as key since it implements Hash + Eq
        let mut counts: HashMap<Value, i64> = HashMap::new();
        let mut last_path = None;

        for traverser in input {
            last_path = Some(traverser.path.clone());

            if let Some(key_value) = self.get_key(ctx, &traverser) {
                // Skip non-hashable keys (List, Map) - while Value does implement Hash,
                // using complex nested structures as keys is semantically questionable
                // and matches Gremlin's behavior
                if matches!(key_value, Value::List(_) | Value::Map(_)) {
                    continue;
                }

                // Increment count by traverser bulk
                *counts.entry(key_value).or_insert(0) += traverser.bulk as i64;
            }
        }

        // Convert counts to a single Value::Map
        // Value::Map uses String keys, so convert Value keys to strings
        let mut result_map: crate::value::ValueMap = crate::value::ValueMap::new();
        for (key, count) in counts {
            let key_str = value_to_map_key(&key);
            result_map.insert(key_str, Value::Int(count));
        }

        // Emit a single traverser with the counted result
        let result_value = Value::Map(result_map);
        let result_traverser = Traverser {
            value: result_value,
            path: last_path.unwrap_or_default(),
            loops: 0,
            sack: None,
            bulk: 1,
        };

        std::iter::once(result_traverser)
    }

    fn name(&self) -> &'static str {
        "groupCount"
    }

    fn is_barrier(&self) -> bool {
        true
    }

    fn category(&self) -> crate::traversal::explain::StepCategory {
        crate::traversal::explain::StepCategory::Aggregation
    }

    fn apply_streaming(
        &self,
        _ctx: crate::traversal::context::StreamingContext,
        input: Traverser,
    ) -> Box<dyn Iterator<Item = Traverser> + Send + 'static> {
        // BARRIER STEP: GroupCountStep cannot truly stream because it must count ALL inputs
        // before producing any output. The output is a single Map of group -> count pairs.
        // This is fundamentally incompatible with O(1) streaming semantics.
        // Current behavior: pass-through (incorrect but safe for pipeline compatibility).
        Box::new(std::iter::once(input))
    }
}

// -----------------------------------------------------------------------------
// GroupCountBuilder - fluent API for building GroupCountStep
// -----------------------------------------------------------------------------

/// Fluent builder for creating GroupCountStep.
///
/// The builder allows configuring the grouping key using `by` methods.
/// Unlike `GroupBuilder`, there is no value collector since we always count.
///
/// # Example
///
/// ```ignore
/// use interstellar::*;
///
/// let graph = Graph::new(/* ... */);
/// let snapshot = graph.snapshot();
/// let g = snapshot.gremlin();
///
/// // Count by label
/// g.v().group_count().by_label().build();
///
/// // Count by property
/// g.v().group_count().by_key("age").build();
/// ```
pub struct GroupCountBuilder<In> {
    steps: Vec<Box<dyn DynStep>>,
    key_selector: Option<GroupKey>,
    _phantom: PhantomData<In>,
}

impl<In> GroupCountBuilder<In> {
    /// Create a new GroupCountBuilder with existing steps.
    pub(crate) fn new(steps: Vec<Box<dyn DynStep>>) -> Self {
        GroupCountBuilder {
            steps,
            key_selector: None,
            _phantom: PhantomData,
        }
    }

    /// Group by element label (vertex or edge label).
    pub fn by_label(mut self) -> Self {
        self.key_selector = Some(GroupKey::Label);
        self
    }

    /// Group by a property value.
    pub fn by_key(mut self, key: &str) -> Self {
        self.key_selector = Some(GroupKey::Property(key.to_string()));
        self
    }

    /// Group by the result of a traversal.
    pub fn by_traversal(mut self, traversal: Traversal<Value, Value>) -> Self {
        self.key_selector = Some(GroupKey::Traversal(Box::new(traversal)));
        self
    }

    /// Build the final traversal with the GroupCountStep.
    ///
    /// If no key selector is specified, defaults to grouping by identity (the traverser value itself).
    pub fn build(self) -> Traversal<In, Value> {
        let key_selector = self.key_selector.unwrap_or(GroupKey::Label);
        let mut steps = self.steps;
        steps.push(Box::new(GroupCountStep::new(key_selector)));
        Traversal {
            steps,
            source: None,
            _phantom: PhantomData,
        }
    }
}

// -----------------------------------------------------------------------------
// BoundGroupCountBuilder - for bound traversals
// -----------------------------------------------------------------------------

/// Builder for `group_count()` on `BoundTraversal`.
///
/// This builder preserves the graph snapshot reference and path tracking state
/// when building the final `BoundTraversal`.
pub struct BoundGroupCountBuilder<'g, In> {
    snapshot: &'g dyn crate::traversal::SnapshotLike,
    source: Option<crate::traversal::TraversalSource>,
    steps: Vec<Box<dyn DynStep>>,
    key_selector: Option<GroupKey>,
    track_paths: bool,
    _phantom: PhantomData<In>,
}

impl<'g, In> BoundGroupCountBuilder<'g, In> {
    /// Create a new BoundGroupCountBuilder.
    pub(crate) fn new(
        snapshot: &'g dyn crate::traversal::SnapshotLike,
        source: Option<crate::traversal::TraversalSource>,
        steps: Vec<Box<dyn DynStep>>,
        track_paths: bool,
    ) -> Self {
        BoundGroupCountBuilder {
            snapshot,
            source,
            steps,
            key_selector: None,
            track_paths,
            _phantom: PhantomData,
        }
    }

    /// Group by element label.
    pub fn by_label(mut self) -> Self {
        self.key_selector = Some(GroupKey::Label);
        self
    }

    /// Group by a property value.
    pub fn by_key(mut self, key: &str) -> Self {
        self.key_selector = Some(GroupKey::Property(key.to_string()));
        self
    }

    /// Group by the result of a traversal.
    pub fn by_traversal(mut self, traversal: Traversal<Value, Value>) -> Self {
        self.key_selector = Some(GroupKey::Traversal(Box::new(traversal)));
        self
    }

    /// Build the final BoundTraversal with the GroupCountStep.
    pub fn build(self) -> crate::traversal::BoundTraversal<'g, In, Value> {
        let key_selector = self.key_selector.unwrap_or(GroupKey::Label);
        let mut steps = self.steps;
        steps.push(Box::new(GroupCountStep::new(key_selector)));

        let traversal = Traversal {
            steps,
            source: self.source,
            _phantom: PhantomData,
        };

        let mut bound = crate::traversal::source::BoundTraversal::new(self.snapshot, traversal);

        // Preserve track_paths by conditionally calling with_path()
        if self.track_paths {
            bound = bound.with_path();
        }

        bound
    }
}

// -----------------------------------------------------------------------------
// CountStep - reducing step that counts traversers
// -----------------------------------------------------------------------------

/// Reducing step that counts all input traversers.
///
/// This is a **reducing step** - it consumes ALL input and produces a single
/// traverser containing the count as a `Value::Int`. The count respects
/// traverser bulk, so a traverser with `bulk=5` contributes 5 to the count.
///
/// # Performance
///
/// This step uses streaming evaluation - it does not store traversers in memory,
/// only accumulates a running count. Memory usage is O(1) regardless of input size.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().count()           // Count all vertices
/// g.V().out().count()     // Count all outgoing neighbors
/// g.E().count()           // Count all edges
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::*;
///
/// let graph = Graph::new();
/// // ... add vertices ...
/// let snapshot = graph.snapshot();
/// let g = snapshot.gremlin();
///
/// // Count all vertices
/// let count: u64 = g.v().count();
///
/// // Count with filters
/// let person_count: u64 = g.v().has_label("person").count();
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct CountStep;

impl CountStep {
    /// Create a new CountStep.
    #[inline]
    pub fn new() -> Self {
        Self
    }
}

impl Step for CountStep {
    type Iter<'a>
        = std::iter::Once<Traverser>
    where
        Self: 'a;

    fn apply<'a>(
        &'a self,
        _ctx: &'a ExecutionContext<'a>,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> Self::Iter<'a> {
        // Stream through input, summing bulk values
        // This is O(1) memory - we only keep a running count
        let count: i64 = input.map(|t| t.bulk as i64).sum();
        std::iter::once(Traverser::new(Value::Int(count)))
    }

    fn name(&self) -> &'static str {
        "count"
    }

    fn is_barrier(&self) -> bool {
        true
    }

    fn category(&self) -> crate::traversal::explain::StepCategory {
        crate::traversal::explain::StepCategory::Aggregation
    }

    fn apply_streaming(
        &self,
        _ctx: crate::traversal::context::StreamingContext,
        input: Traverser,
    ) -> Box<dyn Iterator<Item = Traverser> + Send + 'static> {
        // BARRIER STEP: CountStep cannot truly stream because it must count ALL inputs
        // before producing a single output. The output is a single Int value.
        // Current behavior: pass-through (incorrect but safe for pipeline compatibility).
        Box::new(std::iter::once(input))
    }
}

// -----------------------------------------------------------------------------
// MinStep - reducing step that finds minimum value
// -----------------------------------------------------------------------------

/// Reducing step that finds the minimum value among all input traversers.
///
/// This is a **reducing step** - it consumes ALL input and produces a single
/// traverser containing the minimum value. Only numeric and string values
/// can be compared; other types are skipped.
///
/// # Comparison Rules
///
/// - `Int` values are compared numerically
/// - `Float` values are compared numerically (NaN is treated as greater than all)
/// - `String` values are compared lexicographically
/// - Mixed types: `Int` < `Float` < `String`
/// - Non-comparable types (`Null`, `Bool`, `List`, `Map`, `Vertex`, `Edge`) are skipped
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().values("age").min()    // Find minimum age
/// g.V().values("name").min()   // Find lexicographically smallest name
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::*;
///
/// let graph = Graph::new();
/// // ... add vertices with age properties ...
/// let snapshot = graph.snapshot();
/// let g = snapshot.gremlin();
///
/// // Find minimum age
/// let min_age = g.v().values("age").min().next();
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct MinStep;

impl MinStep {
    /// Create a new MinStep.
    #[inline]
    pub fn new() -> Self {
        Self
    }

    /// Compare two values for ordering.
    /// Returns None if values are not comparable.
    fn compare_values(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
        use std::cmp::Ordering;
        match (a, b) {
            (Value::Int(x), Value::Int(y)) => Some(x.cmp(y)),
            (Value::Float(x), Value::Float(y)) => x.partial_cmp(y),
            (Value::String(x), Value::String(y)) => Some(x.cmp(y)),
            // Mixed numeric types: convert to float for comparison
            (Value::Int(x), Value::Float(y)) => (*x as f64).partial_cmp(y),
            (Value::Float(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)),
            // Int < Float < String for cross-type comparison
            (Value::Int(_), Value::String(_)) => Some(Ordering::Less),
            (Value::String(_), Value::Int(_)) => Some(Ordering::Greater),
            (Value::Float(_), Value::String(_)) => Some(Ordering::Less),
            (Value::String(_), Value::Float(_)) => Some(Ordering::Greater),
            // Non-comparable types
            _ => None,
        }
    }
}

impl Step for MinStep {
    type Iter<'a>
        = std::iter::Once<Traverser>
    where
        Self: 'a;

    fn apply<'a>(
        &'a self,
        _ctx: &'a ExecutionContext<'a>,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> Self::Iter<'a> {
        let mut min_value: Option<Value> = None;
        let mut last_path = None;

        for t in input {
            last_path = Some(t.path.clone());

            // Skip non-comparable values
            if !matches!(t.value, Value::Int(_) | Value::Float(_) | Value::String(_)) {
                continue;
            }

            min_value = match min_value {
                None => Some(t.value),
                Some(current) => {
                    if let Some(ord) = Self::compare_values(&t.value, &current) {
                        if ord == std::cmp::Ordering::Less {
                            Some(t.value)
                        } else {
                            Some(current)
                        }
                    } else {
                        Some(current)
                    }
                }
            };
        }

        // Return the minimum value, or Null if no comparable values found
        let result = min_value.unwrap_or(Value::Null);
        let mut traverser = Traverser::new(result);
        if let Some(path) = last_path {
            traverser.path = path;
        }
        std::iter::once(traverser)
    }

    fn name(&self) -> &'static str {
        "min"
    }

    fn is_barrier(&self) -> bool {
        true
    }

    fn category(&self) -> crate::traversal::explain::StepCategory {
        crate::traversal::explain::StepCategory::Aggregation
    }

    fn apply_streaming(
        &self,
        _ctx: crate::traversal::context::StreamingContext,
        input: Traverser,
    ) -> Box<dyn Iterator<Item = Traverser> + Send + 'static> {
        // BARRIER STEP: MinStep cannot truly stream because it must see ALL inputs
        // Current behavior: pass-through (incorrect but safe for pipeline compatibility).
        Box::new(std::iter::once(input))
    }
}

// -----------------------------------------------------------------------------
// MaxStep - reducing step that finds maximum value
// -----------------------------------------------------------------------------

/// Reducing step that finds the maximum value among all input traversers.
///
/// This is a **reducing step** - it consumes ALL input and produces a single
/// traverser containing the maximum value. Only numeric and string values
/// can be compared; other types are skipped.
///
/// # Comparison Rules
///
/// - `Int` values are compared numerically
/// - `Float` values are compared numerically (NaN is treated as greater than all)
/// - `String` values are compared lexicographically
/// - Mixed types: `Int` < `Float` < `String`
/// - Non-comparable types (`Null`, `Bool`, `List`, `Map`, `Vertex`, `Edge`) are skipped
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().values("age").max()    // Find maximum age
/// g.V().values("name").max()   // Find lexicographically largest name
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::*;
///
/// let graph = Graph::new();
/// // ... add vertices with age properties ...
/// let snapshot = graph.snapshot();
/// let g = snapshot.gremlin();
///
/// // Find maximum age
/// let max_age = g.v().values("age").max().next();
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct MaxStep;

impl MaxStep {
    /// Create a new MaxStep.
    #[inline]
    pub fn new() -> Self {
        Self
    }
}

impl Step for MaxStep {
    type Iter<'a>
        = std::iter::Once<Traverser>
    where
        Self: 'a;

    fn apply<'a>(
        &'a self,
        _ctx: &'a ExecutionContext<'a>,
        input: Box<dyn Iterator<Item = Traverser> + 'a>,
    ) -> Self::Iter<'a> {
        let mut max_value: Option<Value> = None;
        let mut last_path = None;

        for t in input {
            last_path = Some(t.path.clone());

            // Skip non-comparable values
            if !matches!(t.value, Value::Int(_) | Value::Float(_) | Value::String(_)) {
                continue;
            }

            max_value = match max_value {
                None => Some(t.value),
                Some(current) => {
                    if let Some(ord) = MinStep::compare_values(&t.value, &current) {
                        if ord == std::cmp::Ordering::Greater {
                            Some(t.value)
                        } else {
                            Some(current)
                        }
                    } else {
                        Some(current)
                    }
                }
            };
        }

        // Return the maximum value, or Null if no comparable values found
        let result = max_value.unwrap_or(Value::Null);
        let mut traverser = Traverser::new(result);
        if let Some(path) = last_path {
            traverser.path = path;
        }
        std::iter::once(traverser)
    }

    fn name(&self) -> &'static str {
        "max"
    }

    fn is_barrier(&self) -> bool {
        true
    }

    fn category(&self) -> crate::traversal::explain::StepCategory {
        crate::traversal::explain::StepCategory::Aggregation
    }

    fn apply_streaming(
        &self,
        _ctx: crate::traversal::context::StreamingContext,
        input: Traverser,
    ) -> Box<dyn Iterator<Item = Traverser> + Send + 'static> {
        // BARRIER STEP: MaxStep cannot truly stream because it must see ALL inputs
        // Current behavior: pass-through (incorrect but safe for pipeline compatibility).
        Box::new(std::iter::once(input))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::Graph;
    use crate::traversal::SnapshotLike;
    use std::collections::HashMap as StdHashMap;

    fn create_test_graph() -> Graph {
        let graph = Graph::new();

        // Add person vertices with different ages
        let mut props1 = StdHashMap::new();
        props1.insert("name".to_string(), Value::String("Alice".to_string()));
        props1.insert("age".to_string(), Value::Int(29));
        graph.add_vertex("person", props1);

        let mut props2 = StdHashMap::new();
        props2.insert("name".to_string(), Value::String("Bob".to_string()));
        props2.insert("age".to_string(), Value::Int(29));
        graph.add_vertex("person", props2);

        let mut props3 = StdHashMap::new();
        props3.insert("name".to_string(), Value::String("Charlie".to_string()));
        props3.insert("age".to_string(), Value::Int(30));
        graph.add_vertex("person", props3);

        // Add software vertices
        let mut props4 = StdHashMap::new();
        props4.insert("name".to_string(), Value::String("lop".to_string()));
        graph.add_vertex("software", props4);

        graph
    }

    #[test]
    fn test_group_by_label_identity() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group all vertices by label
        let result = g.v().group().by_label().by_value().build().next();

        assert!(result.is_some());
        let result = result.unwrap();

        // Should be a Map
        if let Value::Map(map) = result {
            // Should have "person" and "software" keys
            assert!(map.contains_key("person"));
            assert!(map.contains_key("software"));

            // Person group should have 3 vertices
            if let Some(Value::List(persons)) = map.get("person") {
                assert_eq!(persons.len(), 3);
                // All should be vertices
                for val in persons {
                    assert!(matches!(val, Value::Vertex(_)));
                }
            } else {
                panic!("Expected person group to be a list");
            }

            // Software group should have 1 vertex
            if let Some(Value::List(softwares)) = map.get("software") {
                assert_eq!(softwares.len(), 1);
                assert!(matches!(softwares[0], Value::Vertex(_)));
            } else {
                panic!("Expected software group to be a list");
            }
        } else {
            panic!("Expected Map value, got: {:?}", result);
        }
    }

    #[test]
    fn test_group_by_property_collect_property() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group people by age, collect names
        let result = g
            .v()
            .has_label("person")
            .group()
            .by_key("age")
            .by_value_key("name")
            .build()
            .next();

        assert!(result.is_some());
        let result = result.unwrap();

        if let Value::Map(map) = result {
            // Should have "29" and "30" keys
            assert!(map.contains_key("29") || map.contains_key("30"));

            // Age 29 should have Alice and Bob
            if let Some(Value::List(names)) = map.get("29") {
                assert_eq!(names.len(), 2);
                assert!(names.contains(&Value::String("Alice".to_string())));
                assert!(names.contains(&Value::String("Bob".to_string())));
            }

            // Age 30 should have Charlie
            if let Some(Value::List(names)) = map.get("30") {
                assert_eq!(names.len(), 1);
                assert!(names.contains(&Value::String("Charlie".to_string())));
            }
        } else {
            panic!("Expected Map value");
        }
    }

    #[test]
    fn test_group_default_selectors() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Use default selectors (by label, identity value)
        let result = g.v().group().build().next();

        assert!(result.is_some());
        let result = result.unwrap();

        // Should still be a Map grouped by label
        if let Value::Map(map) = result {
            assert!(map.contains_key("person"));
            assert!(map.contains_key("software"));
        } else {
            panic!("Expected Map value");
        }
    }

    #[test]
    fn test_group_builder_fluent_api() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Test fluent API chaining
        let result = g
            .v()
            .has_label("person")
            .group()
            .by_key("age")
            .by_value()
            .build()
            .next();

        assert!(result.is_some());

        if let Some(Value::Map(map)) = result {
            // Each group should have vertex values (identity)
            for (_, value) in map {
                if let Value::List(values) = value {
                    for val in values {
                        assert!(matches!(val, Value::Vertex(_)));
                    }
                }
            }
        }
    }

    #[test]
    fn test_group_empty_input() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Filter to no vertices, then group
        let result = g
            .v()
            .has_label("nonexistent")
            .group()
            .by_label()
            .by_value()
            .build()
            .next();

        // Should return empty map
        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            assert!(map.is_empty());
        }
    }

    // -------------------------------------------------------------------------
    // GroupCountStep Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_group_count_by_label() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count all vertices by label
        let result = g.v().group_count().by_label().build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should have 2 labels: "person" and "software"
            assert_eq!(map.len(), 2);
            assert_eq!(map.get("person"), Some(&Value::Int(3))); // 3 person vertices
            assert_eq!(map.get("software"), Some(&Value::Int(1))); // 1 software vertex
        } else {
            panic!("Expected Value::Map, got {:?}", result);
        }
    }

    #[test]
    fn test_group_count_by_property() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count person vertices by age property
        let result = g
            .v()
            .has_label("person")
            .group_count()
            .by_key("age")
            .build()
            .next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should have 2 ages: 29 and 30
            assert_eq!(map.len(), 2);
            assert_eq!(map.get("29"), Some(&Value::Int(2))); // Alice and Bob are 29
            assert_eq!(map.get("30"), Some(&Value::Int(1))); // Charlie is 30
        } else {
            panic!("Expected Value::Map, got {:?}", result);
        }
    }

    #[test]
    fn test_group_count_default_selector() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group count without specifying selector (should default to label)
        let result = g.v().group_count().build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should group by label by default
            assert_eq!(map.len(), 2);
            assert_eq!(map.get("person"), Some(&Value::Int(3)));
            assert_eq!(map.get("software"), Some(&Value::Int(1)));
        } else {
            panic!("Expected Value::Map, got {:?}", result);
        }
    }

    #[test]
    fn test_group_count_empty_input() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Filter to no vertices, then group count
        let result = g
            .v()
            .has_label("nonexistent")
            .group_count()
            .by_label()
            .build()
            .next();

        // Should return empty map
        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            assert!(map.is_empty());
        } else {
            panic!("Expected Value::Map, got {:?}", result);
        }
    }

    #[test]
    fn test_group_count_respects_bulk() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = GroupCountStep::new(GroupKey::Label);

        // Create traversers with different bulk values
        let mut t1 = Traverser::from_vertex(crate::value::VertexId(0)); // person
        t1.bulk = 5;

        let mut t2 = Traverser::from_vertex(crate::value::VertexId(1)); // person
        t2.bulk = 3;

        let mut t3 = Traverser::from_vertex(crate::value::VertexId(3)); // software
        t3.bulk = 2;

        let input = vec![t1, t2, t3];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        if let Value::Map(map) = &result[0].value {
            // person count should be 5 + 3 = 8
            assert_eq!(map.get("person"), Some(&Value::Int(8)));
            // software count should be 2
            assert_eq!(map.get("software"), Some(&Value::Int(2)));
        } else {
            panic!("Expected Value::Map, got {:?}", result[0].value);
        }
    }

    // -------------------------------------------------------------------------
    // GroupStep - Advanced Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_group_by_traversal_key() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group by out-degree (count of outgoing edges)
        // Since our test graph has no edges, we'll use a simpler traversal
        // Group by the first character of name property
        let key_traversal = crate::traversal::__.values("name");

        let result = g
            .v()
            .has_label("person")
            .group()
            .by_traversal(key_traversal)
            .by_value()
            .build()
            .next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should group by name values
            assert!(!map.is_empty());
            // Each group should contain vertices
            for (_key, value) in map {
                if let Value::List(vertices) = value {
                    for v in vertices {
                        assert!(matches!(v, Value::Vertex(_)));
                    }
                }
            }
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_by_value_traversal() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group by label, collect age property values
        let value_traversal = crate::traversal::__.values("age");

        let result = g
            .v()
            .has_label("person")
            .group()
            .by_label()
            .by_value_traversal(value_traversal)
            .build()
            .next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should have "person" key
            if let Some(Value::List(ages)) = map.get("person") {
                // Should have 3 age values
                assert_eq!(ages.len(), 3);
                // All should be integers
                for age in ages {
                    assert!(matches!(age, Value::Int(_)));
                }
            } else {
                panic!("Expected person group with list of ages");
            }
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_edges_by_label() {
        let graph = Graph::new();

        // Create vertices
        let mut props1 = StdHashMap::new();
        props1.insert("name".to_string(), Value::String("v1".to_string()));
        let v1 = graph.add_vertex("person", props1);

        let mut props2 = StdHashMap::new();
        props2.insert("name".to_string(), Value::String("v2".to_string()));
        let v2 = graph.add_vertex("person", props2);

        let mut props3 = StdHashMap::new();
        props3.insert("name".to_string(), Value::String("v3".to_string()));
        let v3 = graph.add_vertex("software", props3);

        // Create edges
        graph.add_edge(v1, v2, "knows", StdHashMap::new()).unwrap();

        graph
            .add_edge(v1, v3, "created", StdHashMap::new())
            .unwrap();

        graph
            .add_edge(v2, v3, "created", StdHashMap::new())
            .unwrap();

        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group all edges by label
        let result = g.e().group().by_label().by_value().build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should have "knows" and "created" groups
            assert_eq!(map.len(), 2);

            if let Some(Value::List(knows_edges)) = map.get("knows") {
                assert_eq!(knows_edges.len(), 1);
                assert!(matches!(knows_edges[0], Value::Edge(_)));
            } else {
                panic!("Expected knows edges");
            }

            if let Some(Value::List(created_edges)) = map.get("created") {
                assert_eq!(created_edges.len(), 2);
                for edge in created_edges {
                    assert!(matches!(edge, Value::Edge(_)));
                }
            } else {
                panic!("Expected created edges");
            }
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_edges_by_property() {
        let graph = Graph::new();

        let v0 = graph.add_vertex("person", StdHashMap::new());
        let v1 = graph.add_vertex("person", StdHashMap::new());

        // Create edges with weight property
        let mut edge1_props = StdHashMap::new();
        edge1_props.insert("weight".to_string(), Value::Float(0.5));
        graph.add_edge(v0, v1, "knows", edge1_props).unwrap();

        let mut edge2_props = StdHashMap::new();
        edge2_props.insert("weight".to_string(), Value::Float(0.8));
        graph.add_edge(v1, v0, "knows", edge2_props).unwrap();

        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group edges by weight property
        let result = g.e().group().by_key("weight").by_value().build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should have two groups by weight
            assert_eq!(map.len(), 2);
            assert!(map.contains_key("0.5") || map.contains_key("0.8"));
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_preserves_path() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Create traversal with path tracking
        let result = g
            .v()
            .has_label("person")
            .with_path()
            .group()
            .by_label()
            .by_value()
            .build()
            .next();

        assert!(result.is_some());
        // The result should exist - path tracking doesn't affect grouping
        if let Some(Value::Map(_map)) = result {
            // Success - grouping worked with path tracking enabled
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_with_bulk_traversers() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = GroupStep::with_selectors(GroupKey::Label, GroupValue::Identity);

        // Create traversers with bulk > 1
        let mut t1 = Traverser::from_vertex(crate::value::VertexId(0)); // person
        t1.bulk = 3;

        let mut t2 = Traverser::from_vertex(crate::value::VertexId(1)); // person
        t2.bulk = 2;

        let input = vec![t1, t2];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        if let Value::Map(map) = &result[0].value {
            if let Some(Value::List(persons)) = map.get("person") {
                // Should have 2 vertex values (one per input traverser)
                // Note: GroupStep doesn't expand by bulk, it just collects values
                assert_eq!(persons.len(), 2);
            } else {
                panic!("Expected person group");
            }
        } else {
            panic!("Expected Value::Map");
        }
    }

    // -------------------------------------------------------------------------
    // GroupCountStep - Advanced Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_group_count_by_traversal() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count by name property value
        let key_traversal = crate::traversal::__.values("name");

        let result = g
            .v()
            .has_label("person")
            .group_count()
            .by_traversal(key_traversal)
            .build()
            .next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should have 3 entries (Alice, Bob, Charlie)
            assert_eq!(map.len(), 3);
            // Each name should have count of 1
            assert_eq!(map.get("Alice"), Some(&Value::Int(1)));
            assert_eq!(map.get("Bob"), Some(&Value::Int(1)));
            assert_eq!(map.get("Charlie"), Some(&Value::Int(1)));
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_count_edges_by_label() {
        let graph = Graph::new();

        let v0 = graph.add_vertex("person", StdHashMap::new());
        let v1 = graph.add_vertex("person", StdHashMap::new());
        let v2 = graph.add_vertex("software", StdHashMap::new());

        // Create edges
        graph.add_edge(v0, v1, "knows", StdHashMap::new()).unwrap();

        graph
            .add_edge(v0, v2, "created", StdHashMap::new())
            .unwrap();

        graph
            .add_edge(v1, v2, "created", StdHashMap::new())
            .unwrap();

        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count edges by label
        let result = g.e().group_count().by_label().build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            assert_eq!(map.len(), 2);
            assert_eq!(map.get("knows"), Some(&Value::Int(1)));
            assert_eq!(map.get("created"), Some(&Value::Int(2)));
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_count_edges_by_property() {
        let graph = Graph::new();

        let v0 = graph.add_vertex("person", StdHashMap::new());
        let v1 = graph.add_vertex("person", StdHashMap::new());

        // Create edges with weight property
        let mut edge1_props = StdHashMap::new();
        edge1_props.insert("weight".to_string(), Value::Float(0.5));
        graph.add_edge(v0, v1, "knows", edge1_props).unwrap();

        let mut edge2_props = StdHashMap::new();
        edge2_props.insert("weight".to_string(), Value::Float(0.5));
        graph.add_edge(v1, v0, "knows", edge2_props).unwrap();

        let mut edge3_props = StdHashMap::new();
        edge3_props.insert("weight".to_string(), Value::Float(0.8));
        graph.add_edge(v0, v1, "likes", edge3_props).unwrap();

        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count edges by weight property
        let result = g.e().group_count().by_key("weight").build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            assert_eq!(map.len(), 2);
            assert_eq!(map.get("0.5"), Some(&Value::Int(2)));
            assert_eq!(map.get("0.8"), Some(&Value::Int(1)));
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_count_preserves_path() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Create traversal with path tracking
        let result = g
            .v()
            .has_label("person")
            .with_path()
            .group_count()
            .by_label()
            .build()
            .next();

        assert!(result.is_some());
        // The result should exist - path tracking doesn't affect counting
        if let Some(Value::Map(map)) = result {
            assert_eq!(map.get("person"), Some(&Value::Int(3)));
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_count_multiple_bulk_values() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = GroupCountStep::new(GroupKey::Property("age".to_string()));

        // Create traversers with different bulk values
        let mut t1 = Traverser::from_vertex(crate::value::VertexId(0)); // Alice, age 29
        t1.bulk = 10;

        let mut t2 = Traverser::from_vertex(crate::value::VertexId(1)); // Bob, age 29
        t2.bulk = 5;

        let mut t3 = Traverser::from_vertex(crate::value::VertexId(2)); // Charlie, age 30
        t3.bulk = 3;

        let input = vec![t1, t2, t3];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        if let Value::Map(map) = &result[0].value {
            // Age 29 should have bulk 10 + 5 = 15
            assert_eq!(map.get("29"), Some(&Value::Int(15)));
            // Age 30 should have bulk 3
            assert_eq!(map.get("30"), Some(&Value::Int(3)));
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_count_with_missing_property() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count by a property that doesn't exist on all vertices
        let result = g.v().group_count().by_key("nonexistent").build().next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should return empty map since no vertices have this property
            assert!(map.is_empty());
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_with_missing_property() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Group by a property that doesn't exist on all vertices
        let result = g
            .v()
            .group()
            .by_key("nonexistent")
            .by_value()
            .build()
            .next();

        assert!(result.is_some());
        if let Some(Value::Map(map)) = result {
            // Should return empty map since no vertices have this property
            assert!(map.is_empty());
        } else {
            panic!("Expected Value::Map");
        }
    }

    #[test]
    fn test_group_step_construction() {
        let step = GroupStep::new();
        assert_eq!(step.name(), "group");

        let step2 = GroupStep::with_selectors(
            GroupKey::Property("age".to_string()),
            GroupValue::Property("name".to_string()),
        );
        assert_eq!(step2.name(), "group");
    }

    #[test]
    fn test_group_count_step_construction() {
        let step = GroupCountStep::new(GroupKey::Label);
        assert_eq!(step.name(), "groupCount");

        let step2 = GroupCountStep::new(GroupKey::Property("age".to_string()));
        assert_eq!(step2.name(), "groupCount");
    }

    // -------------------------------------------------------------------------
    // CountStep Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_count_step_construction() {
        let step = CountStep::new();
        assert_eq!(step.name(), "count");

        let step_default = CountStep::default();
        assert_eq!(step_default.name(), "count");
    }

    #[test]
    fn test_count_step_empty_input() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = CountStep::new();
        let input: Vec<Traverser> = vec![];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].value, Value::Int(0));
    }

    #[test]
    fn test_count_step_single_traverser() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = CountStep::new();
        let input = vec![Traverser::from_vertex(crate::value::VertexId(0))];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].value, Value::Int(1));
    }

    #[test]
    fn test_count_step_multiple_traversers() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = CountStep::new();
        let input = vec![
            Traverser::from_vertex(crate::value::VertexId(0)),
            Traverser::from_vertex(crate::value::VertexId(1)),
            Traverser::from_vertex(crate::value::VertexId(2)),
            Traverser::from_vertex(crate::value::VertexId(3)),
        ];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].value, Value::Int(4));
    }

    #[test]
    fn test_count_step_respects_bulk() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let ctx = ExecutionContext::new(snapshot.storage(), snapshot.interner());

        let step = CountStep::new();

        // Create traversers with different bulk values
        let mut t1 = Traverser::from_vertex(crate::value::VertexId(0));
        t1.bulk = 5;

        let mut t2 = Traverser::from_vertex(crate::value::VertexId(1));
        t2.bulk = 3;

        let mut t3 = Traverser::from_vertex(crate::value::VertexId(2));
        t3.bulk = 2;

        let input = vec![t1, t2, t3];

        let result: Vec<Traverser> = step.apply(&ctx, Box::new(input.into_iter())).collect();

        assert_eq!(result.len(), 1);
        // Count should be 5 + 3 + 2 = 10
        assert_eq!(result[0].value, Value::Int(10));
    }

    #[test]
    fn test_count_step_clone_box() {
        let step = CountStep::new();
        let cloned = step.clone_box();
        assert_eq!(cloned.dyn_name(), "count");
    }

    #[test]
    fn test_count_step_is_copy() {
        let step = CountStep;
        let copied = step; // Copy, not move
        assert_eq!(step.name(), "count");
        assert_eq!(copied.name(), "count");
    }

    #[test]
    fn test_count_via_bound_traversal() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count all vertices (4 in test graph)
        let count = g.v().count();
        assert_eq!(count, 4);
    }

    #[test]
    fn test_count_with_filter() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count only person vertices (3 in test graph)
        let count = g.v().has_label("person").count();
        assert_eq!(count, 3);

        // Count only software vertices (1 in test graph)
        let count = g.v().has_label("software").count();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_count_empty_result() {
        let graph = create_test_graph();
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count vertices with non-existent label
        let count = g.v().has_label("nonexistent").count();
        assert_eq!(count, 0);
    }

    #[test]
    fn test_count_edges() {
        let graph = Graph::new();

        let v0 = graph.add_vertex("person", StdHashMap::new());
        let v1 = graph.add_vertex("person", StdHashMap::new());
        let v2 = graph.add_vertex("software", StdHashMap::new());

        graph.add_edge(v0, v1, "knows", StdHashMap::new()).unwrap();
        graph
            .add_edge(v0, v2, "created", StdHashMap::new())
            .unwrap();
        graph
            .add_edge(v1, v2, "created", StdHashMap::new())
            .unwrap();

        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        // Count all edges
        let count = g.e().count();
        assert_eq!(count, 3);

        // Count only "knows" edges
        let count = g.e().has_label("knows").count();
        assert_eq!(count, 1);

        // Count only "created" edges
        let count = g.e().has_label("created").count();
        assert_eq!(count, 2);
    }
}