graphersal 0.1.0

In-memory graph traversal engine modelled on Apache TinkerPop Gremlin, with a Rhai DSL, optimizer and GraphSON/GraphML I/O
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
use core::fmt;

use crate::error::TraverserResult;
use crate::graph::{GraphNodeType, GraphStorage};
use crate::traversal::{
    AnonymousTraversal, ArgsModulation, By, ByModulation, Traverser, TraverserContext,
};

pub(crate) mod profile;
pub(crate) use profile::*;

pub mod append_steps;
pub mod barrier_steps;
pub mod filter_steps;
pub mod flatbarrier_steps;
pub mod flatmap_steps;
pub(crate) mod local_scope;
pub mod map_steps;
pub mod modulator_steps;
pub(crate) mod order_clauses;
pub(crate) mod path_window;
pub(crate) mod prop_path;
pub mod sideeffect_steps;
pub mod start_steps;

pub(crate) enum GraphStep<'g, S: GraphStorage + 'g> {
    Init(&'static str, Box<dyn GraphStepInit<'g, S> + 'g>),
    Append(&'static str, Box<dyn GraphStepAppend<'g, S> + 'g>),
    Map(&'static str, Box<dyn GraphStepMap<'g, S> + 'g>),
    FlatMap(&'static str, Box<dyn GraphStepFlatMap<'g, S> + 'g>),
    Barrier(&'static str, Box<dyn GraphStepBarrier<'g, S> + 'g>),
    FlatBarrier(&'static str, Box<dyn GraphStepFlatBarrier<'g, S> + 'g>),
    Filter(&'static str, Box<dyn GraphStepFilter<'g, S> + 'g>),
    As(&'static str, Box<dyn GraphStepAs<'g, S> + 'g>),
    SideEffect(&'static str, Box<dyn GraphStepSideEffect<'g, S> + 'g>),
    SideEffectMut(&'static str, Box<dyn GraphStepSideEffectMut<'g, S> + 'g>),
    Modulator(&'static str, Box<dyn GraphStepModulator<'g, S> + 'g>),
    Count(&'static str, Box<dyn GraphStepCount<'g, S> + 'g>),
}

impl<'g, S: GraphStorage + 'g> Clone for GraphStep<'g, S> {
    fn clone(&self) -> Self {
        match self {
            GraphStep::Init(n, s) => GraphStep::Init(n, s.clone_box()),
            GraphStep::Append(n, s) => GraphStep::Append(n, s.clone_box()),
            GraphStep::Map(n, s) => GraphStep::Map(n, s.clone_box()),
            GraphStep::FlatMap(n, s) => GraphStep::FlatMap(n, s.clone_box()),
            GraphStep::Barrier(n, s) => GraphStep::Barrier(n, s.clone_box()),
            GraphStep::FlatBarrier(n, s) => GraphStep::FlatBarrier(n, s.clone_box()),
            GraphStep::Filter(n, s) => GraphStep::Filter(n, s.clone_box()),
            GraphStep::As(n, s) => GraphStep::As(n, s.clone_box()),
            GraphStep::SideEffect(n, s) => GraphStep::SideEffect(n, s.clone_box()),
            GraphStep::SideEffectMut(n, s) => GraphStep::SideEffectMut(n, s.clone_box()),
            GraphStep::Modulator(n, s) => GraphStep::Modulator(n, s.clone_box()),
            GraphStep::Count(n, s) => GraphStep::Count(n, s.clone_box()),
        }
    }
}

impl<'g, S: GraphStorage + 'g> GraphStep<'g, S> {
    /// The canonical rendering of this step: ONE text that reads like the DSL call building it,
    /// in snake_case (`has_label("person")`, `where(__.out())`, `order().by("age", Order.desc)`),
    /// fused and optimizer-inserted steps under the name the profile documents
    /// (`v(labels: ["person"]).count()`, `lazy_barrier()`). It is what `.profile()`, error step
    /// locations and the `help()` rewrites of the failing query show; the camelCase spelling is
    /// derived from it (`traversal::spelling::respell`). Never `Debug` (rule 14).
    pub fn get_name(&self) -> String {
        match self {
            GraphStep::Init(_, step) => step.get_name(),
            GraphStep::Append(_, step) => step.get_name(),
            GraphStep::Map(_, step) => step.get_name(),
            GraphStep::FlatMap(_, step) => step.get_name(),
            GraphStep::Barrier(_, step) => step.get_name(),
            GraphStep::FlatBarrier(_, step) => step.get_name(),
            GraphStep::Filter(_, step) => step.get_name(),
            GraphStep::As(_, step) => step.get_name(),
            GraphStep::SideEffect(_, step) => step.get_name(),
            GraphStep::SideEffectMut(_, step) => step.get_name(),
            GraphStep::Modulator(_, step) => step.to_string(),
            GraphStep::Count(_, step) => step.to_string(),
        }
    }

    /// The child traversals this step holds, in their canonical order. This is the single
    /// definition of the child numbering behind step ids (`Metrics::id` of `.profile()` and the
    /// location of an execution error, `<step>.<child>.<step>...`): the step's own traversal
    /// arguments first, in argument order (`union()`/`coalesce()`/`and()`/`or()` branches, the
    /// `where()`/`not()`/`filter()`/`local()`/`optional()` body, the `repeat()` body, the
    /// `choose()` selector), then its modulator children in attachment order (`by()`,
    /// `option()` keys and branches, `until()`/`emit()`). The optimizer reaches every child
    /// through it too ([`Self::optimize_nested`]), so a child is never optimized but unnumbered.
    pub(crate) fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        match self {
            GraphStep::Init(_, step) => step.child_traversals_mut(),
            GraphStep::Append(_, step) => step.child_traversals_mut(),
            GraphStep::Map(_, step) => step.child_traversals_mut(),
            GraphStep::FlatMap(_, step) => step.child_traversals_mut(),
            GraphStep::Barrier(_, step) => step.child_traversals_mut(),
            GraphStep::FlatBarrier(_, step) => step.child_traversals_mut(),
            GraphStep::Filter(_, step) => step.child_traversals_mut(),
            GraphStep::As(_, step) => step.child_traversals_mut(),
            GraphStep::SideEffect(_, step) => step.child_traversals_mut(),
            GraphStep::SideEffectMut(_, step) => step.child_traversals_mut(),
            GraphStep::Modulator(_, step) => step.child_traversals_mut(),
            GraphStep::Count(_, step) => step.child_traversals_mut(),
        }
    }

    /// Optimizes every child traversal of this step (see [`Self::child_traversals_mut`]).
    pub(crate) fn optimize_nested(
        &mut self,
        optimizer: &crate::traversal::optimizer::TraversalOptimizer<'g, S>,
    ) {
        for child in self.child_traversals_mut() {
            child.optimize(optimizer);
        }
    }

    /// Stores in every child traversal of every step of `steps` (recursively) its position among
    /// the children of the step holding it, the `<child>` segment of a step id. Runs once per
    /// execution on the optimized plan, before any step executes.
    pub(crate) fn number_children(steps: &mut [GraphStep<'g, S>]) {
        for step in steps {
            for (index, child) in step.child_traversals_mut().into_iter().enumerate() {
                child.child_index = index;
                Self::number_children(&mut child.steps);
            }
        }
    }
}

impl<'g, S: GraphStorage + 'g> GraphStep<'g, S> {
    /// Hands `from()`/`to()` arguments to this step; see [`ArgsModulation`]. Categories without
    /// the hook never take one.
    pub(crate) fn push_modulator_args(
        &mut self,
        args: Vec<String>,
        modulator_name: &str,
    ) -> ArgsModulation {
        match self {
            GraphStep::Init(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::Map(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::FlatMap(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::Barrier(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::FlatBarrier(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::Filter(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::SideEffect(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::SideEffectMut(_, step) => step.push_modulator_args(args, modulator_name),
            GraphStep::Append(_, _)
            | GraphStep::As(_, _)
            | GraphStep::Modulator(_, _)
            | GraphStep::Count(_, _) => ArgsModulation::Unsupported,
        }
    }

    /// Hands a `from(__...)`/`to(__...)` child traversal to this step; see [`ArgsModulation`].
    /// Only mutating steps (`add_e()`) take one.
    pub(crate) fn push_modulator_traversal(
        &mut self,
        child: AnonymousTraversal<'g, S>,
        modulator_name: &str,
    ) -> ArgsModulation {
        match self {
            GraphStep::SideEffectMut(_, step) => {
                step.push_modulator_traversal(child, modulator_name)
            }
            _ => ArgsModulation::Unsupported,
        }
    }

    /// Fails when this is a rejected-modulator marker (`StepModulatorRejected`), a mutating
    /// step whose build-time problem `plan_check()` reports (an invalid constant `mergeV()` map),
    /// or a map step whose `plan_check()` reports one (a `math()` equation that does not parse);
    /// every other step is unaffected. Used by the plan-time validation pass
    /// (`optimizer::path_analysis::PathAnalysis`) to find such a problem before execution, even
    /// inside a child traversal that never runs.
    pub(crate) fn modulator_check(&self) -> TraverserResult<()> {
        match self {
            GraphStep::Modulator(_, step) => step.check(),
            GraphStep::SideEffectMut(_, step) => step.plan_check(),
            GraphStep::Map(_, step) => step.plan_check(),
            GraphStep::Filter(_, step) => step.plan_check(),
            GraphStep::Init(_, _)
            | GraphStep::Append(_, _)
            | GraphStep::FlatMap(_, _)
            | GraphStep::Barrier(_, _)
            | GraphStep::FlatBarrier(_, _)
            | GraphStep::As(_, _)
            | GraphStep::SideEffect(_, _)
            | GraphStep::Count(_, _) => Ok(()),
        }
    }

    /// Hands a `by()` modulator to this step; see [`ByModulation`]. Categories without the hook
    /// never take one.
    pub(crate) fn push_modulator_by(
        &mut self,
        by: By<'g, S>,
        modulator_name: &str,
    ) -> ByModulation {
        match self {
            GraphStep::Init(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::Map(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::FlatMap(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::Barrier(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::FlatBarrier(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::Filter(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::SideEffect(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::SideEffectMut(_, step) => step.push_modulator_by(by, modulator_name),
            GraphStep::Append(_, _)
            | GraphStep::As(_, _)
            | GraphStep::Modulator(_, _)
            | GraphStep::Count(_, _) => ByModulation::Unsupported,
        }
    }

    /// Hands a step-level `with(WithOptions..)` option to this step: `None` when the step took
    /// it, otherwise the `InvalidModulator` reason. Only `valueMap()` and `index()` take one.
    pub(crate) fn push_with_option(
        &mut self,
        key: crate::value::WithOptions,
        value: Option<crate::value::WithOptions>,
    ) -> Option<String> {
        match self {
            GraphStep::Map(_, step) => step.push_with_option(key, value),
            GraphStep::Init(_, _)
            | GraphStep::FlatMap(_, _)
            | GraphStep::Barrier(_, _)
            | GraphStep::FlatBarrier(_, _)
            | GraphStep::Filter(_, _)
            | GraphStep::SideEffect(_, _)
            | GraphStep::SideEffectMut(_, _)
            | GraphStep::Append(_, _)
            | GraphStep::As(_, _)
            | GraphStep::Modulator(_, _)
            | GraphStep::Count(_, _) => {
                Some(crate::traversal::with_reason::NOT_ACCEPTED.to_string())
            }
        }
    }

    /// What this step reads from the path of its incoming traversers.
    pub(crate) fn path_requirement(
        &self,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        match self {
            GraphStep::Init(_, step) => step.path_requirement(),
            GraphStep::Append(_, step) => step.path_requirement(),
            GraphStep::Map(_, step) => step.path_requirement(),
            GraphStep::FlatMap(_, step) => step.path_requirement(),
            GraphStep::Barrier(_, step) => step.path_requirement(),
            GraphStep::FlatBarrier(_, step) => step.path_requirement(),
            GraphStep::Filter(_, step) => step.path_requirement(),
            GraphStep::As(_, step) => step.path_requirement(),
            GraphStep::SideEffect(_, step) => step.path_requirement(),
            GraphStep::SideEffectMut(_, step) => step.path_requirement(),
            GraphStep::Modulator(_, step) => step.path_requirement(),
            GraphStep::Count(_, step) => step.path_requirement(),
        }
    }

    /// Labels this step requires to resolve, declared somewhere in the query, together with the
    /// step's own name for the diagnostic; see `GraphStepMap::required_labels`. Only `Map` steps
    /// (`select()`) report anything today.
    pub(crate) fn required_labels(
        &self,
    ) -> Option<(Vec<compact_str::CompactString>, &'static str)> {
        match self {
            GraphStep::Map(name, step) => step.required_labels().map(|labels| (labels, *name)),
            GraphStep::Init(_, _)
            | GraphStep::Append(_, _)
            | GraphStep::FlatMap(_, _)
            | GraphStep::Barrier(_, _)
            | GraphStep::FlatBarrier(_, _)
            | GraphStep::Filter(_, _)
            | GraphStep::As(_, _)
            | GraphStep::SideEffect(_, _)
            | GraphStep::SideEffectMut(_, _)
            | GraphStep::Modulator(_, _)
            | GraphStep::Count(_, _) => None,
        }
    }

    /// The side-effect key this step declares (`aggregate`/`store`/`tree`), if any; see
    /// `GraphStepSideEffect::declares_side_effect_key`/`GraphStepBarrier::declares_side_effect_key`.
    pub(crate) fn declares_side_effect_key(&self) -> Option<&str> {
        match self {
            GraphStep::SideEffect(_, step) => step.declares_side_effect_key(),
            GraphStep::Barrier(_, step) => step.declares_side_effect_key(),
            GraphStep::FlatBarrier(_, step) => step.declares_side_effect_key(),
            GraphStep::Init(_, _)
            | GraphStep::Append(_, _)
            | GraphStep::Map(_, _)
            | GraphStep::FlatMap(_, _)
            | GraphStep::Filter(_, _)
            | GraphStep::As(_, _)
            | GraphStep::SideEffectMut(_, _)
            | GraphStep::Modulator(_, _)
            | GraphStep::Count(_, _) => None,
        }
    }

    /// What running this step itself does besides reading the graph, its child traversals not
    /// included (see [`Self::has_effects`] for the whole subtree): it mutates the graph
    /// (`SideEffectMut`, `drop()`), or writes a side effect (`SideEffect` — `aggregate`, `store`,
    /// `subgraph`, `sideEffect(fn)`, `profile` — or a step declaring a side-effect key, such as
    /// `tree("x")`). The single classification behind both the path analysis' `PlanEffects` and
    /// the optimizer rules that must not move effectful steps.
    pub(crate) fn own_effects(&self) -> crate::traversal::optimizer::path_analysis::PlanEffects {
        let mut effects = crate::traversal::optimizer::path_analysis::PlanEffects::default();
        if self.mutates() {
            effects.mutates = true;
        } else if matches!(self, GraphStep::SideEffect(_, _))
            || self.declares_side_effect_key().is_some()
        {
            effects.writes_side_effects = true;
        }
        effects
    }

    /// Calls `visit` with every [`AccessRequest`](crate::graph::AccessRequest) running this
    /// step itself makes, its child traversals not included, and stops at the first error. The
    /// single step -> request mapping: the authorization check (`permission_check.rs`), the
    /// path analysis' `mutates` ([`Self::own_effects`], via [`Self::mutates`]) and the script
    /// DSL's `is_mutating()` all derive from it.
    ///
    /// - `add_v(labels)` / `add_e(label)`: `Create` on `Data { Vertex | Edge, label }`, one
    ///   request per statically known label (`None` when the label comes from a traversal or is
    ///   absent);
    /// - `merge_v` / `merge_e`: `Create` and `Update` on `Data { Vertex | Edge, None }`;
    /// - `property`, `property_json`, `remove_property`: `Update` on `Data { None, None }`;
    /// - `add_label` / `drop_label`: `Update` on `Data { Vertex, None }`; `set_label`: `Update`
    ///   on `Data { Edge, None }` (the label of the changed element is not known from the plan);
    /// - `drop()`: `Delete` on `Data { None, None }`;
    /// - `schema()`: `Read` on `Schema`;
    /// - `v()` / `e()`: `Read` on `Data { Vertex | Edge, None }`; `out`/`in`/`both`: `Read` on
    ///   edges and on vertices; `out_e`/`in_e`/`both_e`: `Read` on edges;
    ///   `out_v`/`in_v`/`both_v`/`other_v`: `Read` on vertices; `subgraph()`: `Read` on
    ///   vertices (it copies the endpoints of the edges it receives);
    /// - every other step: nothing. Only steps that reach graph data (sources, adjacency) ask
    ///   for a read; a value-only step (`has`, `values`, `limit`, `count`, `inject`, `math`,
    ///   modulators, ...) works on what earlier steps produced, so `g.inject(1, 2).sum()` needs
    ///   no permission. An element handle held from an earlier, allowed run is read without a
    ///   further request (`g.inject(v).values("name")`).
    ///
    /// Labels of reads are not reported (label-level read security is a later storage
    /// decorator, see `book/src/users_guide/permissions.md`).
    pub(crate) fn for_each_access<E>(
        &self,
        mut visit: impl FnMut(crate::graph::AccessRequest<'_>) -> Result<(), E>,
    ) -> Result<(), E> {
        use crate::graph::{AccessRequest, Action, ElementKind, Resource};
        let vertex = Some(ElementKind::Vertex);
        let edge = Some(ElementKind::Edge);
        let read = |element| AccessRequest::new(Action::Read, Resource::data(element, None));
        match self {
            GraphStep::SideEffectMut(kind, step) => {
                let element = match *kind {
                    "add_v" | "merge_v" | "add_label" | "drop_label" => vertex,
                    "add_e" | "merge_e" | "set_label" => edge,
                    _ => None,
                };
                match *kind {
                    "add_v" | "add_e" => {
                        let labels = step.static_labels();
                        if labels.is_empty() {
                            return visit(AccessRequest::new(
                                Action::Create,
                                Resource::data(element, None),
                            ));
                        }
                        for label in labels {
                            visit(AccessRequest::new(
                                Action::Create,
                                Resource::data(element, Some(label)),
                            ))?;
                        }
                        Ok(())
                    }
                    "merge_v" | "merge_e" => {
                        visit(AccessRequest::new(
                            Action::Create,
                            Resource::data(element, None),
                        ))?;
                        visit(AccessRequest::new(
                            Action::Update,
                            Resource::data(element, None),
                        ))
                    }
                    _ => visit(AccessRequest::new(
                        Action::Update,
                        Resource::data(element, None),
                    )),
                }
            }
            GraphStep::Filter("drop", _) => visit(AccessRequest::new(
                Action::Delete,
                Resource::data(None, None),
            )),
            GraphStep::Barrier("infer_schema", _) => {
                visit(AccessRequest::new(Action::Read, Resource::Schema))
            }
            GraphStep::Init("v", _)
            | GraphStep::FlatMap("out_v" | "in_v" | "both_v" | "other_v", _) => visit(read(vertex)),
            GraphStep::Init("e", _) | GraphStep::FlatMap("out_e" | "in_e" | "both_e", _) => {
                visit(read(edge))
            }
            GraphStep::FlatMap("out" | "in" | "both", _) => {
                visit(read(edge))?;
                visit(read(vertex))
            }
            GraphStep::SideEffect("subgraph", _) => visit(read(vertex)),
            GraphStep::Init(_, _)
            | GraphStep::Append(_, _)
            | GraphStep::Map(_, _)
            | GraphStep::FlatMap(_, _)
            | GraphStep::Barrier(_, _)
            | GraphStep::FlatBarrier(_, _)
            | GraphStep::Filter(_, _)
            | GraphStep::As(_, _)
            | GraphStep::SideEffect(_, _)
            | GraphStep::Modulator(_, _)
            | GraphStep::Count(_, _) => Ok(()),
        }
    }

    /// Whether running this step itself changes the graph: one of its requests
    /// ([`Self::for_each_access`]) writes data or the schema.
    pub(crate) fn mutates(&self) -> bool {
        self.for_each_access(|request| {
            if request.writes_graph() {
                Err(())
            } else {
                Ok(())
            }
        })
        .is_err()
    }

    /// Whether running this step can be observed other than through its output stream: the step
    /// itself or any child traversal it holds, at any depth, mutates the graph or writes a side
    /// effect ([`Self::own_effects`]). How often and in which order such a step runs is part of
    /// the query's result (`g.V().filter(__.aggregate("x")).hasLabel("software").cap("x")`), so
    /// an optimizer rule must never reorder other steps across it or move it.
    pub(crate) fn has_effects(&mut self) -> bool {
        let own = self.own_effects();
        own.mutates
            || own.writes_side_effects
            || self
                .child_traversals_mut()
                .into_iter()
                .any(|child| child.steps.iter_mut().any(GraphStep::has_effects))
    }

    /// The static, `&'static str` kind name behind this step's category constructor (e.g.
    /// `"values"`, `"select"`), without formatting (`get_name()` may `format!`). Used by the
    /// plan-time "undeclared label" check to recognize steps that can turn any incoming value
    /// into a map/object shape a later `select()` might legitimately read a key from.
    pub(crate) fn kind_name(&self) -> &'static str {
        match self {
            GraphStep::Init(n, _)
            | GraphStep::Append(n, _)
            | GraphStep::Map(n, _)
            | GraphStep::FlatMap(n, _)
            | GraphStep::Barrier(n, _)
            | GraphStep::FlatBarrier(n, _)
            | GraphStep::Filter(n, _)
            | GraphStep::SideEffect(n, _)
            | GraphStep::SideEffectMut(n, _)
            | GraphStep::Modulator(n, _)
            | GraphStep::Count(n, _) => n,
            GraphStep::As(_, _) => "as",
        }
    }

    /// Analyses the child traversals of this step; see `GraphStepMap::analyze_nested_paths`.
    pub(crate) fn analyze_nested_paths(
        &mut self,
        analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        match self {
            GraphStep::Init(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::Append(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::Map(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::FlatMap(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::Barrier(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::FlatBarrier(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::Filter(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::As(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::SideEffect(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::SideEffectMut(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::Modulator(_, step) => step.analyze_nested_paths(analysis, downstream),
            GraphStep::Count(_, step) => step.analyze_nested_paths(analysis, downstream),
        }
    }

    /// Whether the executor skips this step entirely when a fused `count()` follows it.
    pub(crate) fn skipped_before_count(&self) -> bool {
        match self {
            GraphStep::Map(_, step) => !step.may_filter(),
            GraphStep::Barrier(_, _) => true,
            _ => false,
        }
    }

    /// Whether this step starts new paths, so nothing upstream of it survives into its outputs.
    pub(crate) fn resets_path(&self) -> bool {
        matches!(self, GraphStep::Barrier(_, _) | GraphStep::Count(_, _))
    }

    /// Whether this step genuinely owns new heap data at the end of its execution — see
    /// `GraphStepMap::materializes` and its siblings. `Modulator` never materializes (it doesn't
    /// execute independently); `Count`'s fused output is a scalar, so it doesn't either.
    ///
    /// Only called from the `alloc-tracking`-off (estimation) path in `source.rs`'s
    /// `step_memory_metrics` — with the feature on, every step's real allocator delta is measured
    /// directly instead, so this and every trait-level `materializes()` override go unreferenced in
    /// that build; `cfg_attr` silences the resulting dead-code warning without deleting the method,
    /// which the estimation path (any consumer built without `alloc-tracking`) still needs.
    #[cfg_attr(feature = "alloc-tracking", allow(dead_code))]
    pub(crate) fn materializes(&self) -> bool {
        match self {
            GraphStep::Init(_, step) => step.materializes(),
            GraphStep::Append(_, step) => step.materializes(),
            GraphStep::Map(_, step) => step.materializes(),
            GraphStep::FlatMap(_, step) => step.materializes(),
            GraphStep::Barrier(_, step) => step.materializes(),
            GraphStep::FlatBarrier(_, step) => step.materializes(),
            GraphStep::Filter(_, step) => step.materializes(),
            GraphStep::As(_, step) => step.materializes(),
            GraphStep::SideEffect(_, step) => step.materializes(),
            GraphStep::SideEffectMut(_, step) => step.materializes(),
            GraphStep::Modulator(_, _) => false,
            GraphStep::Count(_, _) => false,
        }
    }
}

/// The canonical rendering (see [`GraphStep::get_name`]).
impl<'g, S: GraphStorage + 'g> fmt::Display for GraphStep<'g, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.get_name())
    }
}

/// For debugging only: the canonical rendering, so a `{:?}` of a plan stays readable.
impl<'g, S: GraphStorage + 'g> fmt::Debug for GraphStep<'g, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.get_name())
    }
}

pub(crate) trait GraphStepCount<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    fn clone_box(&self) -> Box<dyn GraphStepCount<'g, S> + 'g>;
}

pub(crate) trait GraphStepModulator<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    fn get_args(&mut self) -> Option<Vec<String>> {
        None
    }
    fn get_by(&mut self) -> Option<By<'g, S>> {
        None
    }
    /// The option of a step-level `with(WithOptions..)` modulator, taken once like
    /// [`get_by`](Self::get_by); `None` for every other modulator.
    fn get_with_option(
        &mut self,
    ) -> Option<(crate::value::WithOptions, Option<crate::value::WithOptions>)> {
        None
    }
    /// The child traversal of a `from(__...)`/`to(__...)` modulator, taken once like
    /// [`get_args`](Self::get_args); `None` for every other modulator.
    fn get_traversal(&mut self) -> Option<AnonymousTraversal<'g, S>> {
        None
    }
    /// Fails when the executor reaches this modulator; only the marker of a `by()` no step took
    /// (`StepByRejected`) overrides it.
    fn check(&self) -> TraverserResult<()> {
        Ok(())
    }
    /// Renames the empty traversal a rejected modulator with no step before it reports (`__`)
    /// to `root`; only that marker (`StepModulatorRejected`) overrides it. Used when the steps
    /// of a root traversal were built through the anonymous-traversal builders (the script DSL
    /// lowering, see `GraphTraversalSource::adopt_lowered`).
    fn rename_root(&mut self, _root: &'static str) {}
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    fn clone_box(&self) -> Box<dyn GraphStepModulator<'g, S> + 'g>;
}

pub(crate) trait GraphStepSideEffectMut<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    /// The labels of the element this step creates when the plan names them (`add_v("person")`),
    /// for its authorization requests ([`GraphStep::for_each_access`]); empty when there are
    /// none or they come from a traversal.
    fn static_labels(&self) -> Vec<&str> {
        Vec::new()
    }
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Option<Traverser<S>>,
    ) -> TraverserResult<Vec<Traverser<S>>>;
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `from(__...)`/`to(__...)` child traversal. The default rejects it; only
    /// `add_e()` takes one (its endpoint is the traversal's first result).
    fn push_modulator_traversal(
        &mut self,
        _child: AnonymousTraversal<'g, S>,
        _modulator_name: &str,
    ) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether each output object is a new path position. Steps that return their input element,
    /// such as `property()`, override it with `false`.
    fn extends_path(&self) -> bool {
        true
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    /// The element-creating step (`addV()`/`addE()`) behind this step, so a following
    /// `property(T.id|T.label, v)` can fold into it (TinkerPop folds `property()` calls that
    /// directly follow an add step into it). Every other step keeps the default `None`.
    fn as_add_element_mut(&mut self) -> Option<&mut dyn AddElementStep> {
        None
    }
    /// For a plain `property(name, constant)` step: the key and the constant value, so the
    /// `add_property_fold` optimizer rule can fold it into the preceding add step. Every other
    /// step, and every `property()` form whose semantics folding could not reproduce exactly
    /// (a traversal value, a `Cardinality`, a `jpath` key), keeps the default `None`.
    fn constant_property(&self) -> Option<(&compact_str::CompactString, &crate::ElementProperty)> {
        None
    }
    /// The merge step (`mergeV()`/`mergeE()`) behind this step, so a following
    /// `option(Merge.x, ..)` can attach to it. Every other step keeps the default `None`.
    fn as_merge_mut(&mut self) -> Option<&mut dyn sideeffect_steps::merge_map::MergeStep<'g, S>> {
        None
    }
    /// A problem found when the step was built (e.g. an invalid constant merge map), raised by
    /// the plan-time validation pass before execution, even when no traverser reaches the step.
    fn plan_check(&self) -> TraverserResult<()> {
        Ok(())
    }
    fn clone_box(&self) -> Box<dyn GraphStepSideEffectMut<'g, S> + 'g>;
}

/// An element-creating step that `property(T.id, v)` / `property(T.label, v)` can fold into.
pub(crate) trait AddElementStep {
    /// Sets the user-supplied id of the element this step creates.
    fn set_id(&mut self, id: compact_str::CompactString);
    /// Replaces the label of the element this step creates; `false` when the step cannot take a
    /// label this way (`addE()`, whose label comes from `addE(label)`).
    fn set_label(&mut self, label: compact_str::CompactString) -> bool;
    /// Adds a property the element is created with (the `add_property_fold` rule). A key that
    /// is already present is overwritten, so the last `property()` of a key wins, exactly as the
    /// unfused sequence would leave it.
    fn fold_property(&mut self, key: compact_str::CompactString, value: crate::ElementProperty);
}

pub(crate) trait GraphStepSideEffect<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    /// Mutates `context.side_effect` (or runs some other non-transforming side operation);
    /// `source` continues downstream unchanged either way. Fallible because a `.by(...)`
    /// modulator (`aggregate()`/`store()`) resolves and materializes a value, which can fail the
    /// same way `group()`/`fold()`'s `.by()` resolution can.
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: &Traverser<S>,
    ) -> TraverserResult<()>;
    /// Called once after `process` has seen every traverser of one batch (one execution of the
    /// step; a `local()` child runs it once per traverser). The default does nothing;
    /// `aggregate()` folds the batch into a reduced side effect here.
    fn finish_batch(&self, _context: &mut TraverserContext<'_, S>) -> TraverserResult<()> {
        Ok(())
    }
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    /// The side-effect key this step populates (`aggregate("key")`/`store("key")`), if any — a
    /// second way, besides `as()`, that a label read by `select()`/`cap()`/
    /// `where(within(...))` can be declared somewhere in the query. `None` for every step that
    /// isn't a keyed side effect.
    fn declares_side_effect_key(&self) -> Option<&str> {
        None
    }
    /// Registers the (empty) bucket of [`Self::declares_side_effect_key`] before the step
    /// processes its first traverser, so `cap(key)` of a step that ran but collected nothing
    /// (an empty upstream, or a `by()` that resolved no value) reads the empty collection, as in
    /// TinkerPop. An existing bucket (a `withSideEffect` seed, a `Set`, an earlier fill) is never
    /// touched, and the common path only does a `contains_key`.
    fn declare_side_effect(
        &self,
        side_effect: &mut std::collections::HashMap<
            compact_str::CompactString,
            crate::traversal::side_effect::SideEffectValue<S>,
        >,
    ) {
        if let Some(key) = self.declares_side_effect_key()
            && !side_effect.contains_key(key)
        {
            side_effect.insert(
                compact_str::CompactString::new(key),
                crate::traversal::side_effect::SideEffectValue::List(Vec::new()),
            );
        }
    }
    fn clone_box(&self) -> Box<dyn GraphStepSideEffect<'g, S> + 'g>;
}

pub(crate) trait GraphStepAs<'g, S: GraphStorage + 'g>: Send + Sync + fmt::Display {
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: &mut Traverser<S>,
    ) -> TraverserResult<()>;
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// The labels this step attaches to the current path position.
    fn step_labels(&self) -> Option<&std::sync::Arc<[compact_str::CompactString]>> {
        None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    fn clone_box(&self) -> Box<dyn GraphStepAs<'g, S> + 'g>;
}

/// A `has(key, value)` condition folded into a `v()`/`e()` source step: the element must carry
/// the property `key` (a literal name, never a jpath) equal to `value`, with exactly the equality
/// of the `has` step ([`filter_steps::step_has::vertex_has`]/`edge_has`), so folding never changes
/// a result. Checked while the source scans, before a traverser exists.
#[derive(Debug, Clone)]
pub(crate) struct PropertyFilter {
    pub(crate) key: String,
    pub(crate) value: crate::value::ElementProperty,
}

impl PropertyFilter {
    /// Whether vertex `node` satisfies the condition.
    #[inline]
    pub(crate) fn vertex_matches<S: GraphStorage>(&self, storage: &S, node: S::VertexId) -> bool {
        filter_steps::step_has::vertex_has(storage, node, &self.key, &self.value)
    }

    /// Whether edge `edge` satisfies the condition.
    #[inline]
    pub(crate) fn edge_matches<S: GraphStorage>(&self, storage: &S, edge: S::EdgeId) -> bool {
        filter_steps::step_has::edge_has(storage, edge, &self.key, &self.value)
    }
}

pub(crate) trait GraphStepInit<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
    ) -> (GraphNodeType, &Option<Vec<String>>);
    fn labels(&self) -> Option<&[String]> {
        None
    }
    fn set_labels(&mut self, _labels: Vec<String>) {}
    fn ids(&self) -> Option<&[String]> {
        None
    }
    fn set_ids(&mut self, _ids: Vec<String>) {}
    /// The `has(key, value)` conditions folded into this source step; each element it finds
    /// must satisfy all of them. Default: none.
    fn property_filters(&self) -> &[PropertyFilter] {
        &[]
    }
    /// Folds one more `has(key, value)` condition into this source step. Returns `false` (and
    /// keeps nothing) for a step that cannot check properties while it scans (the default).
    fn push_property_filter(&mut self, _filter: PropertyFilter) -> bool {
        false
    }
    fn is_count_only(&self) -> bool {
        false
    }
    fn set_count_only(&mut self, _count_only: bool) {}
    fn is_group_count_by_label(&self) -> bool {
        false
    }
    fn set_group_count_by_label(&mut self, _group_count_by_label: bool) {}
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    fn clone_box(&self) -> Box<dyn GraphStepInit<'g, S> + 'g>;
}

pub(crate) trait GraphStepAppend<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    fn process(&self, context: &mut TraverserContext<'_, S>) -> TraverserResult<Vec<Traverser<S>>>;
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    fn clone_box(&self) -> Box<dyn GraphStepAppend<'g, S> + 'g>;
}

pub(crate) trait GraphStepMap<'g, S: GraphStorage + 'g>: Send + Sync + fmt::Display {
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Traverser<S>,
    ) -> TraverserResult<Traverser<S>>;
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Takes a step-level `with(WithOptions..)` option: `None` when accepted, otherwise the
    /// `InvalidModulator` reason. The default rejects every option.
    fn push_with_option(
        &mut self,
        _key: crate::value::WithOptions,
        _value: Option<crate::value::WithOptions>,
    ) -> Option<String> {
        Some(crate::traversal::with_reason::NOT_ACCEPTED.to_string())
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether the output object is a new path position (TinkerPop map semantics). A step that
    /// passes its input through unchanged, such as `identity()`, overrides it with `false`.
    fn extends_path(&self) -> bool {
        true
    }
    /// Whether [`process_filter`](Self::process_filter) can drop a traverser. A fused `count()`
    /// skips a map step only when it cannot.
    fn may_filter(&self) -> bool {
        false
    }
    /// Maps one traverser, or drops it; the executor calls this rather than `process`.
    fn process_filter(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Traverser<S>,
    ) -> TraverserResult<Option<Traverser<S>>> {
        self.process(context, source).map(Some)
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    /// Labels this step needs to resolve, declared **somewhere** in the query (an `as()`, or a
    /// side-effect key from `aggregate()`/`store()`/`tree()`), for the plan-time "undeclared
    /// label" check. Narrower than [`path_requirement`](Self::path_requirement): a step overrides
    /// this only when failing to resolve one of its labels is itself a query-authoring mistake
    /// that this crate reports before execution (`select()`), never for a step that treats an
    /// unresolved label as a best-effort match and falls back to something else (`is()`/
    /// `where_p()` fall back to a literal-value comparison; see `value/predicate.rs`).
    fn required_labels(&self) -> Option<Vec<compact_str::CompactString>> {
        None
    }
    /// A problem found when the step was built (e.g. a `math()` equation that does not parse),
    /// raised by the plan-time validation pass before execution, even when no traverser reaches
    /// the step.
    fn plan_check(&self) -> TraverserResult<()> {
        Ok(())
    }
    fn clone_box(&self) -> Box<dyn GraphStepMap<'g, S> + 'g>;
}

pub(crate) trait GraphStepFlatMap<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    /// Expands one input traverser into zero or more output traversers, writing them into
    /// `output` rather than returning a freshly allocated `Vec`.
    ///
    /// Buffer-ownership contract: `output` is owned by the caller and may already contain items
    /// from earlier calls (e.g. earlier input traversers in the same step's execution). This
    /// method must only `push`/`extend` onto `output` — it must never call `output.clear()` or
    /// otherwise assume anything about its prior contents beyond "it's where this call's new
    /// items go." Callers rely on this to grow one shared, amortized-growth buffer across many
    /// `process()` calls instead of allocating a small `Vec` per call.
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Traverser<S>,
        output: &mut Vec<Traverser<S>>,
    ) -> TraverserResult<()>;
    /// Expands the whole input stream at once. Only called by the executor for a step whose
    /// [`is_batch`](Self::is_batch) is true; the default loops over [`process`](Self::process).
    /// `union()`/`choose()`/`branch()` override it to feed every traverser routed to a stateful
    /// child (`limit`, `count`, `order`, `dedup`, ...) into one run of that child, as
    /// TinkerPop's `BranchStep` does.
    fn process_batch(
        &self,
        context: &mut TraverserContext<'_, S>,
        input: Vec<Traverser<S>>,
        output: &mut Vec<Traverser<S>>,
    ) -> TraverserResult<()> {
        for source in input {
            self.process(context, source, output)?;
        }
        Ok(())
    }
    /// Whether the executor must hand this step the whole input stream through
    /// [`process_batch`](Self::process_batch) instead of calling `process` per traverser. True
    /// for a branching step with a stateful child traversal. Default `false`.
    fn is_batch(&self) -> bool {
        false
    }
    fn count(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Traverser<S>,
    ) -> TraverserResult<u64> {
        let mut scratch = Vec::new();
        self.process(context, source, &mut scratch)?;
        // Outputs inherit the parent's bulk, so the logical count is the sum of their bulks.
        crate::traversal::bulk::total_bulk(context, &scratch, "count")
    }
    /// Whether this step walks the graph structure (`out`, `in`, `both`, their edge and
    /// endpoint forms). Two such steps in a row are where equal traversers pile up, so the
    /// `lazy_barrier` optimizer rule puts a merge point between them. Default `false`.
    fn is_adjacency(&self) -> bool {
        false
    }
    fn labels(&self) -> Option<&[String]> {
        None
    }
    fn set_labels(&mut self, _labels: Vec<String>) {}
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether each output object is a new path position. Branching steps (`union()`,
    /// `coalesce()`, `optional()`) override it with `false`: their children already extended it.
    fn extends_path(&self) -> bool {
        true
    }
    /// Whether this step may start a traversal (`g.union(...)`). As the first step of the root
    /// traversal it receives one seed traverser holding `null`, like TinkerPop's
    /// `GraphTraversalSource.union`. Default `false`; only `union()` overrides it.
    fn is_start(&self) -> bool {
        false
    }
    /// Called by the executor on a start step ([`is_start`](Self::is_start)) before it runs, so
    /// the step knows that its input is the seed, not a real traverser. Default: nothing.
    fn mark_start(&mut self) {}
    /// The step as a `choose()`/`branch()`, so a chained `.option(pick, traversal)` can attach to
    /// it in place (TinkerPop `GraphTraversal.option`), mirroring `GraphStepFlatBarrier::
    /// as_repeat_mut`'s postfix-attachment hook for `repeat()`'s `times()`/`until()`/`emit()`.
    /// Only `StepBranch` (shared by `choose()` and `branch()`) overrides it.
    fn as_branch_mut(
        &mut self,
    ) -> Option<&mut crate::traversal::step::flatmap_steps::step_choose::StepBranch<'g, S>> {
        None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    fn clone_box(&self) -> Box<dyn GraphStepFlatMap<'g, S> + 'g>;
}

pub(crate) trait GraphStepBarrier<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    /// Reduces the whole batch to at most one output traverser. `None` means the barrier emits
    /// nothing for this batch — TinkerPop's un-seeded reducing barriers (`sum()`/`mean()`/
    /// `min()`/`max()`/`median()`) on an empty (or all-null) numeric stream. A seeded barrier
    /// (`fold()`/`group()`/`groupCount()`/`tree()`/`cap()`, see [`always_emits`](Self::always_emits))
    /// never returns `None`.
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Vec<Traverser<S>>,
    ) -> TraverserResult<Option<Traverser<S>>>;
    fn is_group_by_label_count(&self) -> bool {
        false
    }
    /// Whether this barrier always produces exactly one output traverser, independent of how
    /// many traversers reach it. TinkerPop's seeded reducing barriers (`fold()` → `[]`,
    /// `group()`/`groupCount()`/`tree()` → `{}`) and `cap()` (whose output depends only on side
    /// effects collected so far, never on the incoming stream's size) all set this to `true`.
    /// Default `false`: `sum()`/`mean()`/`min()`/`max()`/`median()` emit nothing on an empty
    /// stream, matching TinkerPop's un-seeded reducing barriers. Lets a fused `count()` learn the
    /// output count (always `1`) without materializing the barrier's actual value.
    fn always_emits(&self) -> bool {
        false
    }
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    /// The side-effect key this step populates (`tree("key")`), if any — a second way, besides
    /// `as()`, that a label read by `select()`/`cap()`/`where(within(...))` can be declared
    /// somewhere in the query. `None` for every step that isn't a keyed side effect.
    fn declares_side_effect_key(&self) -> Option<&str> {
        None
    }
    fn clone_box(&self) -> Box<dyn GraphStepBarrier<'g, S> + 'g>;
}

pub(crate) trait GraphStepFlatBarrier<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Vec<Traverser<S>>,
    ) -> TraverserResult<Option<Vec<Traverser<S>>>>;
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether this step keeps state across the traversers it sees that a per-traverser run of
    /// its enclosing child would lose: a `repeat()` whose body holds a `dedup()` (the seen-set
    /// lives for the whole loop). `union()`/`choose()`/`branch()` then run such a child as one
    /// batch. Only `repeat()` overrides it.
    fn holds_loop_state(&self) -> bool {
        false
    }
    /// The step as a `repeat()`, so `times()`/`until()`/`emit()` can attach to it. Only
    /// `repeat()` overrides it.
    fn as_repeat_mut(
        &mut self,
    ) -> Option<&mut crate::traversal::step::flatbarrier_steps::step_repeat::StepRepeat<'g, S>>
    {
        None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    /// The side-effect key this step populates (`tree("key")`), if any; see
    /// [`GraphStepBarrier::declares_side_effect_key`].
    fn declares_side_effect_key(&self) -> Option<&str> {
        None
    }
    fn clone_box(&self) -> Box<dyn GraphStepFlatBarrier<'g, S> + 'g>;
}

pub(crate) trait GraphStepFilter<'g, S: GraphStorage + 'g>:
    Send + Sync + fmt::Display
{
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: &Traverser<S>,
    ) -> TraverserResult<bool>;
    /// How much of `source`'s bulk survives this filter: all of it or none for a deterministic
    /// filter (the default), possibly a part of it for a filter that draws per unit of bulk
    /// (`coin()`). Only the executor calls it; a child traversal asks `process` with a bulk of 1.
    fn surviving_bulk(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: &Traverser<S>,
    ) -> TraverserResult<u64> {
        Ok(if self.process(context, source)? {
            source.bulk
        } else {
            0
        })
    }
    fn labels(&self) -> Option<&[String]> {
        None
    }
    fn ids(&self) -> Option<&[String]> {
        None
    }
    #[allow(dead_code)]
    fn keys(&self) -> Option<&[String]> {
        None
    }
    /// The condition of a `has(key, value)` on a literal property name, which the
    /// `source_filter_pushdown` rule may fold into a `v()`/`e()` source step (see
    /// [`PropertyFilter`]). Default `None`: the step cannot be folded.
    fn property_equality(&self) -> Option<PropertyFilter> {
        None
    }
    fn as_where_traversal(&self) -> Option<&AnonymousTraversal<'g, S>> {
        None
    }
    /// Called once on the first step of a `where(traversal)` child: `and()`/`or()`/`not()` turn
    /// a leading/trailing `as()` of their own children into start/end labels (see
    /// `filter_steps/where_scope.rs`); every other step keeps the default no-op.
    fn configure_where_scope(&mut self) {}
    /// Whether this `where(traversal)` has a start or end label, so the optimizer must not
    /// flatten its child into the surrounding steps.
    fn has_scope_labels(&self) -> bool {
        false
    }
    /// A problem found when the step was built (an invalid start/end label of a `where()`
    /// child), raised by the plan-time validation pass before execution.
    fn plan_check(&self) -> TraverserResult<()> {
        Ok(())
    }
    fn into_inner_steps(self: Box<Self>) -> Option<Vec<GraphStep<'g, S>>> {
        None
    }
    /// Attaches a `from()`/`to()` modulator argument list. The default rejects it: only a
    /// step that overrides this and returns [`ArgsModulation::Accepted`] takes `from()`/
    /// `to()` (TinkerPop's `FromToModulating`: `add_e()` today), so a step can never swallow
    /// one silently.
    fn push_modulator_args(&mut self, _args: Vec<String>, _modulator_name: &str) -> ArgsModulation {
        ArgsModulation::Unsupported
    }
    /// Attaches a `by()` modulator. The default rejects it: only a step that overrides this and
    /// returns [`ByModulation::Accepted`] takes `by()`, so a step can never swallow one silently.
    fn push_modulator_by(&mut self, _args: By<'g, S>, _modulator_name: &str) -> ByModulation {
        ByModulation::Unsupported
    }
    fn get_name(&self) -> String {
        self.to_string()
    }
    /// The child traversals of this step in their canonical order; see
    /// [`GraphStep::child_traversals_mut`]. Steps without children keep the default.
    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        Vec::new()
    }
    /// What this step reads from the path of its incoming traversers. Steps that read
    /// `Traverser.path` must override it, so the path requirement analysis records it for them.
    fn path_requirement(&self) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Analyses the child traversals of this step, given what the steps after it read, and
    /// returns what the children read from the incoming path. Steps without children keep the
    /// default.
    fn analyze_nested_paths(
        &mut self,
        _analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        crate::traversal::optimizer::path_analysis::PathRequirement::None
    }
    /// Whether this step's `process()` genuinely owns new heap data at the end of execution
    /// (e.g. a terminal materialization, `group()`/`fold()`/`sum()`/`mean()`/`median()` building
    /// an aggregation buffer, `path()` building a `Path` object, `element_map()` constructing an
    /// owned map). Default `false`: most steps only pass lazy handles through
    /// (`GraphNodeIndex`/`GraphEdgeIndex`/`VertexProperty`/`EdgeProperty`), per rule 4's
    /// lazy-evaluation discipline. Used by `.profile()` (D3 of the memory-inspection spec) to
    /// decide, with no per-item work, whether a step's `bytes_materialized` figure is worth
    /// computing at all.
    fn materializes(&self) -> bool {
        false
    }
    fn clone_box(&self) -> Box<dyn GraphStepFilter<'g, S> + 'g>;
}

macro_rules! impl_box_clone {
    ($trait:ident) => {
        impl<'g, S: GraphStorage + 'g> Clone for Box<dyn $trait<'g, S> + 'g> {
            fn clone(&self) -> Self {
                self.clone_box()
            }
        }
    };
}

impl_box_clone!(GraphStepCount);
impl_box_clone!(GraphStepModulator);
impl_box_clone!(GraphStepSideEffectMut);
impl_box_clone!(GraphStepSideEffect);
impl_box_clone!(GraphStepAs);
impl_box_clone!(GraphStepInit);
impl_box_clone!(GraphStepAppend);
impl_box_clone!(GraphStepMap);
impl_box_clone!(GraphStepFlatMap);
impl_box_clone!(GraphStepBarrier);
impl_box_clone!(GraphStepFlatBarrier);
impl_box_clone!(GraphStepFilter);