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
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
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
use crate::graph::{GraphNodeType, GraphStorage};
use crate::value::TraverserValue;

/// Diagnostic trait providing actionable advice for errors.
pub trait DiagnosticError: std::error::Error {
    /// Returns actionable advice or recommendations to fix the error.
    fn help(&self) -> Option<String>;

    /// Returns labelled detail lines rendered underneath the error message, such as the
    /// offending value or the graph element it was read from. Values may span several lines.
    fn details(&self) -> Vec<(String, String)> {
        Vec::new()
    }

    /// Renders the error message, its details and the cause chain, excluding help guidance.
    fn diagnostic_body(&self) -> String {
        let mut buf = format!("Error: {self}");
        push_details(&mut buf, &self.details());
        let mut current: Option<&dyn std::error::Error> = self.source();
        while let Some(src) = current {
            buf.push_str(&format!("\nCaused by: {src}"));
            current = src.source();
        }
        buf
    }
}

/// Appends labelled detail lines, aligning continuation lines under the first one so that
/// multi-line values (such as a plan and its caret marker) keep their relative offsets.
pub(crate) fn push_details(buf: &mut String, details: &[(String, String)]) {
    if details.is_empty() {
        return;
    }
    let width = details
        .iter()
        .map(|(key, _)| key.chars().count())
        .max()
        .unwrap_or(0);
    for (key, value) in details {
        let prefix = format!("  {key}:{} ", " ".repeat(width - key.chars().count()));
        let padding = " ".repeat(prefix.chars().count());
        for (idx, line) in value.lines().enumerate() {
            if idx == 0 {
                buf.push_str(&format!("\n{prefix}{line}"));
            } else {
                buf.push_str(&format!("\n{padding}{line}"));
            }
        }
    }
}

/// Formats a `DiagnosticError` into a multi-line string containing the main error message,
/// cause chain (if any), and actionable help guidance.
pub fn format_diagnostic<E>(err: &E) -> String
where
    E: DiagnosticError + ?Sized,
{
    let mut buf = err.diagnostic_body();
    if let Some(help) = err.help() {
        for (idx, line) in help.lines().enumerate() {
            if idx == 0 {
                buf.push_str(&format!("\nHelp: {line}"));
            } else {
                buf.push_str(&format!("\n      {line}"));
            }
        }
    }
    buf
}

/// Provenance of a value that triggered an error: the graph element it was read from.
///
/// Carried by value errors so that diagnostics can name the exact vertex, edge and property
/// responsible for a failure instead of reporting only the mismatched type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ValueOrigin {
    /// Element kind the value belongs to: `vertex` or `edge`.
    pub element_type: &'static str,
    /// User-facing element identifier, when the element is still present in storage.
    pub element_id: Option<String>,
    /// Element label, when known.
    pub element_label: Option<String>,
    /// Property key the value was read from, when the value is a property.
    pub property: Option<String>,
}

impl ValueOrigin {
    /// Builds an origin pointing at a vertex, optionally at one of its properties.
    pub fn vertex(id: Option<String>, label: Option<String>, property: Option<String>) -> Self {
        Self {
            element_type: "vertex",
            element_id: id,
            element_label: label,
            property,
        }
    }

    /// Builds an origin pointing at an edge, optionally at one of its properties.
    pub fn edge(id: Option<String>, label: Option<String>, property: Option<String>) -> Self {
        Self {
            element_type: "edge",
            element_id: id,
            element_label: label,
            property,
        }
    }
}

impl ValueOrigin {
    /// Renders only the element part of the origin, without the property key.
    pub fn element(&self) -> String {
        let mut rendered = self.element_type.to_string();
        if let Some(id) = &self.element_id {
            rendered.push_str(&format!(" id=\"{id}\""));
        }
        if let Some(label) = &self.element_label {
            rendered.push_str(&format!(" label=\"{label}\""));
        }
        rendered
    }
}

impl std::fmt::Display for ValueOrigin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.element_type)?;
        if let Some(id) = &self.element_id {
            write!(f, " id=\"{id}\"")?;
        }
        if let Some(label) = &self.element_label {
            write!(f, " label=\"{label}\"")?;
        }
        if let Some(property) = &self.property {
            write!(f, " property=\"{property}\"")?;
        }
        Ok(())
    }
}

/// One traversal level of a step trace: the optimized physical plan of that level together
/// with the position of the step that failed inside it.
///
/// Nested traversals (`where_t()`, `not()`, `by()` sub-traversals) produce one frame per
/// level, so a failure is addressed by a path such as `#2.0` rather than a flat index.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StepFrame {
    /// Rendered steps of the executed plan for this level, in optimized physical order.
    pub steps: Vec<String>,
    /// Position of the failing step within `steps`.
    pub position: usize,
    /// The same level as the user wrote it, when the optimizer tracked provenance.
    pub(crate) logical: Option<LogicalFrame>,
}

/// A traversal level as written by the user, with the steps a failure originates from.
///
/// Rule-based optimization reorders and folds steps, so one executed step can trace back to
/// several written ones: `v().has_label("person").count()` runs as a single fused scan.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) struct LogicalFrame {
    /// Rendered steps of the level before optimization.
    pub steps: Vec<String>,
    /// Positions in `steps` the failing step originates from, in ascending order.
    pub positions: Vec<usize>,
}

/// Renders a dotted step chain with a caret line underlining the marked steps.
fn render_marked(steps: &[String], marked: &[usize]) -> String {
    let plan = steps.join(".");
    if marked.is_empty() {
        return plan;
    }
    let mut caret = String::new();
    let mut column = 0;
    for (index, step) in steps.iter().enumerate() {
        let width = step.chars().count();
        if marked.contains(&index) {
            // Marked neighbours are underlined as one run, separator included.
            let start = if index > 0 && marked.contains(&(index - 1)) {
                column - 1
            } else {
                column
            };
            while caret.chars().count() < start {
                caret.push(' ');
            }
            while caret.chars().count() < column + width {
                caret.push('^');
            }
        }
        column += width + 1;
    }
    if caret.trim().is_empty() {
        return plan;
    }
    format!("{plan}\n{caret}")
}

impl StepFrame {
    /// Builds a frame from the rendered steps of one traversal level.
    pub fn new(steps: Vec<String>, position: usize) -> Self {
        Self {
            steps,
            position,
            logical: None,
        }
    }

    /// Attaches the level as the user wrote it, for reporting against the original query.
    pub(crate) fn with_logical(mut self, logical: LogicalFrame) -> Self {
        self.logical = Some(logical);
        self
    }

    /// Returns the name of the failing step, when the position is inside the plan.
    pub fn step_name(&self) -> Option<&str> {
        self.steps.get(self.position).map(|s| s.as_str())
    }

    /// Renders the plan of this level without the caret line.
    pub fn plan(&self) -> String {
        self.steps.join(".")
    }

    /// Renders the executed plan of this level followed by a caret line marking the failing step.
    pub fn render(&self) -> String {
        render_marked(&self.steps, &[self.position])
    }

    /// Renders the level as written by the user, marking the steps the failure originates from.
    ///
    /// Returns `None` when provenance is unavailable, or when optimization left this level
    /// unchanged and the executed plan already shows the user their own query.
    pub fn render_logical(&self) -> Option<String> {
        let logical = self.logical.as_ref()?;
        if logical.positions.is_empty() || logical.steps == self.steps {
            return None;
        }
        Some(render_marked(&logical.steps, &logical.positions))
    }
}

/// The id segments one `StepFailed` level contributes: its child index (when it is a child
/// traversal of the enclosing step) and its step index (`?` when unknown).
fn level_segments(child_index: Option<usize>, step_index: Option<usize>) -> Vec<String> {
    let mut segments = Vec::with_capacity(2);
    if let Some(child) = child_index {
        segments.push(child.to_string());
    }
    segments.push(
        step_index
            .map(|index| index.to_string())
            .unwrap_or_else(|| "?".to_string()),
    );
    segments
}

/// Renders the step id of a failure (`#3.1.0`, the numbering of `Metrics::id`), walking nested
/// step frames.
fn step_path(child: &Option<usize>, index: &Option<usize>, source: &TraverserError) -> String {
    let mut segments: Vec<String> = level_segments(*child, *index);
    let mut current = source;
    while let TraverserError::StepFailed {
        child_index,
        step_index,
        source,
        ..
    } = current
    {
        segments.extend(level_segments(*child_index, *step_index));
        current = source;
    }
    if segments.iter().all(|s| s == "?") {
        return String::new();
    }
    format!("#{} ", segments.join("."))
}

/// Returns the name of the innermost failing step of a nested step chain.
fn innermost_step_name(step_name: &str, source: &TraverserError) -> String {
    match source {
        TraverserError::StepFailed {
            spelling: crate::traversal::Spelling::Snake,
            step_name: inner,
            source,
            ..
        } => innermost_step_name(inner, source),
        _ => step_name.to_string(),
    }
}

/// Errors related to value operations, properties, types, and casting.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum ValueError {
    /// A value failed to convert to the type a step required.
    #[error("Cast exception: expected type [{expected}], got type '{actual}'")]
    #[non_exhaustive]
    CastException {
        /// Type the step required.
        expected: String,
        /// Type the value actually had.
        actual: String,
        /// Rendered offending value, when it could be captured at the failure site.
        value: Option<String>,
        /// Graph element the offending value was read from, when it came from storage.
        ///
        /// Boxed so that the provenance, needed only to render a diagnostic, does not inflate
        /// every `Result` that carries a [`ValueError`].
        origin: Option<Box<ValueOrigin>>,
    },

    /// `min()`/`max()` met a value they cannot order against the others: a value of another
    /// kind than the one already seen (a number after a string), or a graph element, path or
    /// container. Numbers compare with numbers, text with text.
    #[error("Step '{step}' cannot order a {actual} value among {expected} values")]
    #[non_exhaustive]
    IncomparableValues {
        /// The failing step's name (`min` or `max`).
        step: &'static str,
        /// The kind(s) the step can order at this point, e.g. `number`.
        expected: String,
        /// The kind of the offending value.
        actual: String,
        /// Rendered offending value, when it could be captured at the failure site.
        value: Option<String>,
        /// Graph element the offending value was read from, when it came from storage.
        ///
        /// Boxed for the same reason as [`ValueError::CastException`]'s `origin`.
        origin: Option<Box<ValueOrigin>>,
    },

    /// A requested property does not exist on the element.
    #[error("Property '{key}' not found on element type '{element_type}'")]
    #[non_exhaustive]
    PropertyNotFound {
        /// The missing property's key.
        key: String,
        /// `"vertex"` or `"edge"`.
        element_type: &'static str,
    },

    /// A step reads a step label (`select("a")`, `where(P.eq("a"))`, `math("a + 1")`, ...) that
    /// no `as()` and no keyed side effect (`aggregate`/`store`/`group`/`tree`/
    /// `with_side_effect`) declares anywhere in the query: a plan-time error, raised before
    /// execution instead of silently returning nothing.
    #[error("Step label '{label}' is never declared in this query")]
    #[non_exhaustive]
    UndeclaredLabel {
        /// The label no step declares.
        label: String,
    },

    /// An operator was applied to two incompatible types.
    #[error("Invalid operation '{op}' between types '{type_a}' and '{type_b}'")]
    #[non_exhaustive]
    InvalidTypeOperation {
        /// The operator's name.
        op: &'static str,
        /// The left operand's type.
        type_a: &'static str,
        /// The right operand's type.
        type_b: &'static str,
    },

    /// `path()` was read on a traverser that never recorded one.
    #[error("Path is not defined or initialized for traverser")]
    PathNotDefined,

    /// A numeric value or conversion was invalid.
    #[error("Invalid numeric value or conversion: {reason}")]
    #[non_exhaustive]
    InvalidNumber {
        /// Why the value/conversion was invalid.
        reason: String,
    },

    /// A cast/coercion target type is not supported.
    #[error("Unsupported cast target '{target}'")]
    #[non_exhaustive]
    UnsupportedCastTarget {
        /// Rendered conversion target that cannot be produced.
        target: String,
        /// Why the target cannot be produced yet.
        reason: &'static str,
    },

    /// A `Scope.local` step that transforms each element of the list a traverser holds met an
    /// element it cannot take — for example a number in the list of `trim(Scope.local)`.
    ///
    /// The message carries TinkerPop's wording (`The trim(local) step can only take string or
    /// list of strings`), so a query ported from Gremlin fails with the text it expects.
    #[error(
        "Cast exception: The {step}(local) step can only take {accepts}, but element {index} of \
         the list has type '{actual}'"
    )]
    #[non_exhaustive]
    LocalElementType {
        /// The step's Gremlin name (`trim`, `toUpper`, `asString`, ...).
        step: &'static str,
        /// What the step accepts, in TinkerPop's words (`string or list of strings`).
        accepts: &'static str,
        /// 0-based position of the offending element in the list.
        index: usize,
        /// Type of the offending element.
        actual: String,
    },

    /// A label step met a traverser of the wrong kind: `add_label()`/`drop_label()` change the
    /// label set of a vertex, `set_label()` the label of an edge. The help names the step for
    /// the kind that arrived.
    #[error("The {step}() step takes {expected}, but got a value of type '{actual}'")]
    #[non_exhaustive]
    LabelStepElementKind {
        /// The step's name (`add_label`, `drop_label`, `set_label`).
        step: &'static str,
        /// The element kind the step takes, with its article (`a vertex` or `an edge`).
        expected: &'static str,
        /// Type of the incoming value (`edge`, `vertex`, `string`, ...).
        actual: String,
    },

    /// A list function step (`combine`, `conjoin`, `difference`, `disjunct`, `intersect`,
    /// `merge`, `product`) met an incoming value or an argument it cannot take: a `null`, a value
    /// that is not a list (or, for `merge`, not a map), or a child traversal without a result.
    #[error("The {step}() step takes a {expected} as its {operand}, but got {actual}")]
    #[non_exhaustive]
    ListFunctionInput {
        /// The step's name (`combine`, `merge`, ...).
        step: &'static str,
        /// Which input failed: `incoming value`, `argument` or `traversal argument`.
        operand: &'static str,
        /// What the step needed there: `list`, `map`, `list or map`.
        expected: &'static str,
        /// What it got (`null`, a type name, or that the traversal yielded nothing).
        actual: String,
    },

    /// A string step that combines several strings (`concat`) met an argument it cannot take:
    /// a constant that is neither a string nor `null`, or a child traversal that yields no result
    /// or a value that is not a string.
    #[error("The {step}() step takes a {expected} as its {operand}, but got {actual}")]
    #[non_exhaustive]
    StringFunctionInput {
        /// The step's name (`concat`).
        step: &'static str,
        /// Which input failed: `argument` or `traversal argument`.
        operand: &'static str,
        /// What the step needed there (`string or null`).
        expected: &'static str,
        /// What it got (a type name, or that the traversal yielded nothing).
        actual: String,
    },

    /// `sample(n).by(..)` weighs each traverser by its `by()` value, and that value was not a
    /// number of at least 0 (a string, a negative number, NaN, ...).
    #[error(
        "The sample() step weighs each traverser by its by() value, which must be a number of at \
         least 0, but got {actual}"
    )]
    #[non_exhaustive]
    SampleWeight {
        /// What the `by()` produced: a type name or the offending number.
        actual: String,
    },

    /// A JSON Path expression could not be parsed.
    #[error("Invalid JSONPath '{path}': {reason}")]
    #[non_exhaustive]
    InvalidJsonPath {
        /// The raw string the query passed.
        path: String,
        /// Why it could not be parsed.
        reason: String,
    },

    /// A `glob_path()` pattern could not be compiled.
    #[error("Invalid glob pattern '{pattern}' at position {position}: {reason}")]
    #[non_exhaustive]
    InvalidGlobPattern {
        /// The raw pattern the query passed.
        pattern: String,
        /// 0-based character (not byte) position of the problem.
        position: usize,
        /// Why it could not be compiled.
        reason: String,
    },

    /// A `TextP.regex()`/`TextP.notRegex()` expression could not be compiled.
    #[error("Invalid regular expression '{pattern}': {reason}")]
    #[non_exhaustive]
    InvalidRegex {
        /// The raw expression the query passed.
        pattern: String,
        /// Why it could not be compiled.
        reason: String,
    },

    /// `has_id(P)` (also `has(T.id, P)`) with an order predicate (`P.gt`, `P.gte`, `P.lt`,
    /// `P.lte`, `P.between`, `P.inside`, `P.outside`) on a number: element ids are strings, so
    /// the comparison could never hold. Raised at plan time, located on the step. Equality
    /// forms (`has_id(3)`, `P.eq(3)`, `P.neq(3)`, `P.within(1, 2)`, `P.without(1, 2)`, also nested
    /// in `and`/`or`/`not`) compare the number's literal text and stay valid.
    #[error("{step} compares element ids with a number, but element ids are strings")]
    #[non_exhaustive]
    NumericIdComparison {
        /// The step as written, e.g. `has_id(P.gt(3))`.
        step: String,
        /// The same step with every number operand as a string, e.g. `has_id(P.gt("3"))`.
        fix: String,
    },

    /// A TinkerPop `Operator` (`sum`, `max`, `addAll`, ...) could not combine two values.
    #[error("{}", operator_failed_message(operator, kind, left, right))]
    #[non_exhaustive]
    OperatorFailed {
        /// The operator's TinkerPop name (`sum`, `addAll`, ...).
        operator: &'static str,
        /// Why it failed.
        kind: OperatorFailure,
        /// The left operand, rendered with its type, e.g. `3 (int64)`.
        left: String,
        /// The right operand, rendered with its type.
        right: String,
    },
}

/// Why an [`Operator`](crate::value::Operator) failed: the kind of a [`ValueError::OperatorFailed`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum OperatorFailure {
    /// An `int64` operation left the `i64` range (`sum`, `minus`, `mult`, `div` of `i64::MIN` by
    /// `-1`, `sumLong`). TinkerPop promotes or wraps; this engine reports an error.
    Overflow,
    /// An integer was divided by zero (`div`).
    DivisionByZero,
    /// The operands are not of the kind the operator accepts.
    #[non_exhaustive]
    IncompatibleOperands {
        /// What the operator accepts, e.g. `number`.
        expected: &'static str,
    },
}

fn operator_failed_message(
    operator: &str,
    kind: &OperatorFailure,
    left: &str,
    right: &str,
) -> String {
    match kind {
        OperatorFailure::Overflow => {
            format!(
                "Operator '{operator}' overflowed the int64 range combining {left} with {right}"
            )
        }
        OperatorFailure::DivisionByZero => {
            format!("Operator '{operator}' cannot divide {left} by {right}: division by zero")
        }
        OperatorFailure::IncompatibleOperands { expected } => {
            format!("Operator '{operator}' cannot combine {left} with {right}: expected {expected}")
        }
    }
}

fn operator_help(operator: &str, kind: &OperatorFailure) -> String {
    let mut help = match kind {
        OperatorFailure::Overflow => format!(
            "'{operator}' works on int64 and does not widen or wrap: the result is outside the int64 range. \
             Convert an operand to a float first (for example g.v().values(\"age\").as_number()) \
             or reduce the values before combining them."
        ),
        OperatorFailure::DivisionByZero => format!(
            "'{operator}' of two integers is an integer division, so a zero divisor is an error. \
             Filter the zero out first, or divide by a float (1.0 / 0.0 is infinity)."
        ),
        OperatorFailure::IncompatibleOperands { expected } => {
            format!("'{operator}' expects {expected}.")
        }
    };
    help.push_str(
        "\nOperators: sum, minus, mult and div take numbers (null as the right operand leaves the left one); \
         min and max take two numbers or two values of one kind (string, boolean, uuid); and and or take \
         booleans; sumLong takes int64 only; addAll takes two lists, two maps, or a list and a value; assign \
         accepts anything. Convert values with as_number(), as_bool() or as_string() first, for example \
         g.v().values(\"age\").as_number().",
    );
    help.push_str(
        "\nIn a sack the operand comes from by(), or is the traverser's own value without one: \
         g.with_sack(0).v().out_e().sack(Operator.sum).by(\"weight\") adds every edge weight to the \
         sack. To combine a sack with a value that is not a number yet, convert the operand, for \
         example g.with_sack(0).v().sack(Operator.sum).by(__.values(\"age\").as_number()).",
    );
    help.push_str(
        "\nfold(seed, Operator) and with_side_effect(name, initial, Operator) apply the operator to every \
         value of the stream: g.v().values(\"age\").fold(0, Operator.sum) adds the ages, and \
         g.with_side_effect(\"a\", 0, Operator.sum).v().aggregate(\"a\").by(\"age\").cap(\"a\") does the \
         same into a side effect. The seed decides the kind: 0 for sum, 1 for mult, true for and, [] for addAll.",
    );
    if operator == "normSack" {
        help.push_str(
            "\nbarrier(Barrier.normSack) scales numeric sacks (null sacks are skipped), so every \
             sack in the stream must be a number or null, for example \
             g.with_sack(1.0).v().out().barrier(Barrier.normSack).sack().",
        );
    }
    help
}

/// Names the coercion step that produces a value of the rendered type, for a runnable example
/// in a diagnostic.
///
/// Returns `None` when the expectation is not a value type at all — a step that wanted a vertex
/// is not repaired by a conversion.
fn coercion_step(expected: &str) -> Option<&'static str> {
    Some(match expected {
        "string" => "as_string()",
        "boolean" => "as_bool()",
        // `number` is the numeric family (`GType::NUMBER`) that numeric steps expect.
        "number" => "as_number(GType.LONG)",
        "int64" => "as_number(GType.LONG)",
        "float64" => "as_number(GType.DOUBLE)",
        // UUID has no dedicated `as_uuid()` step (the coercion vocabulary follows TinkerPop's
        // as_string()/as_bool()/as_number()); the generic cast() step produces it.
        "uuid" => "cast(GType.UUID)",
        _ => return None,
    })
}

/// What the coercion step named by [`coercion_step`] really converts, so the advice is not a guess.
fn coercion_note(expected: &str) -> Option<&'static str> {
    match expected {
        "boolean" => Some(
            "as_bool() turns 0 (and NaN) into false, any other number into true, and the texts \
             true/false in any letter case; any other text is an error.",
        ),
        "number" | "int64" => Some("as_number(GType.LONG) truncates a float toward zero."),
        _ => None,
    }
}

/// True for the stream kinds that hold a list: a folded stream (`array`) or a stored list value
/// (`array<...>`).
fn is_list_kind(actual: &str) -> bool {
    actual == "array" || actual.starts_with("array<")
}

/// Appended when a step that reads one value per traverser meets a whole list: `Scope.local`
/// applies the step to the list each traverser holds.
const LIST_SCOPE_LOCAL_HINT: &str = "\nThe value is a list (for example from fold()): reduce each \
     traverser's list with Scope.local, for example g.v().values(\"age\").fold().sum(Scope.local) \
     or g.v().fold().count(Scope.local), or unfold() it first. \
     A string step transforms each element of the list the same way, for example \
     g.v().values(\"name\").fold().to_upper(Scope.local). \
     To join the elements into one string use conjoin(), for example \
     g.v().values(\"name\").fold().conjoin(\", \"); to combine it with a second list use \
     combine(), merge(), intersect(), difference(), disjunct() or product(), for example \
     g.v().values(\"name\").fold().combine([\"dave\"]). reverse() reverses the list itself, for \
     example g.v().values(\"name\").fold().reverse().";

/// The snake_case DSL spelling of a Gremlin step name (`toUpper` → `to_upper`), for a runnable
/// example in a diagnostic.
fn snake_step_name(step: &str) -> String {
    let mut name = String::with_capacity(step.len() + 2);
    for c in step.chars() {
        if c.is_ascii_uppercase() {
            name.push('_');
            name.push(c.to_ascii_lowercase());
        } else {
            name.push(c);
        }
    }
    name
}

/// The `help()` text of [`ValueError::LocalElementType`].
fn local_element_help(step: &str, index: usize, actual: &str) -> String {
    let snake = snake_step_name(step);
    if step == "asString" {
        return format!(
            "{step}(local) converts each element of the list a traverser holds to a string, and \
             element {index} has type '{actual}', which has no string form.\n\
             Drop the null elements before converting, for example \
             g.v().values(\"age\").fold().unfold().not(__.is(typeOf(GType.NULL))).fold().as_string(Scope.local), \
             or convert the stream before folding it: g.v().values(\"age\").as_string().fold()."
        );
    }
    format!(
        "{step}(local) transforms each element of the list a traverser holds, so every element \
         must be a string (a null element stays null), but element {index} has type '{actual}'.\n\
         Convert the elements first, for example \
         g.v().values(\"name\").fold().unfold().as_string().fold().{snake}(Scope.local), \
         or keep only the strings with \
         g.v().values(\"name\").fold().unfold().is(typeOf(GType.STRING)).fold().{snake}(Scope.local)."
    )
}

/// The `help()` text of [`ValueError::LabelStepElementKind`].
fn label_step_help(step: &str, actual: &str) -> String {
    let vertex_steps = "a vertex carries a label set, changed with add_label() and drop_label(), \
                        for example g.v().has_label(\"person\").add_label(\"employee\") or \
                        g.v(1).drop_label(\"person\")";
    let edge_step = "an edge has exactly one label, changed with set_label(), for example \
                     g.e().has_label(\"knows\").set_label(\"met\")";
    match (step, actual) {
        ("set_label", "vertex") => {
            format!("set_label() changes the label of an edge; {vertex_steps}.")
        }
        ("add_label" | "drop_label", "edge") => {
            format!("{step}() changes the label set of a vertex; {edge_step}.")
        }
        _ => format!(
            "{step}() changes the label of a graph element, not of a value of type '{actual}': \
             {vertex_steps}; {edge_step}. Keep the elements in the stream (no values(), \
             id() or label() before the step)."
        ),
    }
}

/// The `help()` text of [`ValueError::ListFunctionInput`].
fn list_function_help(step: &str, operand: &str, expected: &str, actual: &str) -> String {
    let argument = if step == "conjoin" {
        "\"-\""
    } else {
        "[\"x\"]"
    };
    match (operand, expected) {
        ("incoming value", "list or map") => format!(
            "{step}() works on the list or the map a traverser holds. Collect the stream into a \
             list with fold() first, for example g.v().values(\"name\").fold().{step}([\"x\"]), or \
             merge two maps, for example \
             g.v().project(\"name\").by(\"name\").{step}([\"other\": \"blueprint\"]) (Rhai: \
             #{{other: \"blueprint\"}})."
        ),
        ("incoming value", _) if actual == "null" => format!(
            "{step}() works on the list a traverser holds, and a null is not a list. Keep the \
             null values out before the step, for example \
             g.v().values(\"tags\").not(__.is(typeOf(GType.NULL))).{step}({argument})."
        ),
        ("incoming value", _) => format!(
            "{step}() works on the list a traverser holds (a fold(), a path(), a list-valued \
             property). Collect the stream into a list with fold() first, for example \
             g.v().values(\"name\").fold().{step}({argument})."
        ),
        ("traversal argument", _) => format!(
            "The child traversal of {step}() must yield a {expected} as its first result. End it \
             with fold() to turn its stream into a list, for example \
             g.v().values(\"name\").fold().{step}(__.v().values(\"name\").fold()); a traversal \
             that yields nothing or null cannot be used."
        ),
        (_, "map") => format!(
            "{step}() of a map merges another map into it: pass a map constant or a traversal \
             whose first result is a map, for example \
             g.v().has(\"name\", \"marko\").element_map().{step}(__.v().has(\"name\", \"lop\")\
             .element_map()); to merge lists, fold() the incoming stream into a list first."
        ),
        _ => format!(
            "The argument of {step}() is a {expected} constant such as [\"a\", \"b\"] or a child \
             traversal whose first result is a {expected}, for example \
             g.v().values(\"name\").fold().{step}(__.v().values(\"name\").fold()); null and \
             single values are not lists (wrap one value: [\"a\"])."
        ),
    }
}

/// The `help()` text of [`ValueError::StringFunctionInput`].
fn string_function_help(step: &str, operand: &str, actual: &str) -> String {
    match operand {
        "traversal argument" if actual.starts_with("no result") => format!(
            "A child traversal of {step}() must yield a value for every traverser: its first \
             result is appended. Make it always produce one, for example with coalesce(): \
             g.v().values(\"name\").{step}(__.coalesce(__.values(\"lang\"), __.constant(\"\"))), \
             or keep only the traversers it has a value for: \
             g.v().where(__.values(\"lang\")).values(\"name\").{step}(__.values(\"lang\"))."
        ),
        "traversal argument" => format!(
            "A child traversal of {step}() must yield a string (or null, which is skipped). \
             Convert its result with as_string(), for example \
             g.v().values(\"name\").{step}(\" \").{step}(__.values(\"age\").as_string()); a list \
             is joined into one string with conjoin(), for example \
             g.v().values(\"name\").{step}(__.out().values(\"name\").fold().conjoin(\",\"))."
        ),
        _ => format!(
            "The arguments of {step}() are strings (a null is skipped) or child traversals, for \
             example g.v().values(\"name\").{step}(\" is \", \"here\") or \
             g.v().values(\"name\").{step}(__.values(\"age\").as_string()); convert a number with \
             as_string() in a child traversal instead of passing it directly."
        ),
    }
}

/// Appended to a `CastException` help whose target is `uuid`: the only accepted form, and the
/// literal that builds a UUID in a query.
const UUID_CANONICAL_HINT: &str = "\nA UUID is written in canonical form: 8-4-4-4-12 lowercase hex \
     digits, no braces, for example UUID.from_string(\"550e8400-e29b-41d4-a716-446655440000\").";

/// Expected-kind text of a `select(Column.keys)` / `select(Column.values)` cast error; `help()`
/// keys its advice on it.
pub(crate) const SELECT_COLUMN_EXPECTED: &str = "map or entry";

/// Expected kinds of the cast error of the `T.key`/`T.value` tokens (`by(T.value)`, ...): a
/// property element or a map entry.
pub(crate) const T_TOKEN_EXPECTED: &[&str] = &[
    "vertexProperty",
    "edgeProperty",
    "pathProperty",
    "map entry",
];

/// Expected-kind text of the cast error of `key()`/`value()`: they read a property object.
const PROPERTY_OBJECT_EXPECTED: &str = "vertexProperty or edgeProperty or pathProperty";

/// Expected-kind text of the cast error of `drop()`: what it can remove.
const DROP_EXPECTED: &str = "vertex or vertexProperty or edge or edgeProperty";

/// Expected-kind text of the cast error of the key filters `has(key)`, `has(key, value)`,
/// `has(key, P)` and `hasNot(key)`.
const KEY_FILTER_EXPECTED: &str = "computed or vertexProperty or edgeProperty or vertex or edge";

/// Expected-kind text of the cast error of the vertex-to-adjacent steps (`out()`, `in()`,
/// `both()`, `outE()`, `inE()`, `bothE()`).
const ADJACENCY_EXPECTED: &str = "vertex or vertexProperty or computed (linked to vertex)";

/// True when the comma-free `expected` list (`a or b or c`) names a graph element kind.
fn expects_an_element(expected: &str) -> bool {
    expected
        .split(" or ")
        .any(|kind| kind == "vertex" || kind == "edge")
}

/// Appended to the cast error of `drop()` on a value that is not stored graph data.
const DROP_HINT: &str = "\ndrop() removes stored graph data: a vertex, an edge, or a property \
     from properties(key) (or a values(key) reference). A computed value, a list, a map or a path \
     is not stored, so there is nothing to remove. To drop the elements a list or a path holds, \
     unfold() it first, for example g.v(\"1\").out().fold().unfold().drop() or \
     g.v(\"1\").out().path().unfold().drop(); to remove a property keep the element and use \
     properties(\"key\").drop() or remove_property(\"key\").";

/// Appended to the cast error of a key filter on a `properties(jpath(..))` element.
const KEY_FILTER_PATH_PROPERTY_HINT: &str = "\nhas(key)/has_not(key) read a key of a vertex, an \
     edge, a map or an object-valued property. A path property element from \
     properties(jpath(..)) is the value at the end of the path: test the path on the element \
     instead, for example g.v().has(jpath(\"meta.a\"), 1) or g.v().has(jpath(\"meta.a\"), P.gt(0)), \
     or test the value itself with has_value(..) or value().is(..).";

/// Appended to the cast error of a key filter on one map entry (`unfold()` of a map).
const KEY_FILTER_ENTRY_HINT: &str = "\nhas(key)/has_not(key) read a key of a whole map, but \
     unfold() split the map into single key/value entries. Filter the map before unfold(), for \
     example g.v().value_map().has(\"name\").unfold(), or test an entry's key or value with \
     select(Column.keys).is(..) / select(Column.values).is(..), for example \
     g.v().value_map().unfold().where(__.select(Column.keys).is(\"name\")).";

/// Appended when a vertex-to-adjacent step (`inE()`, `out()`, ...) meets an edge.
const ADJACENCY_ON_EDGE_HINT: &str = "\nout()/in()/both() and out_e()/in_e()/both_e() start from a \
     vertex. From an edge, step to its vertices first with out_v()/in_v()/both_v()/other_v(), for \
     example g.v(\"1\").out_e().in_v().in_e() (the edges into the vertices the outgoing edges reach).";

/// True for the stream kinds that hold a map (`group()`, `project()`, ...) or one map entry
/// (`unfold()` of a map).
fn is_map_kind(actual: &str) -> bool {
    matches!(actual, "object" | "record" | "entry")
}

/// Appended when an element-only step (`properties()`, `key()`, `value()`, `id()`, `out()`, ...)
/// meets a map: those steps read graph elements, a map's keys and values are read by `Column`.
const MAP_COLUMN_HINT: &str = "\nA map (for example the result of group() or group_count()) is not a \
     graph element, so properties()/key()/value() do not apply to it. Read its keys or values with \
     unfold().select(Column.keys) / unfold().select(Column.values), one traverser per entry, for \
     example g.v().group().by(\"name\").by(__.out().count()).unfold().select(Column.keys); \
     select(Column.keys) without unfold() returns them all as one list.";

/// Appended to the cast error of `select(Column.keys)` / `select(Column.values)` on a non-map.
const SELECT_COLUMN_HINT: &str = "\nselect(Column.keys) / select(Column.values) reads a map \
     (group(), group_count(), project(), element_map(), value_map()) or one entry of it produced by \
     unfold(), for example g.v().group_count().by(\"name\").unfold().select(Column.keys). To read \
     a path label use select(\"label\") with a string; to read a property use values(\"key\"). \
     select(Column.keys) of a path() lists the step labels of each position, for example \
     g.v().as(\"a\").out().as(\"b\").path().select(Column.keys), and select(Column.values) \
     of a path() lists its objects, for example g.v(\"1\").out().path().select(Column.values).";

/// Maps a canonical [`ValueType`](crate::graph::ValueType) name onto the `GType` token that
/// names it, so a diagnostic can hand back a `typeOf()` query that finds every value of that type.
fn gtype_token(observed: &str) -> Option<&'static str> {
    Some(match observed {
        "null" => "NULL",
        "boolean" => "BOOLEAN",
        "int64" => "LONG",
        "float64" => "DOUBLE",
        "string" => "STRING",
        "uuid" => "UUID",
        _ => return None,
    })
}

/// True when a rendered [`ValueType`](crate::graph::ValueType) name denotes a nested container
/// (`object` or `array<...>`), so a `CastException` diagnostic can tell a genuine type mismatch
/// (a `string` where a `number` was wanted) apart from a query that reached a whole nested value
/// when it meant to reach one field inside it — the case `.json_path(...)` was built to resolve.
fn is_nested_container(observed: &str) -> bool {
    observed == "object" || observed.starts_with("array<")
}

/// The `help()` text of [`ValueError::InvalidGlobPattern`], keyed on its `reason`.
fn glob_pattern_help(pattern: &str, reason: &str) -> String {
    use crate::value::glob_path::{double_star_suggestion, reason as r};
    const SYNTAX: &str = "\nA pattern is a '/'-separated list of segments matched level by level below \
         the start vertex: '*' (any value), '?' (one character), '**' (any number of levels, a whole \
         segment only), '[a-z]' / '[!a-z]' (character classes), '{a,b}' (alternatives within one \
         segment) and '\\' to escape any of them, for example glob_path(\"**/src/*.{rs,toml}\").";
    let advice = if reason == r::DOUBLE_STAR_IN_SEGMENT {
        match double_star_suggestion(pattern) {
            Some(fixed) => format!(
                "'**' spans whole levels, so it must stand alone between slashes. Write \
                 glob_path(\"{fixed}\") instead, or plain glob_path(\"**\") to match every level \
                 below the start vertex. A literal '*' is written '\\*'."
            ),
            None => "'**' spans whole levels, so it must stand alone between slashes, for example \
                     glob_path(\"a*/**/*b\") instead of glob_path(\"a**b\"), or plain \
                     glob_path(\"**\")."
                .to_string(),
        }
    } else if reason == r::SLASH_IN_ALTERNATIVES {
        "Alternatives in '{..}' choose within one segment and cannot contain '/'. Split the \
         alternative into two queries, for example glob_path(\"src/a\") and glob_path(\"lib/b\") \
         instead of glob_path(\"{src/a,lib/b}\"), or use '**' to span levels, for example \
         glob_path(\"**/{a,b}\"). A value that itself contains '/' is matched with '\\/'."
            .to_string()
    } else if reason == r::NESTED_ALTERNATIVES {
        "Alternatives cannot be nested; flatten them into one group, for example \
         glob_path(\"{a,b1,b2}\") instead of glob_path(\"{a,b{1,2}}\"), or place two groups side \
         by side: glob_path(\"{a,b}{1,2}\")."
            .to_string()
    } else if reason == r::RESERVED_SEGMENT {
        "'.' and '..' as whole segments are reserved for relative navigation. The start vertex is \
         already the current level: glob_path(\"docs/*\") matches its children directly. To walk \
         back up use .in() or repeat(__.in()) before the step, for example \
         g.v(\"x\").in().glob_path(\"docs/*\"). A value that is literally '.' is matched with '\\.'."
            .to_string()
    } else if reason == r::TOO_MANY_SEGMENTS {
        "A pattern can have at most 63 segments (a run of '**/**' counts once). Split the walk \
         into two consecutive steps, each matching below the vertices the previous one emits, for \
         example glob_path(\"a/b/c\").glob_path(\"d/e/f\") instead of glob_path(\"a/b/c/d/e/f\")."
            .to_string()
    } else if reason == r::TOO_MANY_ALTERNATIVES {
        "The '{..}' groups of one segment expand to their product, capped at 256 alternatives. \
         Replace a group with a class or a wildcard, for example glob_path(\"file[0-9][0-9]\") \
         instead of glob_path(\"file{0,1,...,9}{0,1,...,9}\"), or split the query."
            .to_string()
    } else if reason == r::UNCLOSED_CLASS {
        "Close the character class with ']' in the same segment, for example \
         glob_path(\"file[0-9].txt\"); match a literal '[' with '\\['."
            .to_string()
    } else if reason == r::EMPTY_CLASS {
        "A character class needs at least one character; a ']' right after '[' or '[!' is taken \
         literally, so glob_path(\"[]]\") matches ']' and glob_path(\"[!]]\") anything else."
            .to_string()
    } else if reason == r::INVERTED_RANGE {
        "A range goes from the lower to the higher character, for example glob_path(\"[a-z]*\") \
         instead of glob_path(\"[z-a]*\")."
            .to_string()
    } else if reason == r::UNCLOSED_ALTERNATIVES {
        "Close the alternatives with '}', for example glob_path(\"*.{rs,toml}\"); match a literal \
         '{' with '\\{'."
            .to_string()
    } else if reason == r::TRAILING_ESCAPE {
        "'\\' escapes the character after it; match a literal backslash with '\\\\', for example \
         glob_path(\"dir\\\\\")."
            .to_string()
    } else if reason == r::EMPTY_PATTERN {
        "Pass a non-empty pattern, for example glob_path(\"*\") for the children of the start \
         vertex or glob_path(\"**\") for all of its descendants."
            .to_string()
    } else if reason == r::LEADING_SLASH
        || reason == r::TRAILING_SLASH
        || reason == r::EMPTY_SEGMENT
    {
        "The pattern is relative to the start vertex: drop the leading and trailing '/' and the \
         empty segments, for example glob_path(\"src/main.rs\") instead of \
         glob_path(\"/src//main.rs/\"). Use '**' to match any number of levels."
            .to_string()
    } else {
        "Fix the pattern at the reported position.".to_string()
    };
    format!("{advice}{SYNTAX}")
}

impl DiagnosticError for ValueError {
    fn help(&self) -> Option<String> {
        match self {
            ValueError::CastException {
                expected,
                actual,
                origin,
                ..
            } => {
                let convert = coercion_step(expected);
                let t_token = *expected == T_TOKEN_EXPECTED.join(" or ");
                // A type search does not help a `T.key`/`T.value` misuse: every value fails.
                let locate = gtype_token(actual).filter(|_| !t_token);
                match origin.as_ref().and_then(|origin| {
                    origin.property.as_ref().map(|property| (origin, property))
                }) {
                    Some((origin, property)) => {
                        let mut help = format!(
                            "Property '{property}' holds a {actual} on {}, but [{expected}] is required here.\n\
                             Filter the stream before this step (for example with .has(\"{property}\", ...)), \
                             or declare '{property}' in the graph schema so the type is enforced on write.",
                            origin.element()
                        );
                        if let Some(convert) = convert {
                            help.push_str(&format!(
                                "\nConvert the values in the query instead: values(\"{property}\").{convert}."
                            ));
                            help.push_str(&format!(
                                "\nOr fix the data in place: property(\"{property}\", __.values(\"{property}\").{convert})."
                            ));
                            if let Some(note) = coercion_note(expected) {
                                help.push_str(&format!("\n{note}"));
                            }
                        }
                        if let Some(locate) = locate {
                            help.push_str(&format!(
                                "\nFind every offending value with values(\"{property}\").is(typeOf(GType.{locate}))."
                            ));
                        }
                        if expected == "uuid" {
                            help.push_str(UUID_CANONICAL_HINT);
                        }
                        if is_nested_container(actual) {
                            help.push_str(&format!(
                                "\nReach one nested field directly instead of chaining values(): \
                                 json_path(\"{property}.subkey\") instead of \
                                 values(\"{property}\").values(\"subkey\").\n\
                                 A jpath key does the same inside any step that takes a property name: \
                                 values(jpath(\"{property}.subkey\")), has(jpath(\"{property}.subkey\"), v), \
                                 order().by(jpath(\"{property}.subkey\")); a missing path is simply absent."
                            ));
                        }
                        if is_list_kind(actual) {
                            help.push_str(&format!(
                                "\n'{property}' holds a list: reduce each traverser's list with \
                                 Scope.local, for example values(\"{property}\").sum(Scope.local) \
                                 or values(\"{property}\").count(Scope.local), or unfold() it first. \
                                 values(\"{property}\").conjoin(\", \") joins it into one string."
                            ));
                        }
                        Some(help)
                    }
                    None => {
                        let mut help =
                            "Check the value type before performing conversion or cast operation."
                                .to_string();
                        if let Some(convert) = convert {
                            help.push_str(&format!("\nConvert the stream first with .{convert}."));
                            if let Some(note) = coercion_note(expected) {
                                help.push_str(&format!("\n{note}"));
                            }
                        }
                        if let Some(locate) = locate {
                            help.push_str(&format!(
                                "\nFind every offending value with .is(typeOf(GType.{locate}))."
                            ));
                        }
                        // A string step on an element; not a step that takes elements itself (an
                        // adjacency or key step whose expected kinds name "computed" too).
                        if (expected == "string"
                            || (expected.contains("computed") && !expects_an_element(expected)))
                            && matches!(actual.as_str(), "vertex" | "edge")
                        {
                            help.push_str(
                                "\nThis step needs a string, and a graph element is not one. as_string() \
                                 renders an element as text (g.v().as_string() gives \"v[1]\", an edge \
                                 \"e[7][1-knows->2]\"); to work on a property text, read it first: \
                                 g.v().values(\"name\").to_upper().",
                            );
                        }
                        if expected == "uuid" {
                            help.push_str(UUID_CANONICAL_HINT);
                        }
                        if expected == "scalar, array or object" {
                            help.push_str(
                                "\nA sack holds data, not a graph element. Store the element's id or one \
                                 of its properties instead: sack(Operator.assign).by(T.id) or \
                                 sack(Operator.assign).by(\"name\")."
                            );
                        }
                        if t_token {
                            help.push_str(
                                "\nT.key and T.value read a property element or a map entry, as in \
                                 TinkerPop: produce one with .properties(...) (or unfold() a map) \
                                 first, for example g.v().properties(\"name\").order().by(T.value). \
                                 A plain value (a values(...) result, a number) is already the \
                                 value: use by() with no argument or by(__.identity()) instead, \
                                 for example g.v().values(\"age\").order().by().",
                            );
                        }
                        if expected == PROPERTY_OBJECT_EXPECTED {
                            help.push_str(
                                "\n.value()/.key() only read a property object, produced by \
                                 .properties(...) or a raw .values(key) reference — call one of \
                                 those first, for example .properties(\"name\").value() instead \
                                 of .value() directly on a vertex/edge.",
                            );
                        }
                        if expected == DROP_EXPECTED && actual != "pathProperty" {
                            help.push_str(DROP_HINT);
                        }
                        if expected == KEY_FILTER_EXPECTED && actual == "pathProperty" {
                            help.push_str(KEY_FILTER_PATH_PROPERTY_HINT);
                        }
                        if expected == KEY_FILTER_EXPECTED && actual == "entry" {
                            help.push_str(KEY_FILTER_ENTRY_HINT);
                        }
                        if expected == ADJACENCY_EXPECTED && actual == "edge" {
                            help.push_str(ADJACENCY_ON_EDGE_HINT);
                        }
                        if actual == "pathProperty" && expected == DROP_EXPECTED {
                            help.push_str(
                                "\nA property found by a path, properties(jpath(..)), holds no reference to \
                                 the element it came from, so drop() cannot remove it. Remove the value at \
                                 the path with remove_property(jpath(..)) on the element, for example \
                                 g.v().remove_property(jpath(\"meta.tags[0]\")) (an object key is removed, an \
                                 array element is removed with shift).",
                            );
                        }
                        if is_map_kind(actual)
                            && (expected.contains("vertex") || expected.contains("edge"))
                            && !(expected == KEY_FILTER_EXPECTED && actual == "entry")
                            && expected != DROP_EXPECTED
                        {
                            help.push_str(MAP_COLUMN_HINT);
                        }
                        if expected == SELECT_COLUMN_EXPECTED {
                            help.push_str(SELECT_COLUMN_HINT);
                        }
                        if is_list_kind(actual) && expected != DROP_EXPECTED {
                            help.push_str(LIST_SCOPE_LOCAL_HINT);
                        }
                        Some(help)
                    }
                }
            }
            ValueError::IncomparableValues { step, expected, actual, origin, .. } => {
                let property = origin.as_ref().and_then(|origin| origin.property.as_ref());
                let convert = coercion_step(expected);
                let locate = gtype_token(actual);
                let mut help = match property {
                    Some(property) => format!(
                        "Property '{property}' holds a {actual} where '{step}' can only order [{expected}] values."
                    ),
                    None => format!(
                        "'{step}' can only order [{expected}] values here, but the stream holds a {actual}."
                    ),
                };
                help.push_str(&format!(
                    "\n{step}() compares numbers with numbers and text with text (booleans and uuids \
                     with their own kind); graph elements, paths and collections are not ordered."
                ));
                match property {
                    Some(property) => {
                        help.push_str(&format!(
                            "\nFilter the stream before this step (for example with .has(\"{property}\", ...)), \
                             or declare '{property}' in the graph schema so the type is enforced on write."
                        ));
                        if let Some(convert) = convert {
                            help.push_str(&format!(
                                "\nConvert the values in the query instead: values(\"{property}\").{convert}."
                            ));
                            help.push_str(&format!(
                                "\nOr fix the data in place: property(\"{property}\", __.values(\"{property}\").{convert})."
                            ));
                            if let Some(note) = coercion_note(expected) {
                                help.push_str(&format!("\n{note}"));
                            }
                        }
                        if let Some(locate) = locate {
                            help.push_str(&format!(
                                "\nFind every offending value with values(\"{property}\").is(typeOf(GType.{locate}))."
                            ));
                        }
                    }
                    None => {
                        if let Some(convert) = convert {
                            help.push_str(&format!("\nConvert the stream first with .{convert}."));
                            if let Some(note) = coercion_note(expected) {
                                help.push_str(&format!("\n{note}"));
                            }
                        }
                        if let Some(locate) = locate {
                            help.push_str(&format!(
                                "\nFind every offending value with .is(typeOf(GType.{locate}))."
                            ));
                        }
                    }
                }
                help.push_str(&format!(
                    "\nTo compare a mixed property read it as one kind first, with \
                     values(\"p\").as_string() or values(\"p\").as_number(GType.LONG), for example \
                     g.v().values(\"name\").{step}()."
                ));
                Some(help)
            }
            ValueError::PropertyNotFound {
                key,
                element_type: "path",
            } => Some(format!(
                "No step label '{key}' is set on the path of this traverser.\n\
                 Label the position with as() before reading it, for example \
                 g.v(\"1\").as(\"{key}\").out().select(\"{key}\"), or read the whole path \
                 with path(). A label set several times (as(\"{key}\") inside repeat()) is read \
                 with select(Pop.all, \"{key}\") (every occurrence), Pop.first, Pop.last (the \
                 default) or Pop.mixed."
            )),
            ValueError::UndeclaredLabel { label: key } => Some(format!(
                "Step label '{key}' is never declared anywhere in this query: no as(\"{key}\") \
                 and no side-effect key '{key}' from aggregate(\"{key}\")/store(\"{key}\")/\
                 group(\"{key}\")/group_count(\"{key}\")/\
                 tree(\"{key}\") exists, so it can never resolve — this is caught before \
                 execution instead of silently returning nothing.\n\
                 Label the position with as() before reading it, for example \
                 g.v(\"1\").as(\"{key}\").out().select(\"{key}\"), or read the whole path \
                 with path(). A label that is declared but only sometimes set (e.g. inside \
                 union()/optional()/choose()) is not an error: the traverser is filtered instead.\n\
                 A label set several times (as(\"{key}\") inside repeat()) is read with \
                 select(Pop.all, \"{key}\") (every occurrence), Pop.first, Pop.last (the default) \
                 or Pop.mixed, for example g.v(\"1\").as(\"{key}\").repeat(__.out().as(\"{key}\"))\
                 .times(2).select(Pop.all, \"{key}\").\n\
                 A label can also be read with where(): g.v(\"1\").as(\"{key}\").out()\
                 .where(__.as(\"{key}\").values(\"name\")) starts the child at the object \
                 labelled '{key}', and a trailing as(\"{key}\") keeps the traverser only when the \
                 child ends at that object."
            )),
            ValueError::PropertyNotFound {
                key,
                element_type: "side_effect",
            } => Some(format!(
                "No side-effect key '{key}' has been populated yet.\n\
                 A key whose aggregate()/store()/subgraph() step ran but collected nothing is not \
                 an error: cap(\"{key}\") returns the empty collection. This error therefore means \
                 that no aggregate()/store()/subgraph()/tree()/with_side_effect() declares the key \
                 (usually a typo).\n\
                 Populate it upstream with aggregate(\"{key}\") or store(\"{key}\") (or \
                 with_side_effect(\"{key}\", ...) for a fixed value, tree(\"{key}\") for a \
                 hierarchical tree, group(\"{key}\")/group_count(\"{key}\") for a grouped map, \
                 for example g.v().group_count(\"{key}\").by(T.label).cap(\"{key}\")), then read it with cap(\"{key}\") or \
                 where(within(\"{key}\"))/where(without(\"{key}\")) — a bare string argument to \
                 within()/without() inside where() resolves against a populated side-effect key \
                 first and only falls back to a literal value comparison when no such key exists.\n\
                 aggregate()/store() keep duplicates; to collect each value once declare the key \
                 as a set first: g.with_side_effect(\"{key}\", Set.of()).v().both().values(\"name\")\
                 .aggregate(\"{key}\").cap(\"{key}\"); to combine them with an operator instead of \
                 collecting them declare a reducer: g.with_side_effect(\"{key}\", 0, Operator.sum).v()\
                 .aggregate(\"{key}\").by(\"age\").cap(\"{key}\")."
            )),
            ValueError::PropertyNotFound {
                key,
                element_type: "list",
            } => Some(format!(
                "A list has no property '{key}': by(\"{key}\") reads a property of an element or a \
                 map, and the value here is a list (for example the result of select(Pop.all, \"a\") \
                 or of a select(Pop.mixed, \"a\") over a label set several times, or of fold()).\n\
                 Ensure the property key exists on the specified element type or use .has() filter.\n\
                 List the keys actually present with .properties() (no arguments).\n\
                 Read the property of every element of the list with a child traversal, for example \
                 g.v().as(\"a\").out().as(\"a\").select(Pop.all, \"a\")\
                 .by(__.unfold().values(\"{key}\").fold()); by() applies to the whole selected list, \
                 never to each element."
            )),
            ValueError::PropertyNotFound { key, .. } => {
                Some(format!(
                    "Ensure the property key exists on the specified element type or use .has() filter.\n\
                     List the keys actually present with .properties() (no arguments).\n\
                     A key is a literal property name, so '{key}' is not read as a path even when it \
                     contains dots. To reach a field inside an object or array property use a jpath key, \
                     for example values(jpath(\"meta.k\")) or by(jpath(\"meta.k\")); a path that does not \
                     exist yields nothing instead of an error."
                ))
            }
            ValueError::InvalidTypeOperation { .. } => Some(
                "Ensure operand types are compatible for operation, or convert one side first \
                 with .as_string(), .as_bool() or .as_number(GType.LONG)."
                    .to_string(),
            ),
            ValueError::PathNotDefined => Some(
                "Paths are recorded automatically for the steps that read them: label a position \
                 with as() and read it with select(), for example \
                 g.v(\"1\").as(\"a\").out().select(\"a\"), or read the whole path with \
                 path(), for example g.v(\"1\").out().path()."
                    .to_string(),
            ),
            ValueError::InvalidNumber { .. } => {
                Some("Verify that numeric values are within valid bounds and correct type format.".to_string())
            }
            ValueError::UnsupportedCastTarget { target, reason } => Some(format!(
                "'{target}' cannot be produced by a conversion yet: {reason}.\n\
                 The supported targets are as_string(), as_bool(), as_number(), \
                 as_number(GType.LONG) and as_number(GType.DOUBLE)."
            )),
            ValueError::InvalidJsonPath { .. } => Some(
                "A property path is a singular JSONPath (RFC 9535): member names and integer array \
                 indices only, e.g. jpath(\"meta.tags[0]\"), jpath(\"$.meta.tags[-1]\") (negative \
                 counts from the end) or jpath(\"meta['a.b'].k\") (bracket notation for a name that \
                 holds a dot, a quote or a bracket, escaped with \\' and \\\\). Use it as a key \
                 wherever a property name is taken, for example g.v().values(jpath(\"meta.k\")) \
                 or g.v().has(jpath(\"meta.k\"), 1), and as a step with json_path(\"$.meta.tags[0]\") \
                 or .by(By::JsonPath(\"meta.k\")). Recursive descent ('..'), wildcards ('*'), slices \
                 and filter expressions ('[?(...)]') are not supported. A plain string \
                 key such as values(\"a.b\") is never parsed: it names a property that literally \
                 contains a dot. A path has at most 256 segments, and an index is at most \
                 9007199254740991 (2^53 - 1) from either end."
                    .to_string(),
            ),
            ValueError::InvalidGlobPattern { pattern, reason, .. } => {
                Some(glob_pattern_help(pattern, reason))
            }
            ValueError::SampleWeight { .. } => Some(
                "sample(n).by(..) draws each traverser with a probability proportional to its \
                 by() value, so the by() must yield a number of at least 0: a numeric property \
                 (g.e().sample(2).by(\"weight\")) or a traversal ending in a number \
                 (g.v().sample(1).by(__.out_e().count())). Convert a numeric string with \
                 as_number() inside the by(), for example \
                 g.v().sample(1).by(__.values(\"score\").as_number()), or drop by() for a uniform \
                 sample."
                    .to_string(),
            ),
            ValueError::NumericIdComparison { fix, .. } => Some(format!(
                "Element ids are strings, so an order comparison (P.gt, P.gte, P.lt, P.lte, \
                 P.between, P.inside, P.outside) with a number can never hold. Compare with a \
                 string instead: {fix}. Strings are ordered character by character, so \"10\" \
                 sorts before \"9\": P.gt(\"3\") keeps \"30\" but not \"10\". Equality needs no \
                 change: has_id(3), has_id(P.eq(3)), has_id(P.neq(3)), has_id(P.within(1, 2)) and \
                 has_id(P.without(1, 2)) compare the \
                 number's text."
            )),
            ValueError::InvalidRegex { .. } => Some(
                "TextP.regex()/TextP.not_regex() take a regular expression in the syntax of the \
                 Rust `regex` crate (https://docs.rs/regex/latest/regex/#syntax), not Java's: \
                 classes [a-z], \\d, \\w, \\s, groups (..), alternation |, quantifiers * + ? \
                 {n,m}, inline flags such as (?i). Look-around ((?=..), (?!..)) and \
                 back-references (\\1) are not supported. Escape a literal metacharacter with a \
                 backslash (in a script string the backslash itself is doubled): \
                 g.v().has(\"name\", TextP.regex(\"^ma\\\\.\")). The match is unanchored: \
                 write ^...$ to match the whole string."
                    .to_string(),
            ),
            ValueError::LocalElementType {
                step,
                index,
                actual,
                ..
            } => Some(local_element_help(step, *index, actual)),
            ValueError::LabelStepElementKind { step, actual, .. } => {
                Some(label_step_help(step, actual))
            }
            ValueError::ListFunctionInput {
                step,
                operand,
                expected,
                actual,
            } => Some(list_function_help(step, operand, expected, actual)),
            ValueError::StringFunctionInput {
                step,
                operand,
                actual,
                ..
            } => Some(string_function_help(step, operand, actual)),
            ValueError::OperatorFailed { operator, kind, .. } => Some(operator_help(operator, kind)),
        }
    }

    fn details(&self) -> Vec<(String, String)> {
        let (value, origin) = match self {
            ValueError::CastException { value, origin, .. }
            | ValueError::IncomparableValues { value, origin, .. } => (value, origin),
            _ => return Vec::new(),
        };
        let mut details = Vec::new();
        if let Some(value) = value {
            details.push(("value".to_string(), value.clone()));
        }
        if let Some(origin) = origin {
            details.push(("origin".to_string(), origin.to_string()));
        }
        details
    }
}

/// Errors related to graph structure, vertex/edge lookup, and graph constraints.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum GraphError {
    /// A vertex ID does not exist in the graph.
    #[error("Vertex with ID '{id}' was not found in the graph")]
    #[non_exhaustive]
    VertexNotFound {
        /// The missing vertex's ID.
        id: String,
    },

    /// An edge ID does not exist in the graph.
    #[error("Edge with ID '{id}' was not found in the graph")]
    #[non_exhaustive]
    EdgeNotFound {
        /// The missing edge's ID.
        id: String,
    },

    /// `add_v()` was given a vertex ID that already exists.
    #[error("Vertex with ID '{id}' already exists in the graph")]
    #[non_exhaustive]
    VertexIdUniqueConstraint {
        /// The colliding ID.
        id: String,
    },

    /// `add_e()` was given an edge ID that already exists.
    #[error("Edge with ID '{id}' already exists in the graph")]
    #[non_exhaustive]
    EdgeIdUniqueConstraint {
        /// The colliding ID.
        id: String,
    },

    /// The element behind a handle was removed earlier, typically earlier in the same query
    /// (`sideEffect(__.drop())`, a dropped vertex's edges), and a later step needs its id, its
    /// label, its whole value, or writes to it.
    ///
    /// Reads of a removed element's *data* do not fail: its properties are absent, its adjacency
    /// is empty, and filters that need its data drop it (TinkerGraph behaves the same, except
    /// that `outV()`/`inV()` of a removed TinkerGraph edge still return its endpoints; here they
    /// are empty, a deviation listed with the one below).
    ///
    /// **Deviation from TinkerPop:** TinkerGraph still reports `id()` and `label()` of a removed
    /// element, because its element object keeps them. Graphersal's handle no longer has any
    /// data to read (a slot that was freed may already hold another element), so `id()`,
    /// `label()` and materializing the element in a terminal fail with this error instead. See
    /// `book/src/for_developers/tinkerpop_deviations.md`.
    #[error(
        "The {} was removed earlier in this query; its id, label and value are no longer available",
        match .kind { GraphNodeType::Vertex => "vertex", GraphNodeType::Edge => "edge" }
    )]
    #[non_exhaustive]
    ElementRemoved {
        /// Whether the removed element was a vertex or an edge.
        kind: GraphNodeType,
    },

    /// An element handle refers to storage in an invalid state.
    #[error("Invalid element state: {reason}")]
    #[non_exhaustive]
    InvalidElementState {
        /// What was invalid.
        reason: String,
    },

    /// A vertex label contained `"::"`, the multi-label delimiter of GraphML and GraphSON export.
    #[error(
        "Vertex label '{label}' is invalid: it contains \"::\", which GraphSON and GraphML vertex label export reserve as the multi-label delimiter"
    )]
    #[non_exhaustive]
    InvalidLabel {
        /// The rejected label.
        label: String,
    },

    /// A vertex/edge was written as a property value, which is never allowed.
    #[error(
        "Property '{property_name}' cannot hold {}: {}",
        match *.kind { "edge" => "an edge", "map with a non-string key" => "a map with a non-string key", _ => "a vertex" },
        if *.kind == "map with a non-string key" { "a property map is keyed by strings" } else { "vertices and edges are not property values" }
    )]
    #[non_exhaustive]
    InvalidPropertyValue {
        /// The property key that was assigned an element.
        property_name: String,
        /// `"vertex"`, `"edge"` or `"map with a non-string key"`.
        kind: &'static str,
    },

    /// `property(jpath(..), value)` could not write at the path (see [`PathWriteFault`]).
    #[error("Cannot write property path '{path}': {fault}")]
    #[non_exhaustive]
    InvalidPropertyPath {
        /// The canonical text of the full path that was written.
        path: String,
        /// Why the write was refused.
        fault: PathWriteFault,
    },

    /// A schema-level error, forwarded as-is.
    #[error(transparent)]
    Schema(#[from] SchemaError),

    /// A catalog definition (a saved query, ...) was refused, or does not exist.
    #[error(transparent)]
    Definition(#[from] DefinitionError),

    /// A commit hook's `before_commit` vetoed the commit: the whole unit (the traversal, the
    /// import, the applied change set) was rolled back and nothing of it is applied. `source`
    /// is the hook's own error, unchanged.
    #[error("The commit was rejected by the commit hook '{hook}': {source}")]
    #[non_exhaustive]
    CommitRejected {
        /// The [`CommitHook::name`](crate::graph::CommitHook::name) of the vetoing hook.
        hook: String,
        /// The error the hook returned.
        #[source]
        source: crate::graph::HookError,
    },

    /// [`GraphStorage::mark`] could not set a mark: no
    /// journal is registered, the name is empty or too long, or a unit is open.
    #[error("Cannot set a mark: {reason}")]
    #[non_exhaustive]
    MarkUnavailable {
        /// Why.
        reason: &'static str,
    },

    /// The graph's journal refused a mark (a name it has already recorded, a failed write).
    #[error("The mark was rejected by '{hook}': {source}")]
    #[non_exhaustive]
    MarkRejected {
        /// The name of the journal hook.
        hook: String,
        /// The journal's error.
        #[source]
        source: crate::graph::HookError,
    },

    /// The storage does not support an operation: a [`GraphStorage`] method the storage leaves
    /// at its refusing default (schemas, the catalog, compressed properties, commit hooks on a
    /// storage that is not atomic, see [`StorageCapabilities`](crate::graph::StorageCapabilities)),
    /// or an operation refused in the storage's current state (a write on the read-only `&G`
    /// view, a journal attached while a unit is open). `operation` names it.
    #[error("This graph storage does not support {operation}")]
    #[non_exhaustive]
    Unsupported {
        /// What is not supported.
        operation: &'static str,
    },

    /// A `u64` counter of the graph is at its maximum and cannot advance: the commit sequence
    /// number (the unit was rolled back, nothing of it is applied) or an auto-id sequence (no
    /// new auto id can be handed out). The counters never wrap around, because a reused commit
    /// number or id would corrupt a journal or a replica.
    #[error("The {sequence} of this graph is exhausted: it reached {max} and cannot advance", max = u64::MAX)]
    #[non_exhaustive]
    SequenceOverflow {
        /// Which counter: `"commit sequence number"`, `"vertex auto-id sequence"` or
        /// `"edge auto-id sequence"`.
        sequence: &'static str,
    },

    /// [`ChangeSetBuilder::build`](crate::changes::ChangeSetBuilder::build) refused a change set
    /// built outside the graph: a `commit_seq` of `0` with a commit time, a negative commit time,
    /// or a definition change without an image of its own kind and name.
    #[error("Invalid change set: {reason}")]
    #[non_exhaustive]
    InvalidChangeSet {
        /// What is wrong with it.
        reason: String,
    },

    /// A unit that is not a traversal (a GraphML or GraphSON import into a live graph, an
    /// applied change set, the commit of an outermost unit such as a
    /// [`transaction`](crate::graph::Transactional::transaction) closure) grew the memory in use over
    /// the memory budget `memory.limit`: the whole unit was rolled back. The same limit as
    /// [`TraverserError::ResourceLimitExceeded`] of a traversal, with the same `help()`
    /// advice for the host setting, naming the operation.
    #[error(
        "Resource limit '{limit}' exceeded by the {operation}{}",
        limit_detail(*.max, *.observed)
    )]
    #[non_exhaustive]
    ResourceLimitExceeded {
        /// What was stopped: `"GraphML import"`, `"GraphSON import"`, `"change set apply"` or
        /// `"commit"` (an outermost unit at its commit).
        operation: &'static str,
        /// The limit that was hit: `memory.limit`.
        limit: String,
        /// The configured maximum in bytes.
        max: Option<u64>,
        /// The bytes in use (or estimated) that crossed it.
        observed: Option<u64>,
    },
}

/// The `sequence` name of the commit sequence number in [`GraphError::SequenceOverflow`].
pub(crate) const COMMIT_SEQUENCE: &str = "commit sequence number";
/// The `operation` of [`GraphError::Unsupported`] for a script `withSideEffect(name, graph)`
/// whose target graph is not a `TraversalGraph`.
pub(crate) const SUBGRAPH_TARGET: &str =
    "being the subgraph() target of with_side_effect(name, graph) (only a TraversalGraph is)";
/// The `sequence` name of the vertex auto-id sequence in [`GraphError::SequenceOverflow`].
pub(crate) const VERTEX_ID_SEQUENCE: &str = "vertex auto-id sequence";
/// The `sequence` name of the edge auto-id sequence in [`GraphError::SequenceOverflow`].
pub(crate) const EDGE_ID_SEQUENCE: &str = "edge auto-id sequence";

/// Why a `property(jpath(..), value)` write was refused. Every fault is detected before anything
/// is changed, so a refused write leaves the property exactly as it was.
///
/// `at` is the canonical text of the path prefix whose value (or absence) caused the fault.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathWriteFault {
    /// The first path segment must name the property (`jpath("meta.k")`), not an index.
    FirstSegmentNotName,
    /// A key segment met something that is not an object (an array, a scalar, `null`, a map with
    /// non-string keys).
    KeyOnNonObject {
        /// The path of the value that is not an object.
        at: String,
        /// The kind of that value.
        found: &'static str,
    },
    /// An index segment met something that is not an array.
    IndexOnNonArray {
        /// The path of the value that is not an array.
        at: String,
        /// The kind of that value.
        found: &'static str,
    },
    /// An index outside `0..=len` (`len` appends, and only as the last segment), or a negative
    /// index outside `-len..=-1`.
    IndexOutOfRange {
        /// The path of the array.
        at: String,
        /// The requested index.
        index: i64,
        /// The current length of the array.
        len: usize,
    },
    /// An index segment needs an existing array; only key segments create missing containers.
    MissingArray {
        /// The path of the array that does not exist.
        at: String,
    },
    /// `property(Cardinality, jpath(..), value)` is not supported.
    CardinalityWithPath,
}

impl std::fmt::Display for PathWriteFault {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PathWriteFault::FirstSegmentNotName => {
                write!(f, "the first segment must name the property, not an index")
            }
            PathWriteFault::KeyOnNonObject { at, found } => {
                write!(
                    f,
                    "'{at}' is {} {found}, not an object, so a key cannot be set on it",
                    article(found)
                )
            }
            PathWriteFault::IndexOnNonArray { at, found } => {
                write!(
                    f,
                    "'{at}' is {} {found}, not an array, so an index cannot be used on it",
                    article(found)
                )
            }
            PathWriteFault::IndexOutOfRange { at, index, len } => {
                write!(
                    f,
                    "index {index} is out of range for the array '{at}' of length {len}"
                )
            }
            PathWriteFault::MissingArray { at } => {
                write!(
                    f,
                    "the array '{at}' does not exist, and an index segment never creates one"
                )
            }
            PathWriteFault::CardinalityWithPath => {
                write!(
                    f,
                    "property(Cardinality, jpath(..), value) is not supported"
                )
            }
        }
    }
}

/// Constructors for the errors the [`GraphStorage`] contract asks
/// an implementation to return. The variants are `#[non_exhaustive]`, so a storage outside this
/// crate builds them here.
impl GraphError {
    /// [`GraphError::Unsupported`]: this storage does not support `operation` (for example
    /// `"schemas"` or `"commit hooks"`, the texts the trait's defaults use).
    pub fn unsupported(operation: &'static str) -> Self {
        GraphError::Unsupported { operation }
    }

    /// [`GraphError::ElementRemoved`]: a write (or an id/label read) through a handle whose
    /// element was removed.
    pub fn element_removed(kind: GraphNodeType) -> Self {
        GraphError::ElementRemoved { kind }
    }

    /// [`GraphError::VertexNotFound`] for the vertex id `id`.
    pub fn vertex_not_found(id: impl Into<String>) -> Self {
        GraphError::VertexNotFound { id: id.into() }
    }

    /// [`GraphError::EdgeNotFound`] for the edge id `id`.
    pub fn edge_not_found(id: impl Into<String>) -> Self {
        GraphError::EdgeNotFound { id: id.into() }
    }

    /// [`GraphError::VertexIdUniqueConstraint`]: `add_vertex` was given an id already in use.
    pub fn duplicate_vertex_id(id: impl Into<String>) -> Self {
        GraphError::VertexIdUniqueConstraint { id: id.into() }
    }

    /// [`GraphError::EdgeIdUniqueConstraint`]: `add_edge` was given an id already in use.
    pub fn duplicate_edge_id(id: impl Into<String>) -> Self {
        GraphError::EdgeIdUniqueConstraint { id: id.into() }
    }

    /// [`GraphError::InvalidLabel`]: a vertex label containing `"::"`.
    pub fn invalid_label(label: impl Into<String>) -> Self {
        GraphError::InvalidLabel {
            label: label.into(),
        }
    }

    /// [`GraphError::InvalidElementState`]: the storage found itself in a state it cannot serve.
    pub fn invalid_element_state(reason: impl Into<String>) -> Self {
        GraphError::InvalidElementState {
            reason: reason.into(),
        }
    }

    /// [`GraphError::InvalidPropertyValue`]: the property `property_name` was given a value it
    /// cannot hold. `kind` names what was found, with the texts the crate uses: `"vertex"`,
    /// `"edge"` or `"map with a non-string key"`. A storage normally gets this error from
    /// `graphersal::storage::check_property_value` instead of building it.
    pub fn invalid_property_value(property_name: impl Into<String>, kind: &'static str) -> Self {
        GraphError::InvalidPropertyValue {
            property_name: property_name.into(),
            kind,
        }
    }

    /// [`GraphError::InvalidPropertyPath`]: a write at `path` was refused for `fault`; the error
    /// carries the canonical text of the path. A storage normally gets this error from the path
    /// helpers of `graphersal::storage` (`write_path`, `write_path_in`, `path_property_name`).
    pub fn invalid_property_path(path: &crate::value::JsonPath, fault: PathWriteFault) -> Self {
        GraphError::InvalidPropertyPath {
            path: path.to_string(),
            fault,
        }
    }

    /// [`GraphError::MarkUnavailable`]: this storage cannot set a mark now, for `reason` (no
    /// journal, a bad name, an open unit).
    pub fn mark_unavailable(reason: &'static str) -> Self {
        GraphError::MarkUnavailable { reason }
    }

    /// [`GraphError::ElementRemoved`] for a vertex.
    pub(crate) fn vertex_removed() -> Self {
        GraphError::ElementRemoved {
            kind: GraphNodeType::Vertex,
        }
    }

    /// [`GraphError::ElementRemoved`] for an edge.
    pub(crate) fn edge_removed() -> Self {
        GraphError::ElementRemoved {
            kind: GraphNodeType::Edge,
        }
    }
}

/// The own help of a hook's veto that brings one: a [`HookRefusal`](crate::graph::HookRefusal),
/// or a Store's refusal (`persist::PersistError`: a store in maintenance mode, a backup, a
/// store frozen by damage or read-only for this version, a journal write failure).
fn refusal_help(source: &(dyn std::error::Error + Send + Sync + 'static)) -> Option<String> {
    if let Some(refusal) = source.downcast_ref::<crate::graph::HookRefusal>() {
        return Some(refusal.help().to_string());
    }
    #[cfg(feature = "persist")]
    if let Some(err) = source.downcast_ref::<crate::persist::PersistError>() {
        return err.help();
    }
    None
}

fn article(kind: &str) -> &'static str {
    if kind.starts_with(['a', 'e', 'i', 'o', 'u']) {
        "an"
    } else {
        "a"
    }
}

impl DiagnosticError for GraphError {
    fn help(&self) -> Option<String> {
        match self {
            GraphError::VertexNotFound { .. } => Some(
                "Verify that the vertex ID exists in the graph before referencing it. A vertex that was \
                 dropped earlier (also earlier in the same traversal, for example by \
                 side_effect(__.drop())) no longer exists, and neither do its edges; do not add an \
                 edge to it, or add the edge before the drop."
                    .to_string(),
            ),
            GraphError::EdgeNotFound { .. } => Some(
                "Verify that the edge ID exists in the graph before referencing it.".to_string(),
            ),
            GraphError::VertexIdUniqueConstraint { .. } => {
                Some(
                    "Ensure vertex IDs are unique when adding new vertices. To get the vertex \
                     with this id if it exists and create it otherwise, use mergeV, for example \
                     g.merge_v(#{\"T.id\": \"1\"}).option(Merge.onCreate, #{\"T.label\": \"person\"})."
                        .to_string(),
                )
            }
            GraphError::EdgeIdUniqueConstraint { .. } => {
                Some(
                    "Ensure edge IDs are unique when adding new edges. To get the edge with this \
                     id if it exists and create it otherwise, use mergeE, for example \
                     g.merge_e(#{\"T.id\": \"7\"}).option(Merge.onCreate, #{\"T.label\": \
                     \"knows\", \"Direction.OUT\": \"1\", \"Direction.IN\": \"2\"})."
                        .to_string(),
                )
            }
            GraphError::ElementRemoved { kind } => {
                let (kind, example) = match kind {
                    GraphNodeType::Vertex => (
                        "vertex",
                        "g.v(\"1\").as(\"a\").element_map().as(\"m\")\
                         .select(\"a\").side_effect(__.drop()).select(\"m\")",
                    ),
                    GraphNodeType::Edge => (
                        "edge",
                        "g.v(\"1\").out_e().as(\"e\").element_map().as(\"m\")\
                         .select(\"e\").side_effect(__.drop()).select(\"m\")",
                    ),
                };
                Some(format!(
                    "The {kind} was dropped earlier in the same query (by drop(), \
                     side_effect(__.drop()), or together with a dropped vertex), but a later step \
                     still holds it, through a step label (as()/select()), a side effect \
                     (aggregate()/store()/cap()), a path or a sack. A removed {kind} has no \
                     properties and no edges, its id(), label() and value cannot be returned, \
                     and it cannot be changed. Materialize what you need before the drop (element_map(), value_map(), \
                     project()) and keep that instead, for example {example}, or run the drop as \
                     a separate query after reading. A lazy value such as values(\"name\") or \
                     id() taken before the drop is read only when it is returned, so it fails \
                     the same way."
                ))
            }
            GraphError::InvalidElementState { .. } => {
                Some("Ensure element properties and states are valid.".to_string())
            }
            GraphError::InvalidLabel { .. } => Some(
                "Rename the label to remove \"::\" — e.g. add_v(\"Admin_Role\") instead of \
                 add_v(\"Admin::Role\") — since GraphSON and GraphML export join a vertex's multiple labels \
                 with \"::\" (see labels()/has_label())."
                    .to_string(),
            ),
            GraphError::InvalidPropertyValue {
                property_name,
                kind,
            } if *kind == "map with a non-string key" => Some(format!(
                "A property value that is a map must have string keys, because a stored map is a \
                 plain object. Store the map under string keys, for example \
                 property(\"{property_name}\", #{{\"29\": 1}}), or keep the data in the stream and \
                 show a map with a non-string key with to_json(), for example \
                 g.v().group_count().by(\"age\").to_json()."
            )),
            GraphError::InvalidPropertyValue {
                property_name,
                kind,
            } => {
                let (step, lookup) = if *kind == "edge" {
                    ("out_e(\"knows\")", "g.e(id)")
                } else {
                    ("out(\"knows\")", "g.v(id)")
                };
                Some(format!(
                    "Store the {kind}'s id instead of the {kind} itself, e.g. \
                     property(\"{property_name}\", __.{step}.id()), and look the {kind} up \
                     again with {lookup}."
                ))
            }
            GraphError::InvalidPropertyPath { path, fault } => Some(match fault {
                PathWriteFault::FirstSegmentNotName => format!(
                    "Start the path with the property name, for example \
                     property(jpath(\"meta.tags[0]\"), \"x\"); '{path}' begins with an index."
                ),
                PathWriteFault::KeyOnNonObject { .. } => format!(
                    "A key segment needs an object. Read the current value first, for example \
                     g.v().values(jpath(\"{path}\")), or write a whole object at a shorter \
                     path, for example property(jpath(\"meta\"), #{{\"k\": 1}}). Missing keys are \
                     created, existing scalars and arrays are never overwritten by a deeper path."
                ),
                PathWriteFault::IndexOnNonArray { .. } => format!(
                    "An index segment needs an array. Use a key segment for an object, for example \
                     jpath(\"meta.tags\") instead of jpath(\"meta[0]\"), or write the array first \
                     with property(jpath(\"meta.tags\"), [\"x\"]). Written path: {path}."
                ),
                PathWriteFault::IndexOutOfRange { .. } => format!(
                    "Use an index inside the array, [len] to append as the last segment, or a \
                     negative index [-1] for the last element; arrays are never padded with null. \
                     Written path: {path}."
                ),
                PathWriteFault::MissingArray { .. } => format!(
                    "Create the array first, for example property(jpath(\"meta.tags\"), [\"x\"]), \
                     then address its elements. Only key segments create missing objects. Written \
                     path: {path}."
                ),
                PathWriteFault::CardinalityWithPath => {
                    "Graphersal stores one value per property; write a nested value with \
                     property(jpath(\"meta.tags[0]\"), \"x\") without a Cardinality, or build the \
                     whole value and write it with property(Cardinality.single, \"meta\", value)."
                        .to_string()
                }
            }),
            GraphError::Schema(err) => err.help(),
            GraphError::Definition(err) => err.help(),
            GraphError::CommitRejected { hook, source }
                if refusal_help(source.as_ref()).is_some() =>
            {
                refusal_help(source.as_ref()).map(|own| {
                    format!(
                        "The commit hook '{hook}' refused the commit, so the whole unit was \
                         rolled back and left nothing behind. {own}"
                    )
                })
            }
            GraphError::CommitRejected { .. } => Some(
                "A commit hook registered by the host application (for example the write-ahead \
                 log of a server) refused the changes, so the whole unit was rolled back: the \
                 query, transaction, whole script, import or applied change set left nothing \
                 behind. The hook's reason is in the message; once its cause is fixed (disk \
                 space, a replica, a business rule), run the query again unchanged. To see what would \
                 have been committed without committing, run it in a dry run (Rust: \
                 Transactional::dry_run), which calls no hooks."
                    .to_string(),
            ),
            GraphError::MarkUnavailable { .. } => Some(
                "A mark is a record in the graph's journal: register one first (Rust: \
                 persist::Journal::new(file, Durability::EveryCommit).attach(&mut graph), \
                 Python: graph.start_journal(path)), give it a name of 1 to 255 bytes and set \
                 it between queries, for example g.mark(\"before-import\"), not inside a \
                 transaction. A storage that keeps no journal (a custom GraphStorage without \
                 one) cannot set marks at all."
                    .to_string(),
            ),
            GraphError::MarkRejected { .. } => Some(
                "Mark names are unique within a journal: choose a new one, for example \
                 g.mark(\"before-import-2\"). When the message reports a write failure, the \
                 journal is unusable until the graph is recovered from its snapshot and journal."
                    .to_string(),
            ),
            GraphError::Unsupported { operation } if *operation == SUBGRAPH_TARGET => Some(
                "subgraph() writes only into a TraversalGraph, and every graph a script builds \
                 is one: let the subgraph land in a graph of the script, for example \
                 g.e().has_label(\"knows\").subgraph(\"sg\").cap(\"sg\") or \
                 g.e().has_label(\"knows\").to_graph(), and copy what the host graph needs \
                 into it with add_v()/add_e() or merge_v()/merge_e()."
                    .to_string(),
            ),
            GraphError::Unsupported { operation } => Some(format!(
                "The graph's storage does not implement {operation}: a GraphStorage \
                 implementation supports only what it implements of the trait (the trait's \
                 defaults refuse), and some operations are refused only in a state (on a \
                 read-only view, while a unit is open). Check the storage's documentation and \
                 what its GraphStorage::capabilities() report before using the operation (for \
                 example commit hooks and dry runs need change_capture, and therefore atomic), \
                 or run it on a TraversalGraph, the reference storage, which implements every \
                 operation of the trait."
            )),
            GraphError::SequenceOverflow { sequence } if *sequence == COMMIT_SEQUENCE => Some(
                "The graph was numbered close to the end of the commit sequence (for example by \
                 TraversalGraph::with_last_commit_seq(u64::MAX), or by replaying a change set with \
                 such a commit_seq), so no further unit can commit; the failed one was rolled \
                 back and left nothing behind. Rebuild the graph from its data with a small \
                 commit sequence number: export it and load it into a new TraversalGraph."
                    .to_string(),
            ),
            GraphError::SequenceOverflow { .. } => Some(
                "An explicit numeric id raises the auto-id sequence to it, so an element added \
                 with an id at the end of the range (for example \
                 g.add_v(\"person\").property(T.id, \"18446744073709551615\")) leaves no room \
                 for further auto ids; the failed query was rolled back. Give new elements \
                 explicit ids, for example g.add_v(\"person\").property(T.id, \"p-1\"), and \
                 prefer non-numeric ids for imported elements, which do not move the sequence."
                    .to_string(),
            ),
            GraphError::InvalidChangeSet { .. } => Some(
                "A change set built with ChangeSet::builder carries the position of a real commit \
                 (commit_seq from 1 on, with its commit time in microseconds since the Unix \
                 epoch) or is a never-committed one (both 0, like a dry run). A \
                 Mutation::set_definition needs a before or an after definition, both of the \
                 kind and name it names; build it with Mutation::set_definition(kind, name, \
                 before, after)."
                    .to_string(),
            ),
            GraphError::ResourceLimitExceeded {
                operation,
                limit,
                max,
                observed,
            } => Some(unit_resource_limit_help(operation, limit, *max, *observed)),
        }
    }
}

/// Errors encountered during graph import/export or IO operations.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum IOError {
    /// A file could not be opened/read.
    #[error("Failed to read file '{path}': {source}")]
    #[non_exhaustive]
    FileRead {
        /// The file path.
        path: String,
        /// The underlying I/O failure.
        #[source]
        source: std::io::Error,
    },

    /// The GraphML XML could not be parsed.
    #[error("XML parsing error at position {position}: {message}")]
    #[non_exhaustive]
    XmlParse {
        /// Byte offset of the failure.
        position: u64,
        /// What went wrong.
        message: String,
    },

    /// A file could not be created or written.
    #[error("Failed to write file '{path}': {source}")]
    #[non_exhaustive]
    FileWrite {
        /// The file path (`<GraphSON output>` for a caller's writer).
        path: String,
        /// The underlying I/O failure.
        #[source]
        source: std::io::Error,
    },

    /// A GraphSON line (line form) or document (wrapped form) is not valid JSON or not a vertex.
    #[error("GraphSON parse error at line {line}: {message}")]
    #[non_exhaustive]
    GraphSONParse {
        /// The 1-based line (line form) or vertex position (wrapped form).
        line: usize,
        /// What went wrong (with the byte offset inside the line, where known).
        message: String,
    },

    /// The input is a GraphSON variant Graphersal does not read (typed GraphSON 1.0 with
    /// `@class`, or the TinkerPop 2 Blueprints format).
    #[error("Unsupported GraphSON variant at line {line}: {reason}")]
    #[non_exhaustive]
    UnsupportedGraphSON {
        /// The 1-based line where it was detected.
        line: usize,
        /// Which variant it is.
        reason: String,
    },

    /// One GraphSON line (line form) or the whole document (wrapped form) is larger than the
    /// importer's `max_text_bytes`.
    #[error("GraphSON input at line {line} is larger than the limit of {limit} bytes")]
    #[non_exhaustive]
    InputTooLarge {
        /// The 1-based line that is too long.
        line: usize,
        /// The limit, in bytes.
        limit: usize,
    },

    /// The file's extension is not a supported graph file format.
    #[error("Unsupported graph file format: '{path}'")]
    #[non_exhaustive]
    UnsupportedFormat {
        /// The offending file path.
        path: String,
    },

    /// A schema JSON file failed to parse.
    #[cfg(feature = "serde")]
    #[error("JSON parsing error: {0}")]
    JsonParse(#[from] serde_json::Error),

    /// A packed snapshot file (`.gsnap`) could not be read or written (feature `persist`).
    #[cfg(feature = "persist")]
    #[error("Snapshot '{path}': {source}")]
    #[non_exhaustive]
    Snapshot {
        /// The file path.
        path: String,
        /// The persistence error.
        #[source]
        source: Box<crate::persist::PersistError>,
    },

    /// A required XML attribute was missing on an element.
    #[error("Missing required XML attribute '{attribute}' on element '{element}'")]
    #[non_exhaustive]
    MissingAttribute {
        /// The XML element name.
        element: String,
        /// The missing attribute name.
        attribute: String,
    },

    /// An XML attribute's value did not have the expected shape.
    #[error(
        "Invalid attribute '{attribute}' value '{value}' for key '{key}' (expected '{expected_type}')"
    )]
    #[non_exhaustive]
    InvalidAttributeValue {
        /// The GraphML key this attribute is for.
        key: String,
        /// The XML attribute name.
        attribute: String,
        /// The value actually found.
        value: String,
        /// The expected value shape.
        expected_type: String,
    },

    /// A property holds `NaN`/`Infinity`, which GraphML export cannot represent.
    #[error("Property '{key}' holds the non-finite float {value}, which GraphML cannot represent")]
    #[non_exhaustive]
    NonFiniteFloat {
        /// The offending property's key.
        key: String,
        /// The non-finite value, rendered.
        value: String,
    },

    /// A property is declared as a union of an array/object and a text type (`string`/`uuid`):
    /// GraphML writes all of them as text, so an import cannot tell which one a value is.
    #[error(
        "Property '{key}' is declared as {declared}, a union of an array/object and a text type, \
         which GraphML import cannot tell apart"
    )]
    #[non_exhaustive]
    AmbiguousContainerImport {
        /// The offending property's key.
        key: String,
        /// The declared type, in canonical spelling.
        declared: String,
    },

    /// The value of a property declared as an array/object is not valid JSON text.
    #[error(
        "Property '{key}' is declared as {declared}, but its GraphML value is not valid JSON: \
         {reason}"
    )]
    #[non_exhaustive]
    InvalidJsonValue {
        /// The offending property's key.
        key: String,
        /// The declared type, in canonical spelling.
        declared: String,
        /// Why the text was rejected (with its byte offset).
        reason: String,
    },

    /// A graph-level error encountered while applying imported data, forwarded as-is.
    #[error(transparent)]
    Graph(#[from] GraphError),
}

impl DiagnosticError for IOError {
    fn help(&self) -> Option<String> {
        match self {
            IOError::FileRead { .. } => Some(
                "Check if the file path is correct and accessible with read permissions."
                    .to_string(),
            ),
            IOError::XmlParse { .. } => {
                Some("Verify that the XML file is well-formed.".to_string())
            }
            IOError::FileWrite { .. } => Some(
                "Check that the directory exists and is writable, and that the disk is not full."
                    .to_string(),
            ),
            IOError::GraphSONParse { .. } => Some(
                "GraphSON is read as one vertex JSON object per line (TinkerPop's default, what \
                 g.io(file).write() produces) or as one document {\"vertices\": [...]}. Fix the \
                 JSON on the named line; a number must fit int64/float64."
                    .to_string(),
            ),
            IOError::UnsupportedGraphSON { .. } => Some(
                "Re-export the graph from TinkerPop 3 as GraphSON 3.0 (the default of \
                 g.io(\"graph.json\").write()) or as GraphML, and import that file."
                    .to_string(),
            ),
            IOError::InputTooLarge { .. } => Some(
                "Write the graph in the line form (one vertex per line, TinkerPop's default) \
                 instead of one wrapped document, or raise the importer's limit with \
                 GraphSONImport::new().with_max_text_bytes(n)."
                    .to_string(),
            ),
            IOError::UnsupportedFormat { .. } => Some(
                "Graph files are read by their extension: GraphSON ('.json', '.jsonl', \
                 '.graphson') or GraphML ('.xml', '.graphml'), for example \
                 GraphSource::file(\"graph.json\") or GraphSource::file(\"graph.graphml\")."
                    .to_string(),
            ),
            #[cfg(feature = "serde")]
            IOError::JsonParse(_) => {
                Some("Verify that the JSON document is well-formed.".to_string())
            }
            #[cfg(feature = "persist")]
            IOError::Snapshot { source, .. } => source.help(),
            IOError::MissingAttribute { .. } => {
                Some("Ensure all required XML attributes are present.".to_string())
            }
            IOError::InvalidAttributeValue { .. } => {
                Some("Ensure attribute values match expected type formats.".to_string())
            }
            IOError::NonFiniteFloat { key, .. } => Some(format!(
                "GraphML writes numbers as finite decimal text, so NaN and infinities cannot be \
                 exported: overwrite or drop the property on the affected elements before \
                 exporting, e.g. .property(\"{key}\", 0.0), .remove_property(\"{key}\") (keeps the element) or \
                 .properties(\"{key}\").drop(). GraphSON keeps them: \
                 g.export_graphson(\"graph.json\")."
            )),
            IOError::AmbiguousContainerImport { key, .. } => Some(format!(
                "Declare '{key}' either as an array/object type (its GraphML text is then read \
                 as JSON) or as `string` (the text is kept as it is), not as a union of both, \
                 and set that schema on the target graph before importing. GraphSON keeps array/object \
                 values typed and needs no declaration: g.export_graphson(\"graph.json\")."
            )),
            IOError::InvalidJsonValue { key, .. } => Some(format!(
                "A property declared as an array/object is imported from its JSON text, as \
                 GraphML export writes it (e.g. [\"a\",\"b\"] or {{\"cpu\":2}}). Fix the value \
                 of '{key}' in the file, or declare '{key}' as `string` in the target graph's \
                 schema to import the text unchanged. GraphSON keeps array/object values typed: \
                 g.export_graphson(\"graph.json\")."
            )),
            IOError::Graph(err) => err.help(),
        }
    }
}

/// Errors encountered during script parsing, compilation, or execution.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum ScriptError {
    /// A Rhai script failed to evaluate.
    #[error("Script evaluation error near '{script_snippet}': {message}")]
    #[non_exhaustive]
    Eval {
        /// The offending script text, or a snippet of it.
        script_snippet: String,
        /// Failing line, when known.
        line: Option<usize>,
        /// Failing column, when known.
        column: Option<usize>,
        /// The underlying failure message.
        message: String,
    },

    /// A step name is not registered with the DSL.
    #[error("Unsupported step '{step_name}' in script context")]
    #[non_exhaustive]
    UnsupportedStep {
        /// The unrecognized step name.
        step_name: String,
    },

    /// A step was called with the wrong argument shape.
    #[error("Argument mismatch for step '{step_name}': expected {expected}, got {actual}")]
    #[non_exhaustive]
    ArgumentMismatch {
        /// The step's name.
        step_name: String,
        /// The expected argument shape.
        expected: String,
        /// The argument shape actually given.
        actual: String,
    },

    /// A named parameter binding was invalid (e.g. shadows a DSL global).
    #[error("Invalid script parameter '{parameter}': {message}")]
    #[non_exhaustive]
    InvalidParameter {
        /// The offending parameter name.
        parameter: String,
        /// Why it was rejected.
        message: String,
    },

    /// A script run as one unit (`script::eval_value_atomic`, `script::eval_value_dry_run`)
    /// returned a closure or function pointer (also inside an array or a map). The script's graph is private while it runs, so
    /// a closure that captured `g` would point at an empty graph once the script ends: the
    /// script is rejected and everything it changed is rolled back.
    #[error("A script run as one unit cannot return a closure or function pointer ({location})")]
    #[non_exhaustive]
    ReturnedClosure {
        /// Where the closure was found: `the result`, or a path such as `result[2].f`.
        location: String,
    },

    /// `query(..)` was called after steps (`g.v().query("x")`) or on the anonymous spawn
    /// (`__.query("x")`): a saved query starts a traversal, `g.query("x")`; calling one
    /// mid-traversal is a later feature (`roadmap/saved-queries.md`, section 9).
    #[error("query(\"{name}\") can only start a traversal, it cannot follow {position}")]
    #[non_exhaustive]
    QueryNotAtStart {
        /// The saved query named in the call.
        name: String,
        /// Where it was called: `other steps` or `__ (an anonymous traversal)`.
        position: String,
    },

    /// Saved queries called each other deeper than the call depth bound (16), usually a
    /// query that calls itself, directly or through others.
    #[error("Saved query calls nested deeper than {limit} levels (calling '{name}')")]
    #[non_exhaustive]
    QueryDepthExceeded {
        /// The query whose call went past the bound.
        name: String,
        /// The bound.
        limit: usize,
    },

    /// A call passed an argument the saved query does not declare.
    #[error("Saved query '{query}' has no parameter '{argument}'")]
    #[non_exhaustive]
    UnknownQueryArgument {
        /// The saved query.
        query: String,
        /// The argument name as passed.
        argument: String,
        /// The parameters the query declares, in signature order.
        parameters: Vec<String>,
    },

    /// A call left out an argument whose parameter has no default.
    #[error(
        "Saved query '{query}' needs the argument '{parameter}' ({expected}), it has no default"
    )]
    #[non_exhaustive]
    MissingQueryArgument {
        /// The saved query.
        query: String,
        /// The required parameter.
        parameter: String,
        /// Its declared type (`int64`, `string`, ...).
        expected: String,
    },

    /// An argument does not satisfy its parameter's schema (type or constraint), or is not a
    /// data value (a traversal, a closure).
    #[error("Invalid argument '{parameter}' for saved query '{query}': {reason}")]
    #[non_exhaustive]
    InvalidQueryArgument {
        /// The saved query.
        query: String,
        /// The parameter.
        parameter: String,
        /// What is wrong with the value.
        reason: String,
    },

    /// The body of a saved query does not compile, or is not exactly one function named like
    /// the query whose parameters are the declared ones.
    #[error("Invalid body of saved query '{query}': {reason}")]
    #[non_exhaustive]
    InvalidQueryBody {
        /// The saved query.
        query: String,
        /// What is wrong with the body.
        reason: String,
    },

    /// A saved query returned a traversal with a writing step: saved queries are read-only,
    /// also through what they return.
    #[error("Saved query '{query}' returned a traversal with a writing step ({location})")]
    #[non_exhaustive]
    QueryReturnedWrite {
        /// The saved query.
        query: String,
        /// Where in the result: `the result` or a path such as `result[1]`.
        location: String,
    },
}

/// The reason of the [`TraverserError::PermissionDenied`] a saved query's read-only
/// restriction gives; its help explains the rule instead of the host's authorizer.
pub(crate) const SAVED_QUERY_READ_ONLY: &str = "a saved query is read-only";

impl DiagnosticError for ScriptError {
    fn help(&self) -> Option<String> {
        match self {
            ScriptError::Eval { .. } => {
                Some("Check script syntax and expressions at indicated line/column.".to_string())
            }
            ScriptError::ReturnedClosure { location } => Some(format!(
                "Return data or a traversal instead of a closure: run the closure inside the \
                 script and return its result (for example `let f = |x| x + 1; f.call(1)` \
                 instead of `|x| x + 1`), or return the traversal itself \
                 (`g.v().has_label(\"person\")`), which runs against the real graph when it is \
                 rendered. The closure was found at {location}."
            )),
            ScriptError::UnsupportedStep { .. } => {
                Some("Verify step name and DSL script compatibility.".to_string())
            }
            ScriptError::ArgumentMismatch { step_name, .. }
                if matches!(step_name.as_str(), "value_map" | "valueMap") =>
            {
                Some(
                    "value_map() takes property keys as strings; a leading `true` adds id and \
                     label: g.v().value_map(true, \"name\"). A boolean is accepted only as the \
                     first argument, and a null key (`()`) is ignored. element_map() returns the \
                     same shape with plain values instead of lists: g.v().element_map(\"name\"). \
                     A key can also be a jpath(..) into a nested value, keyed by the canonical \
                     path text: g.v().value_map(jpath(\"meta.k\"))."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { step_name, .. }
                if matches!(step_name.as_str(), "and" | "or" | "not" | "negate") =>
            {
                Some(
                    "P.and(), P.or(), P.not() and negate() combine predicates only. Combine two \
                     predicates with p.and(q) / p.or(q), for example \
                     g.v().has(\"age\", P.gt(18).and(P.lt(30))) or \
                     g.v().has(\"age\", P.lt(18).or(P.gt(65))); complement one with P.not(p) or \
                     p.negate(), for example g.v().where(P.not(P.within(\"a\"))). To combine \
                     traversals instead, use the traversal combinators: \
                     g.v().where(__.and(__.out(), __.has(\"age\"))) or \
                     g.v().and(__.out(\"knows\"), __.has(\"age\", P.gt(30)))."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { step_name, .. }
                if matches!(step_name.as_str(), "choose" | "branch") =>
            {
                Some(
                    "choose(selector) and branch(selector) take a traversal or the tokens T.label / \
                     T.id as the selector, for example \
                     g.v().choose(T.label).option(\"person\", __.out(\"knows\")) or \
                     g.v().choose(__.values(\"age\")).option(P.gt(30), __.constant(\"old\")). \
                     The two- and three-argument forms take a traversal or a predicate as the \
                     condition, for example \
                     g.v().values(\"age\").choose(P.gt(30), __.constant(\"old\"), __.constant(\"young\")); \
                     without the third argument a traverser that fails the condition passes through \
                     unchanged. A property key (T.key), a string or a number is not a selector."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "add_e" => Some(
                "add_e() takes the edge label as a string, or as a traversal whose first result is \
                 the label, for example g.v(\"1\").add_e(\"knows\").to(\"2\") or \
                 g.v().as(\"a\").out_e().as(\"b\").in_v().add_e(__.select(\"b\").label()).to(\"a\"). \
                 A list of labels is not accepted."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, .. }
                if matches!(step_name.as_str(), "property" | "has" | "values" | "has_not" | "has_property") =>
            {
                Some(
                    "A property key is a string (a literal name) or a jpath(..) value (a path into a \
                     nested value); a number, a map or another type is not a key. For example \
                     g.v().property(\"name\", \"x\"), g.v().property(jpath(\"meta.tags[0]\"), \"x\") or \
                     g.v().has(jpath(\"meta.k\"), 1). A dotted string such as \"meta.k\" is never \
                     parsed as a path: wrap it in jpath(\"meta.k\")."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "remove_property" => Some(
                "remove_property() takes property keys as strings or jpath(..) values, one key or an \
                 array of keys, for example g.v().has_label(\"person\").remove_property(\"age\") or \
                 g.v().remove_property([\"age\", \"name\"]); a jpath removes the value below a \
                 property, for example g.v().remove_property(jpath(\"meta.tags[0]\")) (an array \
                 element is removed with shift, a missing path is a no-op); without an argument it \
                 removes every property of the element. The step keeps the element, so \
                 values(\"name\") can follow. property(k, ()) stores a null and does not remove."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "to_map" => Some(
                "to_map() turns a map into a Rhai object map, whose keys are strings, so it fails \
                 for a map with a non-string key such as the result of group_count().by(\"age\"). \
                 Read an entry with an indexer, for example \
                 let m = g.v().group_count().by(\"age\").next(); m[29]; list the keys with m.keys(); \
                 or show the whole map with g.v().group_count().by(\"age\").to_json()."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "property_json" => Some(
                "property_json() takes JSON-compatible values, and a JSON object has string keys, so \
                 a map with a non-string key (for example 29 or a list) is rejected. Use string keys, \
                 for example property_json(#{\"29\": 1}); to show a map with a non-string key use \
                 to_json(), for example g.v().group_count().by(\"age\").to_json()."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "Set.of" => Some(
                "Set.of(...) and Set.of_list([...]) take plain values: strings, numbers, booleans, \
                 UUIDs or null (an element or a traversal is not a value of a set). For example \
                 g.with_side_effect(\"a\", Set.of(\"alice\", \"bob\")).v().both().values(\"name\")\
                 .aggregate(\"a\").cap(\"a\") or Set.of_list([\"alice\", \"bob\"]); Set.of() starts an \
                 empty set."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "glob_path" => Some(
                "glob_path(pattern, #{...}) accepts the options max_depth (an integer from 1: the \
                 deepest level below the start vertex the walk visits) and prune (an anonymous \
                 traversal: a visited vertex for which it yields a result is not descended into, \
                 but is still emitted when it matches); the keys edges, path and case_insensitive \
                 are reserved. For example \
                 g.v(\"root\").glob_path(\"**/*.rs\", #{max_depth: 3, prune: __.has(\"name\", \"target\")}).by(\"name\")."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, .. } if step_name == "select" => Some(
                "select() reads step labels, map keys or side-effect keys: select(\"a\"), \
                 select(\"a\", \"b\") (a map), select(Column.keys) (the keys of a map). When a \
                 label was set several times, name the occurrence with a Pop as the FIRST argument: \
                 select(Pop.first, \"a\"), select(Pop.last, \"a\") (the default), \
                 select(Pop.all, \"a\") (a list of every occurrence) or select(Pop.mixed, \"a\"), \
                 for example g.v().as(\"a\").out().as(\"a\").select(Pop.all, \"a\") or \
                 g.v().as(\"a\").out().as(\"b\").select(Pop.first, \"a\", \"b\"). The labels after the \
                 Pop are strings (or one array of strings), and at least one is required. The key \
                 can also be computed by a traversal, with exactly one key: \
                 select(Pop.all, __.constant(\"a\")) or select(__.constant(\"a\")); its first \
                 result must be a string."
                    .to_string(),
            ),
            ScriptError::ArgumentMismatch { step_name, actual, .. }
                if matches!(step_name.as_str(), "has_id" | "has_label" | "has_key")
                    && actual.contains("predicate mixed") =>
            {
                Some(
                    "has_id(), has_label() and has_key() take either plain values or ONE predicate, \
                     never both in one call. Use P.within to combine values, for example \
                     g.v().has_id(P.within([\"1\", \"2\"])) or g.v().has_label(P.neq(\"person\")); \
                     to combine conditions chain the steps: \
                     g.v().has_label(\"person\").has_id(P.neq(\"1\"))."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { step_name, .. }
                if matches!(step_name.as_str(), "V" | "E" | "has_id") =>
            {
                Some(
                    "v(), e() and has_id() take ids (strings, numbers, UUIDs), elements returned by \
                     next()/to_list(), or lists of them. For example: \
                     let e = g.e(\"11\").next(); g.e(e).to_list() or g.v([\"1\", \"2\"]).to_list(). \
                     A map is accepted only as an element, that is, with an `id` key. \
                     has_id() also takes one predicate, for example g.v().has_id(P.neq(\"1\"))."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { step_name, .. }
                if matches!(
                    step_name.as_str(),
                    "define_query"
                        | "define_queries"
                        | "query"
                        | "move_query"
                        | "describe_query"
                ) =>
            {
                Some(
                    "Saved queries take maps and strings: \
                     g.define_query(#{name: \"top\", folder: \"reports\", description: \"..\", \
                     params: #{limit: #{schema: #{type: \"integer\", minimum: 1}, default: 20}}, \
                     body: \"fn top(limit) { g.v().limit(limit) }\"}) (name and body required), \
                     g.define_queries(\"reports\", source, #{top: #{limit: \"integer\"}}), \
                     g.query(\"top\", #{limit: 5}) (named arguments in a map), \
                     g.move_query(\"top\", \"archive\") and g.describe_query(\"top\", \"..\") \
                     (\"\" or () for the root or no description). See the book page \"Saved \
                     queries\"."
                        .to_string(),
                )
            }
            ScriptError::ArgumentMismatch { .. } => {
                Some("Check function call signature and argument types in script.".to_string())
            }
            ScriptError::InvalidParameter { .. } => Some(
                "Bind named parameters with `eval_with_params` using identifier names that do \
                 not shadow the DSL globals (`g`, `__`, `_g`, `params`, `keys`, `values` and every token \
                 class such as `P`, `TextP`, `V`, `T`, `By`, `Order`, `Pick`, `GType`, `Pop`), for \
                 example params = {\"label\": \"person\"} used as \
                 g.v().has_label(label).to_list(). Positional parameters are 1-based: supply one \
                 value per placeholder to `eval_with_positional_params`, so that \
                 g.v().has_label($1).to_list() is evaluated with a single-element vector."
                    .to_string(),
            ),
            ScriptError::QueryNotAtStart { name, .. } => Some(format!(
                "Call a saved query at the start of a traversal, on g: g.query(\"{name}\") (with \
                 arguments g.query(\"{name}\", #{{limit: 5}})), and continue its result there, for \
                 example g.query(\"{name}\").values(\"name\"). Calling a saved query on incoming \
                 traversers (g.v().query(..), __.query(..)) is not supported yet; filter in the \
                 query itself, or pass the values it needs as arguments: \
                 let ids = g.v().has_label(\"person\").id().to_list(); g.query(\"{name}\", #{{ids: ids}})."
            )),
            ScriptError::QueryDepthExceeded { limit, .. } => Some(format!(
                "Saved queries may call each other at most {limit} levels deep; this bound stops a \
                 query that calls itself (directly or through other queries) without an end. \
                 Check the chain of g.query(..) calls in the bodies (g.get_query(name)[\"body\"] \
                 shows a body) and end the recursion, or compute the repetition inside one query \
                 with repeat(), for example g.v(id).repeat(__.out()).times(3)."
            )),
            ScriptError::UnknownQueryArgument {
                query, parameters, ..
            } => Some(if parameters.is_empty() {
                format!(
                    "'{query}' takes no arguments: call it as g.query(\"{query}\"). \
                     g.get_query(\"{query}\") shows its declaration."
                )
            } else {
                format!(
                    "Arguments are named after the parameters of '{query}': {}. For example \
                     g.query(\"{query}\", #{{{}: ..}}). g.get_query(\"{query}\") shows each \
                     parameter's schema and default; names are case-sensitive.",
                    parameters.join(", "),
                    parameters[0]
                )
            }),
            ScriptError::MissingQueryArgument {
                query, parameter, ..
            } => Some(format!(
                "Pass every parameter without a default by name, for example \
                 g.query(\"{query}\", #{{{parameter}: ..}}). A parameter with a default may be \
                 left out; give one a default by redefining the query with \
                 params: #{{{parameter}: #{{schema: .., default: ..}}}}."
            )),
            ScriptError::InvalidQueryArgument {
                query, parameter, ..
            } => Some(format!(
                "An argument is a data value (a string, a number, a boolean, a UUID, a list or a \
                 map, never a traversal or a closure) that satisfies its parameter's schema; types \
                 are exact (only an int64 is accepted where a float64 is declared). \
                 g.get_query(\"{query}\")[\"params\"] shows the schema of '{parameter}'; convert \
                 the value before the call, for example with parse_int(\"5\") or \
                 UUID.from_string(\"..\")."
            )),
            ScriptError::InvalidQueryBody { query, .. } => Some(format!(
                "The body of a saved query is the text of ONE Rhai function named like the query \
                 whose parameters are the declared ones, and nothing else, for example \
                 g.define_query(#{{name: \"{query}\", params: #{{limit: \"integer\"}}, body: \
                 \"fn {query}(limit) {{ g.v().limit(limit) }}\"}}). Several queries at once go \
                 through g.define_queries(folder, source) (one query per function, doc comments \
                 as descriptions). A stored body that no longer compiles is listed by \
                 g.queries() with status \"error\"; redefine it to fix it."
            )),
            ScriptError::QueryReturnedWrite { .. } => Some(
                "Saved queries are read-only, also through a traversal they return. Return a \
                 reading traversal (or its values) and write in a traversal of your own, for \
                 example let ids = g.query(\"q\").id().to_list(); \
                 g.v(ids).property(\"seen\", true).to_list()."
                    .to_string(),
            ),
        }
    }
}

/// Errors related to graph schema validation, topological constraints, and DDL operations.
#[derive(thiserror::Error, Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SchemaError {
    /// A vertex label isn't declared in `Closed` mode.
    #[error("Unknown vertex label '{label}' is not declared in the closed schema")]
    #[non_exhaustive]
    UnknownVertexLabel {
        /// The undeclared label.
        label: String,
        /// The labels the schema does declare.
        allowed: Vec<String>,
    },

    /// An edge label isn't declared in `Closed` mode.
    #[error("Unknown edge label '{label}' is not declared in the closed schema")]
    #[non_exhaustive]
    UnknownEdgeLabel {
        /// The undeclared label.
        label: String,
        /// The labels the schema does declare.
        allowed: Vec<String>,
    },

    /// An edge's source/target label pair isn't an allowed connection shape.
    #[error(
        "Disallowed edge connection: '(:{source_label})-[:{edge_label}]->(:{target_label})' is not defined in schema"
    )]
    #[non_exhaustive]
    InvalidEdgeTopology {
        /// The edge's source vertex label.
        source_label: String,
        /// The edge's label.
        edge_label: String,
        /// The edge's target vertex label.
        target_label: String,
        /// The connections the schema declares for the edge label, rendered
        /// `(:from)-[:edge]->(:to)`.
        allowed: Vec<String>,
    },

    /// A property isn't declared for this label in `Closed` mode.
    #[error(
        "Undeclared property '{property_name}' on {element_type} '{label}' is not declared and not admitted by the schema"
    )]
    #[non_exhaustive]
    UndeclaredProperty {
        /// `"vertex"` or `"edge"`.
        element_type: &'static str,
        /// The element's label.
        label: String,
        /// The undeclared property key.
        property_name: String,
    },

    /// A declared, non-nullable property is missing.
    #[error("Missing required property '{property_name}' on {element_type} '{label}'")]
    #[non_exhaustive]
    MissingRequiredProperty {
        /// `"vertex"` or `"edge"`.
        element_type: &'static str,
        /// The element's label.
        label: String,
        /// The missing property key.
        property_name: String,
    },

    /// Removing a declared, non-nullable (required) property would leave the element invalid.
    #[error("Cannot remove required property '{property_name}' from {element_type} '{label}'")]
    #[non_exhaustive]
    RequiredPropertyRemoval {
        /// `"vertex"` or `"edge"`.
        element_type: &'static str,
        /// The label that declares the property as required.
        label: String,
        /// The property key.
        property_name: String,
    },

    /// A stored value's logical type doesn't match the schema's declared type.
    #[error(
        "Type mismatch on {element_type} '{label}.{property_name}': expected {expected_type}, got {actual_type}"
    )]
    #[non_exhaustive]
    TypeMismatch {
        /// `"vertex"` or `"edge"`.
        element_type: &'static str,
        /// The element's label.
        label: String,
        /// The property key.
        property_name: String,
        /// The declared type.
        expected_type: String,
        /// The value's actual type.
        actual_type: String,
    },

    /// A written value could not be coerced to its declared type.
    #[error(
        "Cannot store {actual_value} in {element_type} '{label}.{property_name}' declared as {declared_type}: {reason}"
    )]
    #[non_exhaustive]
    CoercionFailed {
        /// `"vertex"` or `"edge"`.
        element_type: &'static str,
        /// The element's label.
        label: String,
        /// The property key.
        property_name: String,
        /// The declared type.
        declared_type: String,
        /// The value that failed to coerce, rendered.
        ///
        /// A `Box<str>` rather than a `String`: the rendering is never grown after it is built,
        /// and dropping the capacity word keeps [`SchemaError`] (and every error embedding it)
        /// below `clippy::result_large_err`'s threshold.
        actual_value: Box<str>,
        /// Why coercion failed; always one of the fixed reasons of the coercion rules.
        reason: &'static str,
    },

    /// A declared field constraint (`min`/`max`/`pattern`/...) was violated.
    #[error(
        "Constraint violation on '{label}.{property_name}': {constraint_rule} (actual: {actual_value})"
    )]
    #[non_exhaustive]
    ConstraintViolation {
        /// The element's label.
        label: String,
        /// The property key.
        property_name: String,
        /// The violated constraint, rendered.
        constraint_rule: String,
        /// The offending value, rendered.
        actual_value: String,
    },

    /// A field's `pattern` constraint is not a valid regular expression.
    #[error("Invalid schema pattern '{pattern}': {reason}")]
    #[non_exhaustive]
    InvalidPattern {
        /// The pattern's source text.
        pattern: String,
        /// Why it does not compile.
        reason: String,
    },

    /// A schema was applied to a graph whose existing data violates it. The graph and its
    /// previous schema are unchanged. The report lists every kind of violation, grouped by rule,
    /// with counts and a few sample ids.
    #[error("{report}")]
    #[non_exhaustive]
    ExistingDataViolatesSchema {
        /// The aggregated violations (boxed: keeps `SchemaError` small).
        report: Box<crate::graph::schema::SchemaViolationReport>,
    },

    /// A schema (JSON text, a map, a patch) is not valid in the schema format: unknown or
    /// unsupported keyword (anywhere, the envelope included), a wrong value, an unresolved or
    /// cyclic `$ref`, a pattern that does not compile, ...
    #[error("Invalid schema at {path}: {reason}")]
    #[non_exhaustive]
    InvalidSchema {
        /// Where, as a JSON Pointer into the input (`/vertices/person/schema/properties/age`).
        path: String,
        /// What is wrong there.
        reason: String,
        /// How to fix it (empty when there is nothing specific to say).
        hint: String,
    },
}

/// Why a catalog definition (a saved query, ...; see [`crate::catalog`]) was refused:
/// a rule of its name, folder, sizes or parameters, the catalog's size, a malformed stored or
/// exchanged form, or a definition that does not exist.
#[derive(thiserror::Error, Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DefinitionError {
    /// The definition's name breaks a naming rule (empty, too long, not an identifier, a
    /// reserved word).
    #[error("Invalid {kind} name '{name}': {reason}")]
    #[non_exhaustive]
    InvalidName {
        /// The kind of the definition (`query`, `kind 7`).
        kind: String,
        /// The name as given.
        name: String,
        /// Which rule it breaks.
        reason: String,
    },
    /// A folder path breaks a path rule (empty segment, leading or trailing `/`, too deep or
    /// too long).
    #[error("Invalid folder '{folder}' of '{name}': {reason}")]
    #[non_exhaustive]
    InvalidFolder {
        /// The definition the folder belongs to.
        name: String,
        /// The folder path as given.
        folder: String,
        /// Which rule it breaks.
        reason: String,
    },
    /// A field of a definition is too large, empty when it must not be, or of the wrong kind.
    #[error("Invalid {field} of '{name}': {reason}")]
    #[non_exhaustive]
    InvalidField {
        /// The definition the field belongs to.
        name: String,
        /// The field (`description`, `source`, `dialect`, `meta`, `payload`, ...).
        field: String,
        /// What is wrong with it.
        reason: String,
    },
    /// A parameter of a saved query is invalid: its name, its schema, or its default.
    #[error("Invalid parameter '{parameter}': {reason}")]
    #[non_exhaustive]
    InvalidParameter {
        /// The parameter name as given.
        parameter: String,
        /// What is wrong with it.
        reason: String,
    },
    /// The catalog holds its maximum number of definitions; a new one cannot be added.
    #[error("The catalog already holds {limit} definitions, the maximum")]
    #[non_exhaustive]
    TooManyDefinitions {
        /// The maximum number of definitions.
        limit: usize,
    },
    /// No definition of this kind has this name.
    #[error("There is no {kind} named '{name}'")]
    #[non_exhaustive]
    NotFound {
        /// The kind looked for (`query`, `kind 7`).
        kind: String,
        /// The name looked for.
        name: String,
    },
    /// A compression rule covers the same element kind, label and path as another rule.
    #[error("Conflicting compression rule '{name}': {reason}")]
    #[non_exhaustive]
    Conflict {
        /// The rule being stored.
        name: String,
        /// The rule already stored.
        existing: String,
        /// What they share.
        reason: String,
    },
    /// The JSON (or value) form of a definition or a catalog is malformed.
    #[error("Malformed definition: {reason}")]
    #[non_exhaustive]
    Malformed {
        /// What is wrong, with the place (`/definitions/2/params`).
        reason: String,
    },
}

impl DiagnosticError for DefinitionError {
    fn help(&self) -> Option<String> {
        use crate::graph::definition as d;
        Some(match self {
            DefinitionError::InvalidName { kind, .. } if kind == "compression" => format!(
                "A compression rule's name is an identifier of 1 to {} bytes (ASCII letters, \
                 digits and '_', starting with a letter or '_'), for example \"customer_cv\". \
                 It names the rule for g.drop_compression and g.recompress.",
                d::MAX_QUERY_NAME_BYTES
            ),
            DefinitionError::InvalidName { .. } => format!(
                "A saved query's name is also its Rhai function name and its MCP tool name: 1 to \
                 {} bytes of ASCII letters, digits and '_', starting with a letter or '_' (a \
                 letter before the first digit), not a Rhai keyword, for example \
                 \"top_customers\". Names are case-sensitive and unique per kind; group queries \
                 with a folder instead of a prefix in the name.",
                d::MAX_QUERY_NAME_BYTES
            ),
            DefinitionError::InvalidFolder { .. } => format!(
                "A folder is a '/'-separated path such as \"reports/sales\": non-empty segments \
                 without surrounding spaces, no leading or trailing '/', at most {} segments and \
                 {} bytes. Leave the folder out (or pass an empty one) for the root.",
                d::MAX_FOLDER_SEGMENTS,
                d::MAX_FOLDER_BYTES
            ),
            DefinitionError::InvalidField { field, .. } => match field.as_str() {
                "description" => format!(
                    "Keep the description to at most {} bytes; longer documentation belongs in \
                     the query's source as comments.",
                    d::MAX_DESCRIPTION_BYTES
                ),
                "source" => format!(
                    "The source is the text of one Rhai function, at most {} bytes; split a \
                     larger body into several saved queries that call each other.",
                    d::MAX_SOURCE_BYTES
                ),
                "path" => "A rule path names object keys only, from the top-level property \
                           down: \"cv\" or \"details.career.cv\" (or \
                           jpath(\"$.details.career.cv\")); an index such as [0] or [-1] is not \
                           allowed, arrays are not compressed."
                    .to_string(),
                "min_bytes" => format!(
                    "min_bytes is the shortest string (in UTF-8 bytes) that is compressed: 1 to \
                     {} (default {}); shorter strings stay plain.",
                    crate::graph::compression::MAX_MIN_BYTES,
                    crate::graph::compression::DEFAULT_MIN_BYTES
                ),
                "label" => "Name the vertex or edge label the rule applies to, for example \
                            \"customer\"; it need not exist yet."
                    .to_string(),
                "dialect" => format!(
                    "The dialect names the language of the source; this version writes \"{}\".",
                    d::QUERY_DIALECT
                ),
                _ => "Check the field against the limits of the catalog (book page \"Saved \
                      queries\")."
                    .to_string(),
            },
            DefinitionError::InvalidParameter { .. } => format!(
                "A parameter is {{\"schema\": <schema node>, \"default\": <value>}} (or just a \
                 type name such as \"integer\"): its name is a Rhai identifier that is not a \
                 DSL global (g, __, P, T, ...), its schema uses the node format of the graph \
                 schema (type, enum, minimum, maximum, pattern, ...) and its default, when \
                 given, satisfies that schema, for example \
                 {{\"limit\": {{\"schema\": {{\"type\": \"integer\", \"minimum\": 1}}, \
                 \"default\": 20}}}}. At most {} parameters.",
                d::MAX_PARAMETERS
            ),
            DefinitionError::TooManyDefinitions { .. } => {
                "Remove definitions that are no longer used before adding new ones.".to_string()
            }
            DefinitionError::NotFound { .. } => {
                "List the existing definitions first: g.queries() in the DSL (or \
                 g.queries(\"reports\") for one folder), GraphTraversalSource::list_definitions \
                 in Rust; names are case-sensitive, and a query is called by its name alone, \
                 never with its folder. Define a missing one with g.define_query(#{name: .., \
                 body: ..})."
                    .to_string()
            }
            DefinitionError::Conflict { existing, .. } => format!(
                "One rule per element kind, label and path: change the existing rule instead \
                 (define it again under its name '{existing}' with the new parameters), or drop \
                 it first with g.drop_compression(\"{existing}\")."
            ),
            DefinitionError::Malformed { .. } => {
                "A definition in JSON is an object with \"kind\" (\"query\") and \"name\", plus \
                 for a query \"source\", \"params\" and optionally \"folder\", \
                 \"description\", \"dialect\" and \"meta\"; a compression rule \
                 (\"kind\": \"compression\") has \"label\", \"path\" and optionally \"element\", \
                 \"codec\", \"min_bytes\" and \"dictionary\"; a catalog is \
                 {\"definitions\": [..]}."
                    .to_string()
            }
        })
    }
}

/// True for a schema error's property name that is a nested canonical path (`$.a.b[1].c`) rather
/// than a top-level property name.
fn is_nested_schema_path(name: &str) -> bool {
    name.starts_with("$.") || name.starts_with("$[")
}

impl SchemaError {
    /// The aggregated violation report when this error is an
    /// [`ExistingDataViolatesSchema`](SchemaError::ExistingDataViolatesSchema).
    pub fn violation_report(&self) -> Option<&crate::graph::schema::SchemaViolationReport> {
        match self {
            SchemaError::ExistingDataViolatesSchema { report } => Some(report),
            _ => None,
        }
    }
}

impl DiagnosticError for SchemaError {
    fn help(&self) -> Option<String> {
        match self {
            SchemaError::ExistingDataViolatesSchema { report } => {
                let mut help = String::from(
                    "The schema was NOT applied; the graph and its previous schema are unchanged. Fix or \
                     migrate the offending data first (add the missing properties, correct the values), or \
                     relax the schema (make the key optional by removing it from \"required\", allow null \
                     with \"type\": [\"T\", \"null\"], declare the label or property), or apply it with mode \
                     \"none\" (no validation), or start from the schema of the data (g.infer_schema()). \
                     Check a schema without applying it with g.validate_schema(schema) (or \
                     g.validate_schema_patch(patch)): it lists the same violations and the change's \
                     compatibility.\n\
                     To make a key required that existing elements lack, backfill first, in one \
                     transaction: (in a closed schema, declare the key optional first with \
                     g.patch_schema(..)), write the values, then patch the key into \"required\". A schema \
                     \"default\" is NOT applied to existing elements (it is an annotation only).",
                );
                let unlabeled = report
                    .groups
                    .iter()
                    .any(|group| group.label == crate::graph::schema::UNLABELED);
                if unlabeled {
                    help.push_str(
                        "\nElements without a label: a closed schema admits only declared labels, and \
                         an unlabeled vertex or edge has no label to declare (g.infer_schema() skips \
                         it). Freeze the structure in mode open instead, which admits them unchecked \
                         (g.set_schema(g.infer_schema(), SchemaMode.open)), or label them and freeze \
                         again: g.v(\"id\").add_label(\"Label\") for a vertex and \
                         g.e(\"id\").set_label(\"label\") for an edge listed above (every unlabeled \
                         one: g.v().not(__.has_label()).add_label(\"Label\"), \
                         g.e().not(__.has_label()).set_label(\"label\")), then \
                         g.set_schema(g.infer_schema(), SchemaMode.closed); or recreate them with a \
                         label (add_v(\"Label\"), add_e(\"label\")) and drop the unlabeled ones.",
                    );
                }
                Some(help)
            }
            SchemaError::UnknownVertexLabel { allowed, .. } => Some(format!(
                "A closed schema admits only declared vertex labels: use one of [{}], declare the label \
                 (g.patch_schema(#{{vertices: #{{label: #{{}}}}}})), or set mode \"open\".",
                allowed.join(", ")
            )),
            SchemaError::UnknownEdgeLabel { allowed, .. } => Some(format!(
                "A closed schema admits only declared edge labels: use one of [{}], declare the label \
                 (g.patch_schema(#{{edges: #{{label: #{{}}}}}})), or set mode \"open\".",
                allowed.join(", ")
            )),
            SchemaError::InvalidEdgeTopology { allowed, .. } => Some(format!(
                "A closed schema admits an edge only between the labels of a declared connection (any \
                 label of each endpoint may match; \"*\" matches every label). Declared connections: \
                 [{}]. Add {{\"from\": .., \"to\": ..}} to the edge label's \"connections\", or connect \
                 vertices with matching labels.",
                allowed.join(", ")
            )),
            SchemaError::UndeclaredProperty { property_name, .. } if is_nested_schema_path(property_name) => {
                Some(format!(
                    "Declare '{property_name}' among the \"properties\" of its enclosing object in the \
                     schema, or let that object admit undeclared keys with \"additionalProperties\": true \
                     (a closed schema's default is false; an open schema's is true)."
                ))
            }
            SchemaError::UndeclaredProperty { property_name, .. } => Some(format!(
                "Declare '{property_name}' in the label's \"properties\", or let the label admit \
                 undeclared keys: \"additionalProperties\": true on its schema, or mode \"open\". With \
                 several labels the key is allowed when ANY label declares or admits it."
            )),
            SchemaError::MissingRequiredProperty { property_name, .. } if is_nested_schema_path(property_name) => {
                Some(format!(
                    "Provide a value for the nested key '{property_name}' (e.g. \
                     property(jpath(\"{property_name}\"), value)) or remove it from \"required\" of its \
                     enclosing object in the schema; a required nested key cannot be removed with \
                     remove_property(jpath(..)). A schema \"default\" is an annotation only: it does not \
                     fill a missing key."
                ))
            }
            SchemaError::MissingRequiredProperty { property_name, .. } => {
                Some(format!(
                    "Provide a value for '{property_name}' or remove it from the label's \"required\" in \
                     the schema. A schema \"default\" is an annotation only: it is never filled in, so a \
                     required property needs a value even when its schema has a default.\n\
                     A required property must be supplied when the element is created: \
                     add_v(\"L\").property(\"{property_name}\", value) works because the optimizer rule \
                     add_property_fold folds the directly following constant property() steps into \
                     add_v()/add_e(). If a property() after it is not folded (the rule is disabled with \
                     g.with(\"optimizer.disabled\", [\"add_property_fold\"]), the value is a traversal, a \
                     Cardinality or a jpath key, or another step sits in between), the element is created \
                     empty and this error is raised; move a constant property(\"{property_name}\", value) \
                     directly behind add_v()/add_e() and keep add_property_fold enabled."
                ))
            }
            SchemaError::RequiredPropertyRemoval { property_name, label, element_type } => {
                Some(format!(
                    "'{property_name}' is in \"required\" of {element_type} label '{label}', so it cannot \
                     be removed in open or closed mode. Overwrite it with a new value instead (null only \
                     when its type admits null), remove it from \"required\" in the schema \
                     (g.patch_schema(..)), or set the schema mode to \"none\"."
                ))
            }
            SchemaError::InvalidSchema { hint, .. } => Some(if hint.is_empty() {
                crate::graph::schema::parse::FORMAT_HELP.to_string()
            } else {
                format!("{hint}\n{}", crate::graph::schema::parse::FORMAT_HELP)
            }),
            SchemaError::TypeMismatch {
                property_name,
                expected_type,
                actual_type,
                ..
            } => {
                let mut help = if actual_type == "null" {
                    format!(
                        "'{property_name}' does not admit null: write a value of type \
                         '{expected_type}', remove the property instead (absence is governed by \
                         \"required\", not by null), or allow null in the schema with \"type\": \
                         [\"T\", \"null\"]."
                    )
                } else {
                    format!("Convert value to expected type '{expected_type}' before inserting.")
                };
                // A nested location is read with a jpath key; a plain name is a literal key.
                let key = if is_nested_schema_path(property_name) {
                    format!("jpath(\"{property_name}\")")
                } else {
                    format!("\"{property_name}\"")
                };
                if let Some(convert) = coercion_step(&expected_type.to_lowercase()) {
                    help.push_str(&format!(
                        "\nIn a query, convert the values with values({key}).{convert}."
                    ));
                }
                if expected_type == "uuid" && actual_type != "string" {
                    help.push_str(
                        "\nOnly a canonical UUID string is converted to a uuid on write; convert \
                         a string value explicitly with .cast(GType.UUID).",
                    );
                }
                if let Some(locate) = gtype_token(&actual_type.to_lowercase()) {
                    help.push_str(&format!(
                        "\nFind every offending value with values({key}).is(typeOf(GType.{locate}))."
                    ));
                }
                Some(help)
            }
            SchemaError::CoercionFailed {
                property_name,
                declared_type,
                ..
            } => Some(match declared_type.as_str() {
                "uuid" => "UUIDs are written as 8-4-4-4-12 lowercase hex, e.g. \
                           `550e8400-e29b-41d4-a716-446655440000`."
                    .to_string(),
                "float64" => "The integer is too large to be represented exactly as float64; \
                              store it in an int64 field."
                    .to_string(),
                _ => format!(
                    "Store a value of type '{declared_type}' in '{property_name}', or change the \
                     declared type in the schema."
                ),
            }),
            SchemaError::ConstraintViolation { constraint_rule, .. } => {
                Some(format!("Ensure value complies with validation constraint: {constraint_rule}."))
            }
            SchemaError::InvalidPattern { .. } => Some(
                "A schema `pattern` is a regular expression with JSON Schema semantics (matched \
                 anywhere in the value; anchor it with ^...$ for a whole-value match), in the syntax \
                 of the Rust `regex` crate: classes [a-z], \\d, \\w, \\s, groups (..), alternation |, \
                 quantifiers * + ? {n,m}. Look-around ((?=..), (?!..)) and back-references (\\1) are \
                 not supported. Escape a literal metacharacter with a backslash, e.g. \\. for a dot \
                 (in a JSON schema file the backslash itself is doubled: \"^\\\\d+$\")."
                    .to_string(),
            ),
        }
    }
}

/// Boxed form of [`TraverserError`], used as the `Err` type of [`TraverserResult`].
///
/// `TraverserError` wraps every sub-error (up to 128 bytes on a 64-bit target), so an
/// unboxed `Result<T, TraverserError>` costs at least that much to move regardless of which
/// variant is live, even on the `Ok` path. Boxing keeps that cost to a single pointer.
pub type BoxedTraverserError = Box<TraverserError>;

/// The error type traversal execution returns.
///
/// Boxed (see [`BoxedTraverserError`]) so the success path of every fallible traversal
/// operation stays cheap to move; only the (rare) error path pays for the allocation.
pub type TraverserResult<T> = Result<T, BoxedTraverserError>;

/// Converts a sub-error straight into [`BoxedTraverserError`] in one `?`-hop, without a
/// per-call-site `.map_err(Box::new)`.
///
/// `std` already provides `Box<T>: From<T>` (i.e. `From<TraverserError> for
/// Box<TraverserError>`), but `?` performs only a single `From::from` call, so a
/// `#[from]`-generated conversion (e.g. `ValueError -> TraverserError`) does not compose
/// automatically into `Box<TraverserError>` through two hops. A single blanket `impl<T> From<T>
/// for BoxedTraverserError where TraverserError: From<T>` was tried and rejected: it conflicts
/// (`E0119`) with `std`'s own `impl<T> From<T> for Box<T>` at `T = TraverserError`, since
/// `TraverserError: From<TraverserError>` holds reflexively. Five concrete impls, one per
/// `#[from]` variant of `TraverserError` itself, sidestep that conflict.
macro_rules! impl_from_suberror_for_boxed {
    ($($sub:ty => $variant:ident),+ $(,)?) => {
        $(
            impl From<$sub> for BoxedTraverserError {
                fn from(err: $sub) -> Self {
                    Box::new(TraverserError::$variant(err))
                }
            }
        )+
    };
}

impl_from_suberror_for_boxed! {
    ValueError => Value,
    GraphError => Graph,
    IOError => Io,
    ScriptError => Script,
    SchemaError => Schema,
}

/// Delegates diagnostics to the boxed error, so callers holding a [`BoxedTraverserError`] (the
/// common case now that fallible traversal calls return [`TraverserResult`]) do not need to
/// deref it explicitly to call `help()`/`details()`/`diagnostic_body()`.
impl DiagnosticError for BoxedTraverserError {
    fn help(&self) -> Option<String> {
        (**self).help()
    }

    fn details(&self) -> Vec<(String, String)> {
        (**self).details()
    }

    fn diagnostic_body(&self) -> String {
        (**self).diagnostic_body()
    }
}

/// Top-level error enum wrapping domain errors and traversal pipeline failures.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum TraverserError {
    /// A value/property/cast error, forwarded as-is.
    #[error(transparent)]
    Value(#[from] ValueError),

    /// A graph structure/lookup error, forwarded as-is.
    #[error(transparent)]
    Graph(#[from] GraphError),

    /// An import/export/IO error, forwarded as-is.
    #[error(transparent)]
    Io(#[from] IOError),

    /// A script parsing/evaluation error, forwarded as-is.
    #[error(transparent)]
    Script(#[from] ScriptError),

    /// A schema validation error, forwarded as-is.
    #[error(transparent)]
    Schema(#[from] SchemaError),

    /// A named step in the pipeline failed; wraps the underlying cause with its query position.
    #[error(
        "Step {}'{}' execution failed{}",
        step_path(.child_index, .step_index, .source),
        innermost_step_name(.step_name, .source),
        .element_id.as_ref().map(|id| format!(" for element ID '{id}'")).unwrap_or_default()
    )]
    #[non_exhaustive]
    StepFailed {
        /// The failing step's rendered name.
        step_name: String,
        /// Position of the step inside its own traversal level, used to build the step path.
        step_index: Option<usize>,
        /// When the level is a child traversal: its index among the children of the step that
        /// holds it (`GraphStep::child_traversals_mut` order); `None` at the top level. Together
        /// with `step_index` it builds the step id of [`TraverserError::step_location`].
        child_index: Option<usize>,
        /// Optimized physical plan of the traversal level this step belongs to.
        ///
        /// Boxed so that the plan, needed only to render a diagnostic, keeps
        /// [`TraverserError`] small.
        frame: Option<Box<StepFrame>>,
        /// ID of the element being processed when the step failed, when known.
        element_id: Option<String>,
        /// The underlying cause.
        #[source]
        source: Box<TraverserError>,
        /// The spelling of the step names in this diagnostic (`g.with("render.spelling", ..)`):
        /// the rendered steps are stored in it, and [`DiagnosticError::help`] and
        /// [`DiagnosticError::diagnostic_body`] respell their whole text with it.
        spelling: crate::traversal::Spelling,
    },

    /// A query failed for a reason not captured by a more specific variant.
    #[error("Query execution error: {reason}")]
    #[non_exhaustive]
    QueryExecution {
        /// The query text, when available.
        query: String,
        /// Why it failed.
        reason: String,
    },

    /// A requested capability doesn't exist yet.
    #[error("Feature not implemented yet: {feature}")]
    #[non_exhaustive]
    NotImplemented {
        /// The missing feature's name.
        feature: &'static str,
    },

    /// The execution recorded more path positions than its path arena can address.
    #[error("Path tracking exhausted: the traversal recorded more than {capacity} path positions")]
    #[non_exhaustive]
    PathArenaExhausted {
        /// Maximum number of path positions one execution can record.
        capacity: u64,
    },

    /// The execution stored more distinct sack values than its sack arena can address.
    #[error("Sack storage exhausted: the traversal stored more than {capacity} sack values")]
    #[non_exhaustive]
    SackArenaExhausted {
        /// Maximum number of sack values one execution can store.
        capacity: u64,
    },

    /// The execution ran past its `evaluationTimeout` budget and was stopped cooperatively.
    #[error("Traversal exceeded evaluationTimeout of {limit_ms} ms (ran {elapsed_ms} ms)")]
    #[non_exhaustive]
    Timeout {
        /// The budget set with `g.with("evaluationTimeout", ms)`, in milliseconds.
        limit_ms: u64,
        /// How long the execution had run when it was stopped, in milliseconds.
        elapsed_ms: u64,
    },

    /// The host cancelled the execution through its [`CancelToken`](crate::CancelToken) (for
    /// example the Stop button of the dev server); it stopped cooperatively and its unit rolled
    /// back.
    #[error("Traversal cancelled after {elapsed_ms} ms")]
    #[non_exhaustive]
    Cancelled {
        /// How long the execution had run when it was stopped, in milliseconds.
        elapsed_ms: u64,
    },

    /// An execution option set with `with()` holds a value of the wrong shape.
    ///
    /// Raised when the traversal is executed, since `with()` itself cannot fail.
    #[error("Invalid value for option '{key}': {reason}")]
    #[non_exhaustive]
    InvalidOption {
        /// The option key, such as `evaluationTimeout`.
        key: String,
        /// What is wrong with the value.
        reason: String,
    },

    /// A query's own `g.with(key, ..)` attempted to set an option the host running this
    /// instance has locked via [`crate::graph::ExecutionPolicy::with_locked`]. Distinct from
    /// [`Self::InvalidOption`]: this is not about the value being malformed — no value the query
    /// supplies is accepted for this key at all, regardless of shape.
    ///
    /// Raised when the traversal is executed, same timing as `InvalidOption`, since `with()`
    /// itself cannot fail.
    #[error(
        "Option '{key}' is locked by this instance's execution policy and cannot be set by a query"
    )]
    #[non_exhaustive]
    LockedOption {
        /// The option key the query tried to set, such as `evaluationTimeout`.
        key: String,
    },

    /// The host's [`Authorizer`](crate::graph::Authorizer) denied a request
    /// ([`AccessRequest`](crate::graph::AccessRequest): an action on a resource). Raised once
    /// per execution, before anything runs, for the first request of the plan (in plan order,
    /// child traversals included) that was denied; also for a source method that is not a step
    /// (file I/O, schema loading) and for a file path outside the host's file root.
    #[error("Permission denied for '{step}' ({request}): {reason}")]
    #[non_exhaustive]
    PermissionDenied {
        /// The step or operation that made the request, such as `add_v`, `export_graphml` or
        /// `with("evaluationTimeout")`.
        step: String,
        /// The denied request; [`AccessRequestBuf::as_request`](crate::graph::AccessRequestBuf::as_request)
        /// gives its action and resource.
        request: Box<crate::graph::AccessRequestBuf>,
        /// Why it was denied, as the authorizer said (or the path is outside the file root).
        reason: String,
    },

    /// A `repeat()` without `times()` ran more iterations than `repeat.max_loops` allows,
    /// which usually means it walks a cycle or has no stop condition.
    #[error(
        "repeat(){} exceeded the loop limit of {max_loops} iterations",
        .loop_name.as_ref().map(|name| format!(" loop '{name}'")).unwrap_or_default()
    )]
    #[non_exhaustive]
    RepeatLimitExceeded {
        /// The limit set with `g.with("repeat.max_loops", n)`, 10 000 by default.
        max_loops: u32,
        /// The name given with `repeat(name, body)`, if any.
        loop_name: Option<String>,
        /// The loop body as written, such as `__.out()`, used to build the advice.
        body: String,
    },

    /// The bulk (multiplicity) of merged traversers, or their sum, exceeds `u64` or the largest
    /// `int64`, so no exact count can be produced.
    #[error("The number of traversers at step '{step}' is too large to count (more than 2^63 - 1)")]
    #[non_exhaustive]
    BulkOverflow {
        /// The step that was summing or multiplying bulks.
        step: String,
    },

    /// A step had to expand merged traversers back into individual values, and that would
    /// materialize more values than `bulk.max_expansion` allows.
    #[error(
        "Step '{step}' would have to materialize {requested} values, more than the limit of {limit} \
         (bulk.max_expansion)"
    )]
    #[non_exhaustive]
    BulkExpansionLimit {
        /// The step (or terminal) that had to expand.
        step: String,
        /// How many values the expansion needs.
        requested: u64,
        /// The limit set with `g.with("bulk.max_expansion", n)`, 10 000 000 by default.
        limit: u64,
    },

    /// A script or traversal ran past a configured resource limit and was stopped.
    ///
    /// One error family for every resource bound: the script limits of the Rhai engine
    /// (`script::ScriptLimits`, feature `script`, named `script.*`) and the traversal limits set with
    /// `g.with()` or a host's [`crate::graph::ExecutionPolicy`] (named after their option key,
    /// such as `traversal.max_traversers`).
    #[error("Resource limit '{limit}' exceeded{}", limit_detail(*.max, *.observed))]
    #[non_exhaustive]
    ResourceLimitExceeded {
        /// The limit that was hit: an option key such as `traversal.max_traversers`, or a
        /// script limit such as `script.max_operations`.
        limit: String,
        /// The configured maximum, when it is known where the error is raised.
        max: Option<u64>,
        /// The value that crossed the limit (for example the number of traversers), when known.
        observed: Option<u64>,
    },

    /// `loops(name)` names no enclosing `repeat()`.
    #[error("loops(\"{name}\") names no enclosing repeat(){}", active_loops(.active))]
    #[non_exhaustive]
    UnknownLoopName {
        /// The loop name that was asked for.
        name: String,
        /// Names of the enclosing named loops, innermost first.
        active: Vec<String>,
    },

    /// `times()`, `until()` or `emit()` was written without a `repeat()` to modulate.
    #[error("{modulator} modulates a repeat() step, but the traversal has no repeat() for it")]
    #[non_exhaustive]
    RepeatWithoutBody {
        /// The modulators as written, such as `times(2)`.
        modulator: String,
    },

    /// A `repeat()` body has `inject()` as one of its own steps, which TinkerPop forbids (the
    /// injected values would re-enter every iteration). Only a direct step of the body is rejected;
    /// an `inject()` nested in `union(..)`, `local(..)` and the likeis allowed. The error is raised when the
    /// traversal executes, not when it is built (user's guide: "Recursive Traversals").
    #[error("inject() is not allowed as a step of a repeat() body")]
    #[non_exhaustive]
    RepeatInject {
        /// The name given with `repeat(name, body)`, if any.
        loop_name: Option<String>,
    },

    /// `.option(pick, traversal)` was written without a preceding `choose(traversal)`/
    /// `branch(traversal)` to attach to, or the preceding step is the locked 3-argument
    /// `choose(predicate, onTrue, onFalse)` form (which already has its two branches fixed and
    /// rejects further `.option()` calls).
    #[error(
        "{modulator} modulates a choose(traversal)/branch(traversal) or merge_v()/merge_e() step, but the traversal has none for it (or it already has choose(predicate, onTrue, onFalse)'s two fixed branches)"
    )]
    #[non_exhaustive]
    OptionWithoutBranch {
        /// The modulator as written, such as `.option("person", __.out("knows"))`.
        modulator: String,
    },

    /// `otherV()` walked its traverser's recorded path backward and found no vertex earlier
    /// than the current edge, so there is nothing to call "the other side" of.
    #[error("other_v() found no vertex earlier in the traversal to compare against edge {edge}")]
    #[non_exhaustive]
    OtherVWithoutOrigin {
        /// Debug rendering of the edge id, for the error message.
        edge: String,
    },

    /// `range(low, high)` received a `low`/`high` combination that violates TinkerPop's
    /// `[low, high)` contract: `low` must be zero or positive, `high` must be `-1`
    /// ("unbounded", TinkerPop's own sentinel) or at least `low`. Also raised by
    /// `limit/skip/tail/range(Scope.local, …)` for invalid bounds or a negative count.
    #[error("Invalid range [{low}, {high}): {reason}")]
    #[non_exhaustive]
    InvalidRange {
        /// The `low` bound as given to `range()`.
        low: i64,
        /// The `high` bound as given to `range()`, or `-1` for "unbounded".
        high: i64,
        /// What specifically is wrong with the combination.
        reason: String,
    },

    /// A step received a `by()` or `from()`/`to()` modulator it cannot use at that position, such
    /// as a vertex-label list (`by(["person", "software"])`) on `order()`, a `by()`/`from()`/
    /// `to()` that follows a step that takes none at all (`out().by("name")`,
    /// `out().from("a")`, `count().by("name")`), or no step at all (`g.by(..)`, reported with
    /// `step` `g` or `__`), like TinkerPop, which accepts `by()` only after a `ByModulating` step
    /// and `from()`/`to()` only after a `FromToModulating` step (`addE()`).
    ///
    /// Raised when the traversal is executed, since step builders cannot fail — and, before
    /// that, by a plan-time validation pass that walks the whole plan (including nested child
    /// traversals never reached at runtime), so a rejected modulator inside an unreached branch
    /// still fails instead of silently succeeding.
    #[error("`{step}()` cannot use its {modulator} #{position}: {reason}")]
    #[non_exhaustive]
    InvalidModulator {
        /// The step the modulator modulates, such as `order`, `group` or `add_e`.
        step: String,
        /// The 1-based index of the offending modulator among that step's modulators of the same
        /// kind (`by()`s counted separately from `from()`/`to()`s).
        position: usize,
        /// The modulator kind, `"by()"` or `"from()/to()"`, rendered right after `step`.
        modulator: &'static str,
        /// Why the step cannot use this modulator.
        reason: String,
    },

    /// A step that configures the traversal source `g` (`with_sack()`, `with_side_effect()`,
    /// `with_path()`) was written inside a child traversal (`__.with_sack(1)`), where it has nothing to
    /// configure. In Gremlin these steps exist only on the traversal source; the script DSL can
    /// still record them on `__`, so the plan-time validation pass rejects them before
    /// execution, wherever the child sits (also in a branch the data never reaches).
    #[error(
        "`{step}()` configures the traversal source g and cannot be used inside a child traversal"
    )]
    #[non_exhaustive]
    SourceStepInChild {
        /// The source step, such as `with_sack` or `with_side_effect`.
        step: String,
    },

    /// A property write asked for a cardinality Graphersal cannot honour: `Cardinality.list` or
    /// `Cardinality.set` on a vertex (Graphersal stores one value per property key), or any
    /// cardinality on an edge (edge properties have none, as in TinkerPop's `AddPropertyStep`).
    /// Raised only when a value would actually be written, so a `list`/`set` call that writes
    /// nothing (`property(Cardinality.set, null)`, zero traversers) succeeds.
    #[error("{}", unsupported_cardinality_message(.step, *.cardinality, *.on_edge))]
    #[non_exhaustive]
    UnsupportedCardinality {
        /// The writing step, such as `property`.
        step: String,
        /// The cardinality that was asked for.
        cardinality: crate::value::Cardinality,
        /// `true` when the write targeted an edge, which takes no cardinality at all.
        on_edge: bool,
    },

    /// `property(T.id, ..)` / `property(T.label, ..)` was used where it cannot set the id/label
    /// of an element being created: not right after `addV()`/`addE()` (only other `property()`
    /// calls may come in between), or `T.label` after `addE()`, whose label comes from
    /// `addE(label)`.
    #[error("{}", token_property_outside_add_message(.token))]
    #[non_exhaustive]
    TokenPropertyOutsideAdd {
        /// The token as written: `T.id` or `T.label`.
        token: String,
    },

    /// A `mergeV()`/`mergeE()` map (the merge argument or an `option(Merge.onCreate|onMatch|
    /// outV|inV, ..)` map) is malformed: not a map, a hidden (`~`) key, an invalid `T.id`/`T.label` value,
    /// a token key the step does not take, or `T.id`/`T.label` in `option(Merge.onMatch, ..)`.
    /// A constant map is checked before the traversal executes (even when no traverser reaches
    /// the step); a map produced by a traversal is checked when it arrives.
    #[error("{reason} (in {argument} of {step}())")]
    #[non_exhaustive]
    InvalidMergeMap {
        /// The merge step: `mergeV` or `mergeE`.
        step: String,
        /// Where the problem is: `the merge() map`, `the option(onCreate) map`, `the
        /// option(onMatch) map`, or an option the step does not take such as `option(outV)`.
        argument: String,
        /// What is wrong, e.g. `Property key can not be a hidden key: ~id`.
        reason: String,
    },

    /// A key of the `option(Merge.onCreate, ..)` map is also in the merge argument with a
    /// different value (TinkerPop: the onCreate map may only add keys). Checked before execution
    /// when both maps are constants, otherwise when the element is about to be created.
    #[error(
        "option(onCreate) cannot override values from merge() argument: {key} is {merge_value} in {step}() but {on_create_value} in option(onCreate)"
    )]
    #[non_exhaustive]
    MergeOverride {
        /// The merge step: `mergeV` or `mergeE`.
        step: String,
        /// The conflicting key, such as `T.label` or `name`.
        key: String,
        /// The key's value in the merge argument, rendered for the message.
        merge_value: String,
        /// The key's value in the onCreate map, rendered for the message.
        on_create_value: String,
    },

    /// `mergeE()` could not resolve a vertex of the edge: the merge and onCreate maps name no
    /// out-/in-vertex where an edge must be created ("Out Vertex not specified"), an id names no
    /// vertex ("Vertex id could not be resolved from mergeE: 100"), or a `Merge.outV`/`Merge.inV`
    /// placeholder has no `option(Merge.outV|inV, ..)` or that option does not identify exactly
    /// one vertex.
    #[error("{reason}")]
    #[non_exhaustive]
    MergeVertexUnresolved {
        /// Which end of the edge: `Direction::Out` or `Direction::In`.
        direction: crate::value::Direction,
        /// What went wrong, e.g. `In Vertex not specified`.
        reason: String,
    },

    /// A traverser reached a `fail()` / `fail(message)` step, which stops the traversal on
    /// purpose (TinkerPop `FailStep`).
    #[error("{message} (fail() reached by {value})")]
    #[non_exhaustive]
    Fail {
        /// The message given to `fail(message)`, or `fail() step triggered`.
        message: String,
        /// A short rendering of the value of the traverser that reached the step.
        value: String,
    },

    /// A `math()` equation that does not parse (raised before execution, even when no traverser
    /// reaches the step) or that fails for one traverser: an unknown variable, a nested-access
    /// path that leads nowhere, a value that is not a number, or a division by zero.
    #[error("math({}) failed at column {column}: {message}", crate::value::literal::rhai_string(.expr))]
    #[non_exhaustive]
    MathExpression {
        /// The equation as written.
        expr: String,
        /// Byte offset of the offending token in `expr`.
        offset: usize,
        /// 1-based character column of the offending token in `expr`.
        column: usize,
        /// Width of the offending token in characters (at least 1), for the underline.
        width: usize,
        /// What went wrong, with the data the advice is built from.
        kind: MathErrorKind,
        /// The rendered reason.
        message: String,
    },

    /// An error raised before any step ran and without a step to locate it at (an invalid or
    /// locked option, a denied `with("key")`), under a non-default `render.spelling`: the
    /// diagnostic of `source` respelled. Its message is that of `source`; see
    /// [`TraverserError::root_cause`] for the error itself. Built only by the respelling of an
    /// execution's error, so with the default spelling an error is never wrapped.
    #[error("{source}")]
    #[non_exhaustive]
    Spelled {
        /// The spelling of the step names in the diagnostic.
        spelling: crate::traversal::Spelling,
        /// The error itself.
        source: Box<TraverserError>,
    },
}

/// What went wrong in a `math()` equation: the kind of a [`TraverserError::MathExpression`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MathErrorKind {
    /// The equation does not parse: a syntax error such as `2 +* 3`, an unclosed bracket, or a
    /// function called with the wrong number of arguments.
    Syntax,
    /// A name called like a function (`sqr(_)`) that is not one of the built-in functions.
    #[non_exhaustive]
    UnknownFunction {
        /// The name as written.
        name: String,
    },
    /// A variable that is neither `_` (the current value) nor a key of the current map, a side
    /// effect or a step label.
    #[non_exhaustive]
    UnknownVariable {
        /// The variable name.
        name: String,
    },
    /// A nested-access path (`_.price.total`, `a.items[0]`) that leads to no value: a missing
    /// key, an index out of range, or a step into a value that is neither a map nor a list.
    #[non_exhaustive]
    BadPath {
        /// The path up to and including the failing segment, such as `_.price.total`.
        path: String,
    },
    /// A variable or nested value that is not a number.
    #[non_exhaustive]
    NotANumber {
        /// The variable or nested path, such as `_` or `_.name`.
        path: String,
        /// The type of the value found.
        actual: String,
    },
    /// A variable or nested value that is `null`.
    #[non_exhaustive]
    Null {
        /// The variable or nested path.
        path: String,
    },
    /// `/` or `%` with a zero divisor, or `cot(x)` where `tan(x)` is zero (an error, as in
    /// TinkerPop, instead of infinity).
    DivisionByZero,
    /// An inconsistency of the expression engine itself, never caused by the equation.
    Internal,
}

/// Renders an `UnsupportedCardinality` error.
fn unsupported_cardinality_message(
    step: &str,
    cardinality: crate::value::Cardinality,
    on_edge: bool,
) -> String {
    if on_edge {
        format!(
            "Property cardinality can only be set for a Vertex: {step}(Cardinality.{cardinality}, ..) was applied to an edge"
        )
    } else {
        format!(
            "Cardinality.{cardinality} is not supported: Graphersal stores one value per property key ({step}() would write a second value)"
        )
    }
}

/// Renders a `TokenPropertyOutsideAdd` error.
fn token_property_outside_add_message(token: &str) -> String {
    if token == "T.label" {
        format!(
            "property({token}, ..) can only set the label of a vertex add_v() is creating (an edge's label comes from add_e(label))"
        )
    } else {
        format!(
            "property({token}, ..) can only set the id of an element add_v()/add_e() is creating"
        )
    }
}

/// Renders the active loop names of an `UnknownLoopName` error.
fn active_loops(active: &[String]) -> String {
    if active.is_empty() {
        String::new()
    } else {
        format!(" (active loops: {})", active.join(", "))
    }
}

/// Converts a step-name argument (a `&str` or a pre-rendered `String`) into an owned `String`.
pub(crate) trait StepNameSource {
    /// Consumes this value, producing the step name.
    fn into_step_name(self) -> String;
}

impl StepNameSource for &str {
    fn into_step_name(self) -> String {
        self.to_string()
    }
}

impl StepNameSource for String {
    fn into_step_name(self) -> String {
        self
    }
}

impl<F: FnOnce() -> String> StepNameSource for F {
    fn into_step_name(self) -> String {
        self()
    }
}

/// Where a failing step sits in the optimized plan: the child traversal its level is (`None` at
/// the top level) and its position in that level. See `TraverserError::StepFailed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StepAt {
    pub(crate) child: Option<usize>,
    pub(crate) index: usize,
}

pub(crate) trait ResultExt<T> {
    #[allow(dead_code)]
    fn with_step<S: StepNameSource>(self, step_name: S) -> TraverserResult<T>;

    /// Wraps a step failure together with the position and physical plan of the traversal
    /// level it occurred in, so nested failures can be addressed by a step path.
    fn with_step_frame<S: StepNameSource, F: FnOnce() -> StepFrame>(
        self,
        step_name: S,
        at: StepAt,
        frame: F,
    ) -> TraverserResult<T>;

    #[allow(dead_code)]
    fn with_step_element<S: StepNameSource, EId: StepNameSource>(
        self,
        step_name: S,
        element_id: EId,
    ) -> TraverserResult<T>;
}

impl<T, E> ResultExt<T> for Result<T, E>
where
    E: Into<TraverserError>,
{
    fn with_step<S: StepNameSource>(self, step_name: S) -> TraverserResult<T> {
        self.map_err(|err| {
            Box::new(TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: step_name.into_step_name(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: None,
                source: Box::new(err.into()),
            })
        })
    }

    fn with_step_frame<S: StepNameSource, F: FnOnce() -> StepFrame>(
        self,
        step_name: S,
        at: StepAt,
        frame: F,
    ) -> TraverserResult<T> {
        self.map_err(|err| {
            Box::new(TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: step_name.into_step_name(),
                step_index: Some(at.index),
                child_index: at.child,
                frame: Some(Box::new(frame())),
                element_id: None,
                source: Box::new(err.into()),
            })
        })
    }

    fn with_step_element<S: StepNameSource, EId: StepNameSource>(
        self,
        step_name: S,
        element_id: EId,
    ) -> TraverserResult<T> {
        self.map_err(|err| {
            Box::new(TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: step_name.into_step_name(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: Some(element_id.into_step_name()),
                source: Box::new(err.into()),
            })
        })
    }
}

/// Mirrors the `E: Into<TraverserError>` impl above for an error that is already boxed (the
/// common case now that most fallible calls return [`TraverserResult`]). `Box<TraverserError>`
/// has no `Into<TraverserError>` impl in `std` (unboxing is not a conversion `std` provides), so
/// this impl does not overlap with the generic one.
impl<T> ResultExt<T> for Result<T, BoxedTraverserError> {
    fn with_step<S: StepNameSource>(self, step_name: S) -> TraverserResult<T> {
        self.map_err(|err| {
            Box::new(TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: step_name.into_step_name(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: None,
                source: err,
            })
        })
    }

    fn with_step_frame<S: StepNameSource, F: FnOnce() -> StepFrame>(
        self,
        step_name: S,
        at: StepAt,
        frame: F,
    ) -> TraverserResult<T> {
        self.map_err(|err| {
            Box::new(TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: step_name.into_step_name(),
                step_index: Some(at.index),
                child_index: at.child,
                frame: Some(Box::new(frame())),
                element_id: None,
                source: err,
            })
        })
    }

    fn with_step_element<S: StepNameSource, EId: StepNameSource>(
        self,
        step_name: S,
        element_id: EId,
    ) -> TraverserResult<T> {
        self.map_err(|err| {
            Box::new(TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: step_name.into_step_name(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: Some(element_id.into_step_name()),
                source: err,
            })
        })
    }
}

impl TraverserError {
    /// The `help()` text in the canonical snake_case spelling; [`DiagnosticError::help`]
    /// respells it with [`Self::spelling`].
    fn canonical_help(&self) -> Option<String> {
        match self {
            TraverserError::Value(err) => err.help(),
            TraverserError::Graph(err) => err.help(),
            TraverserError::Io(err) => err.help(),
            TraverserError::Script(err) => err.help(),
            TraverserError::Schema(err) => err.help(),
            TraverserError::StepFailed { .. } => match self.root_cause() {
                // The timeout advice rewrites the query itself, so it needs the outermost level.
                TraverserError::Timeout { limit_ms, .. } => {
                    Some(timeout_help(*limit_ms, self.outermost_steps()))
                }
                TraverserError::RepeatLimitExceeded {
                    max_loops,
                    loop_name,
                    body,
                } => Some(repeat_limit_help(
                    *max_loops,
                    loop_name.as_deref(),
                    body,
                    self.outermost_steps(),
                )),
                TraverserError::RepeatWithoutBody { modulator } => {
                    Some(repeat_without_body_help(modulator, self.failing_level_prefix()))
                }
                TraverserError::RepeatInject { .. } => Some(repeat_inject_help()),
                TraverserError::OptionWithoutBranch { modulator } => {
                    Some(option_without_branch_help(modulator))
                }
                // The corrected query is the failing one with a valid max_depth.
                TraverserError::InvalidOption { key, .. } if key == GLOB_PATH_MAX_DEPTH => {
                    Some(glob_path_max_depth_help(self.outermost_steps()))
                }
                // The advice rewrites the failing query when the math() step is at its top level.
                TraverserError::MathExpression { expr, kind, .. } => {
                    Some(math_expression_help(expr, kind, self.outermost_steps()))
                }
                root => root.help(),
            },
            TraverserError::Spelled { source, .. } => source.canonical_help(),
            TraverserError::Timeout { limit_ms, .. } => Some(timeout_help(*limit_ms, None)),
            TraverserError::Cancelled { .. } => Some(cancelled_help()),
            TraverserError::InvalidOption { key, .. } => Some(invalid_option_help(key)),
            TraverserError::LockedOption { key } => Some(locked_option_help(key)),
            TraverserError::PermissionDenied { reason, .. }
                if reason.starts_with(SAVED_QUERY_READ_ONLY) =>
            {
                Some(
                    "A saved query never writes: not the data, the schema, the saved queries or \
                     files, also not through a query it calls or a traversal it returns (a \
                     g.query(..) result cannot be continued with a writing step). Write in a \
                     traversal of your own after the call, for example \
                     let ids = g.query(\"q\").id().to_list(); \
                     g.v(ids).property(\"seen\", true).to_list(). A graph the query builds \
                     itself (GraphSource::empty(), __) stays writable."
                        .to_string(),
                )
            }
            TraverserError::PermissionDenied { step, request, .. } => {
                Some(permission_denied_help(step, &request.as_request()))
            }
            TraverserError::RepeatLimitExceeded {
                max_loops,
                loop_name,
                body,
            } => Some(repeat_limit_help(*max_loops, loop_name.as_deref(), body, None)),
            TraverserError::BulkOverflow { step } => Some(bulk_overflow_help(step)),
            TraverserError::BulkExpansionLimit {
                step,
                requested,
                limit,
            } => Some(bulk_expansion_limit_help(step, *requested, *limit)),
            TraverserError::ResourceLimitExceeded {
                limit,
                max,
                observed,
            } => Some(resource_limit_help(limit, *max, *observed)),
            TraverserError::UnknownLoopName { name, active } => {
                Some(unknown_loop_name_help(name, active))
            }
            TraverserError::RepeatWithoutBody { modulator } => {
                Some(repeat_without_body_help(modulator, None))
            }
            TraverserError::RepeatInject { .. } => Some(repeat_inject_help()),
            TraverserError::OptionWithoutBranch { modulator } => {
                Some(option_without_branch_help(modulator))
            }
            TraverserError::QueryExecution { query, reason }
                if query == "add_e" && reason.contains("from()") =>
            {
                Some(add_e_endpoint_help())
            }
            TraverserError::QueryExecution { query, reason }
                if query == "tree" && reason.contains("already holds") =>
            {
                Some(tree_key_clash_help(reason))
            }
            TraverserError::QueryExecution { query, reason }
                if (query == "group" || query == "group_count")
                    && (reason.contains("already holds") || reason.contains("reduce differently")) =>
            {
                Some(group_key_clash_help(reason))
            }
            TraverserError::QueryExecution { query, reason }
                if query == "id"
                    && reason == crate::traversal::step::map_steps::step_id::PROPERTY_ELEMENT_ID_REASON =>
            {
                Some(
                    "Graphersal has no property ids, so id() cannot read one from properties(). A \
                     vertex property is identified by its vertex id and key: read the key with \
                     g.v().properties().key(), or the owning vertex id with \
                     g.v().properties().element().id(). label() and has_label() work on \
                     properties(): the label of a vertex property is its key. The same holds \
                     for by(T.id) over properties(): there is no id to sort, group or dedup by; \
                     use by(T.label) (the key) or by(__.element().id())."
                        .to_string(),
                )
            }
            TraverserError::QueryExecution { query, .. }
                if query == "by(T.label)" || query == "by(T.id)" =>
            {
                let token = &query["by(".len()..query.len() - 1];
                Some(format!(
                    "{token} reads the label or id of a graph element, so the stream reaching this \
                     by() must hold vertices, edges or vertex properties (the label of a vertex \
                     property is its key). The values here are plain data, which have no \
                     {token}: order or group the elements before extracting values, or use a \
                     property key or a child traversal instead, for example \
                     g.v().order().by(\"name\") or g.v().order().by(__.values(\"name\")). \
                     To sort plain values, use order() with no by()."
                ))
            }
            TraverserError::QueryExecution { query, reason } if query == "to_graph" => {
                Some(to_graph_help(reason))
            }
            TraverserError::QueryExecution { query, .. } if query == "subgraph()" => {
                Some(
                    "subgraph() needs the name of the side effect that collects the edges. Use \
                     subgraph(\"sg\") and read the graph with cap(\"sg\"): \
                     g.e(0).subgraph(\"sg\").cap(\"sg\"), or the short terminal to_graph() that \
                     needs no label: g.e(0).to_graph()."
                        .to_string(),
                )
            }
            TraverserError::QueryExecution { query, reason } if query == "subgraph" => {
                Some(subgraph_help(reason))
            }
            TraverserError::QueryExecution { query, .. } if query == "property(map)" => {
                Some(property_map_help())
            }
            TraverserError::QueryExecution { .. } => {
                Some("Review traversal query steps and conditions.".to_string())
            }
            TraverserError::UnsupportedCardinality { step, on_edge, .. } => {
                Some(unsupported_cardinality_help(step, *on_edge))
            }
            TraverserError::TokenPropertyOutsideAdd { token } => {
                Some(token_property_outside_add_help(token))
            }
            TraverserError::InvalidMergeMap { step, reason, .. } => {
                Some(invalid_merge_map_help(step, reason))
            }
            TraverserError::MergeOverride { step, key, .. } => Some(merge_override_help(step, key)),
            TraverserError::MergeVertexUnresolved { direction, reason } => {
                Some(merge_vertex_unresolved_help(*direction, reason))
            }
            TraverserError::NotImplemented { .. } => {
                Some("This feature is not yet supported in current release.".to_string())
            }
            TraverserError::SackArenaExhausted { .. } => Some(
                "Every update of a sack to a new distinct value stores one more value, so the \
                 sack grew past what one execution can address.\n\
                 Keep sacks to a few distinct values (a counter that is incremented a bounded \
                 number of times, a flag), narrow the stream before the sack is updated, for \
                 example g.with_sack(0).v().limit(1000).out().sack(Operator.sum).by(__.constant(1)).sack(), \
                 or aggregate with a reducing step such as sum() or group_count() instead of \
                 carrying the running value in the sack."
                    .to_string(),
            ),
            TraverserError::PathArenaExhausted { .. } => Some(
                "Every traverser that reaches path(), simple_path(), cyclic_path() or other_v() \
                 records its whole path, so the traversal fans out into more positions than can \
                 be tracked.\n\
                 Cap the stream before it grows, for example g.v().out().limit(1000).path(), \
                 narrow the start set, for example g.v(\"1\").out().path() instead of \
                 g.v().out().path(), or remove the path consumer when only the end \
                 elements are needed.\n\
                 When the fan-out comes from a few starting elements each having many \
                 neighbours, cap it per starting element instead of across the whole stream with \
                 local(), for example g.v().local(__.out().limit(2)).path().\n\
                 When the paths walk in cycles, drop them early with simple_path(), for example \
                 g.v().both().both().simple_path().path(), or at every hop of a loop: \
                 g.v().repeat(__.both().simple_path()).times(2).path()."
                    .to_string(),
            ),
            TraverserError::OtherVWithoutOrigin { .. } => Some(
                "other_v() reads the vertex the traversal visited right before reaching this \
                 edge, so it needs a vertex earlier in the same traversal, for example \
                 g.v(\"1\").both_e(\"knows\").other_v() or out().out_e().other_v(). Starting \
                 directly from edges has no such vertex, for example g.e().other_v(); use \
                 both_v() there instead to get both endpoints, or out_v()/in_v() to pick one side \
                 unconditionally."
                    .to_string(),
            ),
            TraverserError::InvalidRange { .. } => Some(
                "range(low, high) slices the stream to [low, high): low must be zero or a \
                 positive integer, and high must be -1 (meaning \"no upper bound\", for example \
                 g.v().range(2, -1) to skip the first two and take the rest) or an integer at \
                 least as large as low, for example g.v().range(0, 10) for the first page or \
                 g.v().range(10, 20) for the next. To take a fixed number from the start, use \
                 limit(n) instead, for example g.v().limit(10). The same bounds apply to \
                 the Scope.local form, which slices the list or map each traverser holds, for \
                 example g.v().values(\"name\").fold().range(Scope.local, 1, 3); its \
                 limit(Scope.local, n), skip(Scope.local, n) and tail(Scope.local, n) take a \
                 count of zero or more, for example \
                 g.v().values(\"name\").fold().limit(Scope.local, 2)."
                    .to_string(),
            ),
            TraverserError::InvalidModulator {
                step,
                modulator,
                reason,
                ..
            } if *modulator == crate::traversal::with_reason::MODULATOR => {
                Some(with_modulator_help(step, reason))
            }
            TraverserError::InvalidModulator { step, reason, .. } => {
                Some(invalid_modulator_help(step, reason))
            }
            TraverserError::SourceStepInChild { step } => Some(source_step_in_child_help(step)),
            TraverserError::MathExpression { expr, kind, .. } => {
                Some(math_expression_help(expr, kind, None))
            }
            TraverserError::Fail { .. } => Some(
                "The query stopped on purpose: a traverser reached its fail() step. If that \
                 branch should not fail, remove fail() or guard it so that only unexpected \
                 traversers reach it, for example \
                 g.v().coalesce(__.out(\"knows\"), __.fail(\"no friends\")) fails only for a \
                 vertex without an out(\"knows\") neighbour, and \
                 g.v().choose(__.has(\"age\"), __.values(\"age\"), __.fail(\"age missing\")) \
                 only for a vertex without an age. A mutating traversal that fails is rolled \
                 back as a whole."
                    .to_string(),
            ),
        }
    }

    /// The spelling of step names in this error's diagnostic: the one the outermost
    /// [`TraverserError::StepFailed`] carries (`g.with("render.spelling", ..)`), snake_case
    /// for every other error.
    pub fn spelling(&self) -> crate::traversal::Spelling {
        match self {
            TraverserError::StepFailed { spelling, .. }
            | TraverserError::Spelled { spelling, .. } => *spelling,
            _ => crate::traversal::Spelling::Snake,
        }
    }

    /// Stores the rendered steps of this error in `spelling` (step names and plan frames of
    /// every level) and marks the outermost step failure with it, so `help()` and the
    /// diagnostic body are respelled too. The steps are rendered in snake_case; called once
    /// per execution when `render.spelling` is not the default.
    pub(crate) fn respell(&mut self, spelling: crate::traversal::Spelling) {
        use crate::traversal::spelling::respell;
        if spelling == crate::traversal::Spelling::Snake
            || matches!(self, TraverserError::Spelled { .. })
        {
            return;
        }
        // The operation a permission denial names is data, not a call: rename it here.
        if let TraverserError::PermissionDenied { step, .. } = self.root_cause_mut() {
            *step = if step.contains('(') {
                respell(step, spelling).into_owned()
            } else {
                crate::traversal::spelling::camel_name(step).into_owned()
            };
        }
        if !matches!(self, TraverserError::StepFailed { .. }) {
            // No step frame carries the spelling: the wrapper does.
            let source =
                std::mem::replace(self, TraverserError::NotImplemented { feature: "respell" });
            *self = TraverserError::Spelled {
                spelling,
                source: Box::new(source),
            };
            return;
        }
        let mut outermost = true;
        let mut current = self;
        while let TraverserError::StepFailed {
            step_name,
            frame,
            source,
            spelling: marked,
            ..
        } = current
        {
            *step_name = respell(step_name, spelling).into_owned();
            if let Some(frame) = frame {
                for step in &mut frame.steps {
                    *step = respell(step, spelling).into_owned();
                }
                if let Some(logical) = &mut frame.logical {
                    for step in &mut logical.steps {
                        *step = respell(step, spelling).into_owned();
                    }
                }
            }
            if outermost {
                *marked = spelling;
                outermost = false;
            }
            current = source;
        }
    }
}

impl DiagnosticError for TraverserError {
    fn help(&self) -> Option<String> {
        let help = self.canonical_help()?;
        Some(crate::traversal::spelling::respell(&help, self.spelling()).into_owned())
    }

    fn details(&self) -> Vec<(String, String)> {
        match self {
            TraverserError::Spelled { source, .. } => source.details(),
            TraverserError::Value(err) => err.details(),
            TraverserError::Graph(err) => err.details(),
            TraverserError::Io(err) => err.details(),
            TraverserError::Script(err) => err.details(),
            TraverserError::Schema(err) => err.details(),
            TraverserError::StepFailed { .. } => {
                let mut details = Vec::new();
                let mut path: Vec<String> = Vec::new();
                let mut current = self;
                while let TraverserError::StepFailed {
                    step_index,
                    child_index,
                    frame,
                    source,
                    ..
                } = current
                {
                    path.extend(level_segments(*child_index, *step_index));
                    if let Some(frame) = frame {
                        match frame.render_logical() {
                            Some(logical) => {
                                details.push((format!("at #{}", path.join(".")), logical));
                                details.push(("plan".to_string(), frame.render()));
                            }
                            None => {
                                details.push((format!("at #{}", path.join(".")), frame.render()))
                            }
                        }
                    }
                    current = source;
                }
                details
            }
            TraverserError::MathExpression {
                expr,
                column,
                width,
                ..
            } => vec![(
                "equation".to_string(),
                math_underline(expr, *column, *width),
            )],
            _ => Vec::new(),
        }
    }

    /// Renders nested step failures as a single step trace followed by the root cause,
    /// instead of one `Caused by:` line per traversal level.
    fn diagnostic_body(&self) -> String {
        if let TraverserError::Spelled { spelling, source } = self {
            let body = source.diagnostic_body();
            return crate::traversal::spelling::respell(&body, *spelling).into_owned();
        }
        let mut buf = format!("Error: {self}");
        push_details(&mut buf, &self.details());

        let root = self.root_cause();
        if !std::ptr::eq(root, self) {
            buf.push_str(&format!("\nCaused by: {root}"));
            push_details(&mut buf, &root.details());
        }

        let mut current: Option<&dyn std::error::Error> = std::error::Error::source(root);
        while let Some(src) = current {
            buf.push_str(&format!("\nCaused by: {src}"));
            current = src.source();
        }
        // The stored plan frames are respelled already (`TraverserError::respell`); this brings
        // the step names inside the root cause's own message in line with them.
        match crate::traversal::spelling::respell(&buf, self.spelling()) {
            std::borrow::Cow::Borrowed(_) => buf,
            std::borrow::Cow::Owned(respelled) => respelled,
        }
    }
}

/// Example query the timeout advice is built on when the failing query is unknown.
const TIMEOUT_EXAMPLE_STEPS: [&str; 4] = ["v()", "out()", "out()", "count()"];

/// Advice for a traversal that ran past its `evaluationTimeout`, with every suggestion shown
/// as a rewrite of the failing query (`steps`, outermost level), or of an example query when
/// the query is unknown.
fn timeout_help(limit_ms: u64, steps: Option<Vec<String>>) -> String {
    let steps = steps.filter(|steps| !steps.is_empty()).unwrap_or_else(|| {
        TIMEOUT_EXAMPLE_STEPS
            .iter()
            .map(|s| s.to_string())
            .collect()
    });
    // Narrowing and capping the stream both belong right after the start step.
    let with_after_start = |inserted: &str| {
        let mut rewritten = steps.clone();
        rewritten.insert(1, inserted.to_string());
        runnable_glob_path_options(&rewritten.join("."))
    };
    let query = runnable_glob_path_options(&steps.join("."));
    let raised = limit_ms.saturating_mul(2).max(1);
    // A '**' walk of glob_path() is bounded by max_depth.
    let glob_path_advice = glob_path_query_with_max_depth(&steps)
        .map(|bounded| {
            format!(
                "Bound the '**' walk of glob_path() with max_depth, the deepest level below the \
                 start vertex it visits, for example g.{bounded}.\n"
            )
        })
        .unwrap_or_default();
    // A loop is the usual reason a small query runs long: bound it rather than the stream.
    let repeat_advice = if query.contains("repeat(") {
        "Bound every repeat() loop with times() or until(), and skip cycles with simple_path() \
         in its body, for example g.v().repeat(__.out().simple_path()).times(3) or \
         g.v().repeat(__.out().simple_path()).until(__.has(\"name\", \"<value>\")).\n\
         Equal traversers are merged automatically inside repeat(), so a loop over converging \
         paths stays cheap; path() and simple_path() record full paths, which prevents the \
         merge and keeps exponential path counts expensive, so leave them out when you only \
         need the reached elements or a count. A sack merge operator or with_bulk(false) turns \
         automatic merging off: add barrier() inside the loop body, for example \
         g.v().repeat(__.out().barrier()).times(3).count().\n"
    } else {
        ""
    };
    // Duplicates pile up where many paths converge on one vertex: merge them between two
    // expansions of the failing query, or in the example query when it has none.
    let barriered = barrier_between_expansions(&steps)
        .map(|rewritten| runnable_glob_path_options(&rewritten.join(".")))
        .unwrap_or_else(|| "v().out().barrier().out().barrier().out().count()".to_string());
    format!(
        "The traversal ran longer than its evaluationTimeout budget of {limit_ms} ms. The budget \
         is checked between steps, every 1024 traversers and every 1024 values a step \
         materializes (fold(), group(), order(), a terminal list); the step named above is the \
         one that was running.\n\
         {repeat_advice}\
         {glob_path_advice}\
         Merge duplicate traversers: barrier() merges equal traversers so later steps process \
         each distinct one once, for example g.{barriered}.\n\
         Narrow the start set with has_label() or has_id(), for example \
         g.{narrowed}.\n\
         Cap the stream before it fans out with limit(), for example g.{limited}.\n\
         Or raise the budget: g.with(\"evaluationTimeout\", {raised}).{query}. It is an administrative option: a script whose host restricts it needs Update on that Option to set it.\n\
         To see which step spends the time, run it with execute() and a profile: the profile \
         up to the timed-out step comes back with the error, for example \
         g.{query}.execute(#{{profile: true}}).\n\
         If the traversal mutates the graph, nothing of it was applied: a failing traversal \
         is rolled back.",
        narrowed = with_after_start("has_label(\"<label>\")"),
        limited = with_after_start("limit(1000)"),
    )
}

/// `steps` with a `barrier()` between every two adjacent expansion steps (`out()`, `in()`,
/// `both()`, `outE()`, `inV()`, ...), or `None` when there is no such pair.
fn barrier_between_expansions(steps: &[String]) -> Option<Vec<String>> {
    const EXPANSIONS: [&str; 10] = [
        "out(", "in(", "both(", "out_e(", "in_e(", "both_e(", "out_v(", "in_v(", "both_v(",
        "other_v(",
    ];
    let is_expansion = |step: &String| EXPANSIONS.iter().any(|name| step.starts_with(name));
    let mut rewritten = Vec::with_capacity(steps.len() + 1);
    let mut inserted = false;
    for (index, step) in steps.iter().enumerate() {
        rewritten.push(step.clone());
        if is_expansion(step) && steps.get(index + 1).is_some_and(is_expansion) {
            rewritten.push("barrier()".to_string());
            inserted = true;
        }
    }
    inserted.then_some(rewritten)
}

/// Advice for `inject()` as a direct step of a `repeat()` body.
fn repeat_inject_help() -> String {
    "TinkerPop forbids inject() as a step of a repeat() body: the injected values would enter \
     again in every iteration. Inject before the loop, for example \
     g.inject(\"y\").repeat(__.out()).times(2), or wrap it so it is not a direct step of the \
     body, for example g.v().repeat(__.union(__.identity(), __.inject(\"y\"))).times(2)."
        .to_string()
}

/// Advice for a source step (`with_sack()`, `with_side_effect()`) written inside a child
/// traversal: move it to the `g` the outer traversal starts from.
fn source_step_in_child_help(step: &str) -> String {
    let example = if step == "with_sack" {
        "g.with_sack(1).v().local(__.out().sack()) instead of g.v().local(__.with_sack(1).out().sack())"
    } else if step == "with_path" {
        "g.with_path().v().local(__.out().path()) instead of g.v().local(__.with_path().out().path()); \
         with_path() changes nothing in Graphersal (paths are recorded as the query reads them), \
         so it can also simply be left out"
    } else {
        "g.with_side_effect(\"x\", 1).v().local(__.select(\"x\")) instead of \
         g.v().local(__.with_side_effect(\"x\", 1).select(\"x\"))"
    };
    format!(
        "{step}() sets up the traversal source g: it applies to the whole query, child \
         traversals included, so it is written once on g, before the first step, for example \
         {example}. A child traversal sees the sacks and side effects of the outer traversal."
    )
}

/// Advice for a `by()` or `from()`/`to()` modulator a step cannot use at its position.
/// Advice for a step-level `with(WithOptions..)` no step took.
fn with_modulator_help(step: &str, reason: &str) -> String {
    let start = if reason == crate::traversal::with_reason::NO_STEP {
        "with(WithOptions..) configures the step right before it, so it cannot start a traversal."
            .to_string()
    } else {
        format!("{step}() cannot take this with() option.")
    };
    format!(
        "{start} Two steps take a WithOptions option: value_map() takes WithOptions.tokens \
         (with no value, or ids, labels, all, none), for example \
         g.v().value_map(\"name\").with(WithOptions.tokens, WithOptions.labels); index() takes \
         WithOptions.indexer with WithOptions.list or WithOptions.map, for example \
         g.v().values(\"name\").fold().index().with(WithOptions.indexer, WithOptions.map). \
         To set an execution option of the whole traversal use g.with(\"key\", value) with a \
         string key instead, for example g.with(\"random.seed\", 7)."
    )
}

fn invalid_modulator_help(step: &str, reason: &str) -> String {
    if reason == crate::traversal::by_reason::NO_STEP {
        return format!(
            "by() modulates the step right before it, so it cannot start a traversal. Write the \
             step first and the by() after it, for example g.v().order().by(\"name\"). {BY_STEPS}"
        );
    }
    if reason == crate::traversal::args_reason::NO_STEP {
        return format!(
            "from()/to() modulates the step right before it, so it cannot start a traversal. \
             Write the step first and from()/to() after it, for example \
             g.v(\"1\").add_e(\"knows\").to(\"2\"). {FROM_TO_STEPS}"
        );
    }
    if reason == crate::traversal::args_reason::ONE_LABEL {
        return format!(
            "from()/to() of {step}() takes exactly one step label, a window between two labelled \
             positions of the path, not a list: write g.v().as(\"a\").out().as(\"b\").path()\
             .from(\"a\").to(\"b\"). The label is set with as() before the step. {FROM_TO_STEPS}"
        );
    }
    if reason.ends_with(crate::traversal::args_reason::NOT_ACCEPTED) {
        return from_to_not_accepted_help(step);
    }
    if reason.ends_with(crate::traversal::by_reason::NOT_ACCEPTED) {
        return by_not_accepted_help(step);
    }
    if reason == crate::traversal::by_reason::COLUMN {
        return column_modulator_help(step);
    }
    if step == "glob_path" {
        return glob_path_modulator_help(reason);
    }
    if step == "dedup" {
        return dedup_modulator_help(reason);
    }
    if step == "value_map" {
        return value_map_modulator_help(reason);
    }
    if step == "aggregate" || step == "store" {
        return aggregate_modulator_help(step);
    }
    if step == "group" || step == "group_count" {
        return group_modulator_help(step, reason);
    }
    if step == "sample" {
        return "sample(n) takes at most one by(), the weight each traverser is drawn with, and it \
                must project a number: a numeric property or a traversal ending in a number, for \
                example g.e().sample(2).by(\"weight\") or g.v().sample(1).by(__.out_e().count()). \
                An order or Count is not a weight; to sort and then sample, order first: \
                g.v().order().by(\"age\").sample(2). Drop by() for a uniform sample."
            .to_string();
    }
    if step == "sack" {
        return "sack(Operator) updates the sack with one operand per traverser, so it takes a single \
                by(), for example g.with_sack(0).v().out_e().sack(Operator.sum).by(\"weight\"). To \
                combine several values into one operand, compute it in one traversal, for example \
                g.with_sack(0).v().sack(Operator.sum).by(__.values(\"age\").sum())."
            .to_string();
    }
    if reason == crate::traversal::ring_reason::KIND {
        return ring_modulator_help(step);
    }
    format!(
        "A step's by() modulators are positional: the first by() of {step}() means one thing, \
         the second another, and each position accepts only certain kinds of argument (a \
         property key, T.id/T.label, a traversal such as __.values(\"name\"), ...). \
         A list of vertex labels, such as by([\"person\", \"software\"]), is not a projection \
         {step}() can use. To keep only elements with certain labels, filter them with \
         has_label(...) before the step instead, for example \
         g.v().has_label(\"person\", \"software\").order().by(\"name\")."
    )
}

/// Advice for a `by(Column.keys)` / `by(Column.values)` on a step other than `order()`.
fn column_modulator_help(step: &str) -> String {
    format!(
        "by(Column.keys) / by(Column.values) reads the key or value of a map entry (or the keys or \
         values of a whole map), and only order() takes it, as a sort key, not {step}(). Sort map \
         entries with it, for example \
         g.v().has_label(\"person\").group().by(\"name\").by(__.out_e().values(\"weight\").sum()).unfold().order().by(Column.values, Order.desc), \
         or sort the entries inside each map with order(Scope.local).by(Column.values). To read a \
         map's keys or values as data, use select(Column.keys) / select(Column.values) after the \
         step instead, for example g.v().group().by(\"name\").select(Column.keys). {BY_STEPS}"
    )
}

/// The steps that take `by()` modulators, named in every advice about a misplaced `by()`.
const BY_STEPS: &str = "The steps that take by() are order(), dedup(), group(), group_count(), \
     select() with step labels, project(), path(), simple_path(), cyclic_path(), where(), tree(), \
     math(), value_map(), aggregate(), store(), sample() (the weight) and glob_path().";

/// Advice for a `by()` after a step that does not take `by()` modulators: where it belongs, with
/// a corrected query for the common cases.
fn by_not_accepted_help(step: &str) -> String {
    let fix = match step {
        "count" => {
            "To count per value, use group_count() with the by() instead, for example \
             g.v().group_count().by(\"name\") rather than g.v().count().by(\"name\")."
        }
        "sum" | "max" | "min" | "mean" | "median" => {
            "To aggregate a property, read it with values() first, for example \
             g.v().values(\"age\").sum() rather than g.v().sum().by(\"age\")."
        }
        "select" => {
            "They read a map as it is; put the by() on the step that builds the map, for \
             example g.v().group().by(\"name\").select(Column.keys)."
        }
        _ => {
            "Move the by() to the step it was meant for, for example g.v().out().order().by(\"name\") \
             sorts the neighbours by name; to read a property of each element, use values(), for \
             example g.v().out().values(\"name\") rather than g.v().out().by(\"name\")."
        }
    };
    let what = match step {
        "select" => "select(Column.keys) / select(Column.values)".to_string(),
        _ => format!("{step}()"),
    };
    format!(
        "by() modulates the step right before it, and {what} does not take one. {fix} {BY_STEPS}"
    )
}

/// The steps that take `from()`/`to()` modulators, named in every advice about a misplaced
/// `from()`/`to()`.
const FROM_TO_STEPS: &str = "The steps that take from()/to() are add_e(), path(), \
     simple_path() and cyclic_path().";

/// Advice for a `from()`/`to()` after a step that does not take `from()`/`to()` modulators.
fn from_to_not_accepted_help(step: &str) -> String {
    format!(
        "from()/to() modulates the step right before it, and {step}() does not take one. \
         add_e() accepts from()/to(), to point a new edge at existing elements or \
         labelled positions, for example g.v(\"1\").add_e(\"knows\").to(\"2\") or \
         g.v(\"1\").as(\"a\").out(\"knows\").add_e(\"co-developer\").from(\"a\"). An endpoint \
         can also be a traversal, g.v(\"1\").add_e(\"knows\").to(__.v(\"2\")), or a side-effect key, \
         g.with_side_effect(\"b\", \"2\").v(\"1\").add_e(\"knows\").to(\"b\"). \
         path(), simple_path() and cyclic_path() take them as a window onto the path between two \
         labelled positions, for example \
         g.v().as(\"a\").out().as(\"b\").path().from(\"a\").to(\"b\"). {FROM_TO_STEPS}"
    )
}

/// Advice for an order or `Count` passed to a step whose `by()` modulators form TinkerPop's
/// traversal ring (`select()`, `project()`, `path()`, `simple_path()`, `cyclic_path()`, `tree()`,
/// `math()`).
fn ring_modulator_help(step: &str) -> String {
    let (what, example) = match step {
        "select" => (
            "one by() per selected key, cycling when there are fewer by() than keys",
            "g.v(\"1\").as(\"a\").out(\"knows\").as(\"b\").select(\"a\", \"b\").by(\"name\") \
             reads the name of both a and b",
        ),
        "project" => (
            "one by() per key, cycling when there are fewer by() than keys",
            "g.v().project(\"name\", \"out\").by(\"name\").by(__.out().count())",
        ),
        "path" => (
            "one by() per path object, cycling along the path",
            "g.v(\"1\").out().path().by(\"name\")",
        ),
        "simple_path" | "cyclic_path" => (
            "one by() per object of the path (or of its from()/to() window), cycling along it, \
             before the simple/cyclic test",
            "g.v(\"1\").both().both().simple_path().by(\"name\")",
        ),
        "where" => (
            "the first by() projects the current object, each following one a step-label operand \
             of the predicate in textual order, cycling when there are fewer by() than operands",
            "g.v(\"1\").as(\"a\").out().where(P.gt(\"a\")).by(\"age\") compares the age of \
             each vertex with the age of a",
        ),
        "tree" => (
            "one by() per tree level, cycling along each path",
            "g.v(\"1\").out().tree().by(\"name\")",
        ),
        "math" => (
            "one by() per variable of the equation, cycling when there are fewer by() than \
             variables",
            "g.v().as(\"a\").out(\"knows\").as(\"b\").math(\"a + b\").by(\"age\")",
        ),
        _ => (
            "one by() per value, cycling",
            "g.v(\"1\").out().path().by(\"name\")",
        ),
    };
    format!(
        "{step}() applies its by() modulators round-robin, like TinkerPop's traversal ring: \
         {what}. Each by() is a projection: a property key such as by(\"name\"), T.id / T.label, \
         or a traversal such as __.out().count(). An order or Count projects nothing: drop it, \
         and sort afterwards with order().by(...) if an order was meant. For example {example}."
    )
}

/// Advice for a `by()` modulator `dedup()` cannot use, keyed on the `reason` constants of its
/// step module (any other reason is the shared label-list rejection).
fn dedup_modulator_help(reason: &str) -> String {
    use crate::traversal::step::flatbarrier_steps::step_dedup::reason as r;
    const WHAT: &str = "dedup() takes one by(): the projection each traverser is deduplicated by, \
         a property key such as by(\"name\"), T.id / T.label, or a traversal such as \
         __.out().count() whose first result is the key.";
    const EXAMPLE: &str = "For example g.v().dedup().by(T.label) keeps the first vertex of each \
         label.";
    let advice = if reason == r::KIND {
        "An order or Count is not a projection: drop it, and sort after dedup() with \
         order().by(...) if an order was meant, for example \
         g.v().dedup().by(T.label).order().by(\"name\")."
    } else if reason == r::TOO_MANY {
        "There is no second by(): to deduplicate by several values at once, combine them in one \
         traversal, for example g.v().dedup().by(__.values(\"name\", \"age\").fold())."
    } else {
        "A list of vertex labels, such as by([\"person\", \"software\"]), is not a projection: to \
         keep only elements with certain labels, filter them with has_label(...) before the step \
         instead, for example g.v().has_label(\"person\", \"software\").dedup().by(\"name\")."
    };
    format!("{WHAT} {advice} {EXAMPLE}")
}

/// Advice for a second `by()` on `aggregate()` or `store()`.
fn aggregate_modulator_help(step: &str) -> String {
    format!(
        "{step}() collects one projection of each traverser, so it takes a single by(), for \
         example g.v().{step}(\"x\").by(\"name\").cap(\"x\"). To collect several values per \
         traverser, project them in one traversal, for example \
         g.v().{step}(\"x\").by(__.values(\"name\", \"age\").fold()).cap(\"x\")."
    )
}

/// Advice for a `by()` modulator `valueMap()` cannot use, keyed on the `reason` constants of its
/// step module (any other reason is the shared label-list rejection).
fn value_map_modulator_help(reason: &str) -> String {
    use crate::traversal::step::map_steps::step_value_map::reason as r;
    const WHAT: &str = "value_map() wraps each property value in a list, such as {name: [marko], \
         age: [29]}, and its by() is a traversal applied to each of those lists; the first result \
         replaces the list.";
    const EXAMPLE: &str = "For example g.v().value_map().by(__.unfold()) returns the plain \
         values, {name: marko, age: 29}; element_map() returns them too, together with id and \
         label.";
    let advice = if reason == r::TOO_MANY {
        "value_map() takes a single by(): it is applied to every property's list. To treat the \
         properties differently, select them separately, for example \
         g.v().value_map(\"name\").by(__.unfold()), or use project()."
    } else if reason == r::KIND {
        "A property key, T.id / T.label, an order, a JSON path, Value or Count cannot take a \
         list: pass a traversal instead, or select the keys as arguments, for example \
         g.v().value_map(\"name\").by(__.unfold())."
    } else {
        "A list of vertex labels, such as by([\"person\", \"software\"]), is not a traversal: to \
         keep only elements with certain labels, filter them with has_label(...) before the step \
         instead, for example g.v().has_label(\"person\").value_map()."
    };
    format!("{WHAT} {advice} {EXAMPLE}")
}

/// Advice for a `by()` modulator `group()`/`group_count()` cannot use, keyed on the `reason`
/// constants of its step module (any other reason is the shared label-list rejection).
fn group_modulator_help(step: &str, reason: &str) -> String {
    use crate::traversal::step::barrier_steps::step_group::reason as r;
    const WHAT: &str = "group()'s by() modulators are positional: the first by() reads the \
         grouping key from each element, and the second reads the value kept under that key \
         (group_count() and by(Count) ask for a count there instead).";
    let advice = if reason == r::TOO_MANY {
        "group_count() counts the elements per key, so it takes a single by(), the key; there is \
         no value projection to give. To group and keep a projection per key, use group() with a \
         second by(), for example g.v().group().by(\"name\").by(\"age\") instead of \
         g.v().group_count().by(\"name\").by(\"age\")."
    } else if reason == r::ORDER {
        "An order, such as Order.desc, is not a projection: group() applies each by() to a key \
         or a value, it does not sort the result. Drop it, and sort afterward instead, for \
         example g.v().group().by(\"name\").unfold().order().by(Order.desc)."
    } else {
        "A list of vertex labels, such as by([\"person\", \"software\"]), is not a projection: to \
         keep only elements with certain labels, filter them with has_label(...) before the step \
         instead, for example g.v().has_label(\"person\", \"software\").group().by(\"name\")."
    };
    format!("{WHAT} {advice} For example g.v().{step}().by(\"name\").")
}

/// Advice for a `by()` modulator `glob_path()` cannot use, keyed on the `reason` constants of
/// its step module.
fn glob_path_modulator_help(reason: &str) -> String {
    use crate::traversal::step::flatmap_steps::step_glob_path::reason as r;
    const POSITIONS: &str = "glob_path()'s by() modulators are positional: the first by() is the \
         required match key a named pattern segment is compared with, a property key such as \
         by(\"name\") or T.id / T.label; the optional second by() is a non-empty list of vertex \
         labels that every visited vertex below the start must carry.";
    const EXAMPLE: &str = "For example g.v(\"root\").glob_path(\"**/*.rs\").by(\"name\")\
         .by([\"directory\",\"file\"]).";
    let advice = if reason == r::MISSING_KEY {
        "Add the match key as the first by()."
    } else if reason == r::LABELS_AS_KEY {
        "The first by() is the key and the label list goes second: put a key such as by(\"name\") \
         before the label list."
    } else if reason == r::KEY_KIND {
        "A traversal, an order, a JSON path, Value or Count cannot be the match key."
    } else if reason == r::JPATH_KEY {
        "A jpath(..) path reaches into a nested value, but the match key is the stored value of \
         one property: pass the plain property name, by(\"name\")."
    } else if reason == r::FILTER_KIND {
        "The second by() only filters by vertex label: pass a list such as by([\"directory\", \
         \"file\"]), or drop it to visit every vertex."
    } else if reason == r::EMPTY_LABELS {
        "An empty label list would admit no vertex: list at least one label, or drop the second \
         by() to visit every vertex."
    } else if reason == r::TOO_MANY {
        "There is no third by(): drop it."
    } else {
        ""
    };
    if advice.is_empty() {
        format!("{POSITIONS} {EXAMPLE}")
    } else {
        format!("{POSITIONS} {advice} {EXAMPLE}")
    }
}

/// Advice for an option value of the wrong shape, with a valid value for the key.
/// The parenthesised `(limit N, reached M)` tail of a [`TraverserError::ResourceLimitExceeded`]
/// message; empty when neither number is known.
fn limit_detail(max: Option<u64>, observed: Option<u64>) -> String {
    match (max, observed) {
        (Some(max), Some(value)) => format!(" (limit {max}, reached {value})"),
        (Some(max), None) => format!(" (limit {max})"),
        (None, Some(value)) => format!(" (reached {value})"),
        (None, None) => String::new(),
    }
}

/// How a host sets the memory budget `memory.limit`: the closing advice of every memory-budget
/// help text (a traversal's and a unit's).
const MEMORY_BUDGET_SETTING: &str = "The budget is a host setting (off by default): the \
     graphersal command line takes --memory-limit <bytes|auto>, the Python binding \
     Graph(memory_limit=...), a Rust host ExecutionPolicy::with_default(\"memory.limit\", bytes) \
     or a preset of graph_scope_with_options; \"auto\" is the cgroup memory limit minus \
     'memory.headroom'. Setting it in a query is an administrative option: it needs Update on \
     that Option, and is refused when the host locked it.";

/// Help for [`GraphError::ResourceLimitExceeded`]: a unit that is not a traversal (an import,
/// an applied change set, an outermost commit) grew the memory in use over `memory.limit`.
/// Names the operation and closes with the same host advice as a traversal's memory budget.
fn unit_resource_limit_help(
    operation: &str,
    limit: &str,
    max: Option<u64>,
    observed: Option<u64>,
) -> String {
    let raised = max.map_or(1_000_000, |max| max.saturating_mul(2).max(1));
    format!(
        "The {operation} would take the memory in use over the memory budget '{limit}'{}{}, so \
         it was stopped and everything it changed was rolled back, instead of the process \
         running out of memory. The figure is the process's live heap when the host installs \
         the tracking allocator (the graphersal command line does), else the engine's estimate: \
         the graph's footprint when the unit started (see g.memory_usage()) plus the elements it \
         added. A unit that only removes or rewrites data is never stopped, so make room first: \
         drop data you do not need, for example \
         g.with(\"memory.limit\", {raised}).v().has_label(\"tmp\").drop(), then import or \
         apply again; or give the host more memory. {MEMORY_BUDGET_SETTING}",
        max.map(|max| format!(" ({max} bytes)")).unwrap_or_default(),
        observed
            .map(|observed| format!("; it reached {observed} bytes"))
            .unwrap_or_default(),
    )
}

/// Help for [`TraverserError::ResourceLimitExceeded`]: names the knob that raises the limit and
/// shows a runnable example for it.
fn resource_limit_help(limit: &str, max: Option<u64>, observed: Option<u64>) -> String {
    let raised = max.map_or(1_000_000, |max| max.saturating_mul(2).max(1));
    match limit {
        "traversal.max_traversers" => format!(
            "The traversal kept more traversers alive between two steps than \
             'traversal.max_traversers' allows{}. This usually means an expansion such as \
             out().out().out() or a repeat() multiplies the stream. Narrow it, for example \
             g.v().has_label(\"person\").out().limit(100), aggregate with count() or \
             group_count() instead of listing, or raise the limit when the traversal source is \
             created, for example g.with(\"traversal.max_traversers\", {raised}).v().out().out().count(). \
             A host can lock this option with ExecutionPolicy::with_locked(\"traversal.max_traversers\"); \
             9223372036854775807 is as good as unlimited. Setting it is an administrative option: \
             a script whose host restricts it needs Update on that Option.",
            max.map(|max| format!(" ({max})")).unwrap_or_default()
        ),
        "script.max_value_depth" => format!(
            "A value the script handed to the engine (a step argument such as inject(x) or \
             property(\"k\", x), a parameter, or the script's result) nests arrays and maps \
             deeper than 'script.max_value_depth' allows{}. Deeply nested values are read \
             recursively and would overflow the native stack, so the depth is bounded where a \
             value enters the engine. Flatten the value, for example keep a list of items \
             instead of wrapping a list in a list in a loop: let xs = []; for i in 0..10 {{ \
             xs.push(i); }} g.inject(xs).count(Scope.local).next(). A trusted host raises the limit \
             with ScriptLimits::default().with_max_value_depth({raised}) passed to \
             graphersal::script::engine_with_limits(&limits, authorizer); the graphersal \
             command line takes --max-value-depth {raised}, the Python binding \
             graph.set_limits(max_value_depth={raised}). ScriptLimits::unlimited() keeps this \
             bound, because the native stack cannot be raised by configuration.",
            max.map(|max| format!(" ({max} levels)"))
                .unwrap_or_default()
        ),
        "traversal.max_value_depth" => format!(
            "The traversal built or wrote a value that nests arrays, maps or paths deeper than \
             'traversal.max_value_depth' allows{}. A repeat() whose body wraps its value again \
             on every iteration (repeat(__.fold()), repeat(__.path()), repeat(__.group())) or a \
             jpath(..) write with many segments does this. Bound the loop, for example \
             g.inject(1).repeat(__.fold()).times(10).next(), write to a shorter path, or raise \
             the limit when the traversal source is created, for example \
             g.with(\"traversal.max_value_depth\", {raised}).inject(1).repeat(__.fold()).times(200).count(). \
             Deeply nested values are read recursively, so keep the limit well below the \
             thousands. A host can lock this option with \
             ExecutionPolicy::with_locked(\"traversal.max_value_depth\"). Setting it is an \
             administrative option: a script whose host restricts it needs Update on that Option.",
            max.map(|max| format!(" ({max} levels)"))
                .unwrap_or_default()
        ),
        "traversal.max_materialized_bytes" => format!(
            "A step had to materialize a value or buffer larger than \
             'traversal.max_materialized_bytes' allows{}{}, by the engine's size estimate. \
             Steps that expand merged traversers into single items (fold(), aggregate(), \
             store(), group() value lists, a terminal list) do this, and so does a repeat() \
             whose body doubles its value on every iteration (repeat(__.path()), \
             repeat(__.group())). Prefer a step that works on the multiplicity directly: count() \
             instead of fold(), for example g.v().repeat(__.both()).times(8).count(); \
             group_count() to see how often each result occurs, for example \
             g.v().repeat(__.both()).times(8).group_count(); dedup() or limit(n) before the \
             materializing step, for example g.v().repeat(__.both()).times(8).dedup().fold(); and \
             bound a loop that grows its value, for example \
             g.inject(1).repeat(__.path()).times(10).count(). If you have the memory, raise the \
             limit when the traversal source is created, for example \
             g.with(\"traversal.max_materialized_bytes\", {raised}).v().repeat(__.both()).times(8).fold(). \
             A host can lock this option with \
             ExecutionPolicy::with_locked(\"traversal.max_materialized_bytes\"). Setting it is an \
             administrative option: a script whose host restricts it needs Update on that Option.",
            max.map(|max| format!(" ({max} bytes)")).unwrap_or_default(),
            observed
                .map(|observed| format!("; this one needed at least {observed} bytes"))
                .unwrap_or_default(),
        ),
        "memory.limit" => format!(
            "The traversal would take the memory in use over the memory budget \
             'memory.limit'{}{}, so it was stopped and everything it changed was rolled back, \
             instead of the process running out of memory. The figure is the process's live \
             heap when the host installs the tracking allocator (the graphersal command line \
             does), else the engine's estimate: the graph's footprint (see g.memory_usage()) \
             plus what the traversal holds and adds. Make the traversal hold less: count() \
             instead of fold(), for example g.v().repeat(__.both()).times(8).count(); \
             dedup() or limit(n) before a materializing step, for example \
             g.v().out().dedup().fold(); bound a loop that grows its value, for example \
             g.inject(1).repeat(__.path()).times(10).count(); write in smaller batches, for example \
             g.v().has_label(\"person\").limit(1000).property(\"seen\", true). When the graph \
             itself is over the budget, every traversal fails at its first step: drop data you \
             do not need under a raised budget, for example \
             g.with(\"memory.limit\", {raised}).v().has_label(\"tmp\").drop(), or give the \
             host more memory. {MEMORY_BUDGET_SETTING}",
            max.map(|max| format!(" ({max} bytes)")).unwrap_or_default(),
            observed
                .map(|observed| format!("; it reached {observed} bytes"))
                .unwrap_or_default(),
        ),
        "traversal.max_string_bytes" => format!(
            "A step built a string longer than 'traversal.max_string_bytes' allows{}{}. \
             replace(), concat(), conjoin() and format() can multiply the length of their input \
             (replace() of a short text by a long one at every match, concat() of a string with \
             itself in a loop); the limit stops them before the string is allocated, as \
             'script.max_string_size' does for the strings a script builds. Shorten the input or \
             the replacement, for example g.v().values(\"name\").replace(\"a\", \"b\"), \
             bound a loop that grows a string, for example \
             g.inject(\"x\").repeat(__.concat(__.identity())).times(10), or raise the limit when \
             the traversal source is created, for example \
             g.with(\"traversal.max_string_bytes\", {raised}).v().values(\"name\").replace(\"a\", \"aa\"). \
             A host can lock this option with \
             ExecutionPolicy::with_locked(\"traversal.max_string_bytes\"). Setting it is an \
             administrative option: a script whose host restricts it needs Update on that Option.",
            max.map(|max| format!(" ({max} bytes)")).unwrap_or_default(),
            observed
                .map(|observed| format!("; this one would be {observed} bytes"))
                .unwrap_or_default(),
        ),
        other if other.starts_with("script.") => {
            let field = other.trim_start_matches("script.");
            format!(
                "The script ran past its '{other}' limit{}. Bound the loop or the data it builds. \
                 A trusted host raises the limit with ScriptLimits::default().with_{field}({raised}) \
                 passed to graphersal::script::engine_with_limits(&limits, authorizer), or removes all limits \
                 with ScriptLimits::unlimited(). The graphersal command line takes \
                 --{flag} <n>, for example graphersal --{flag} {raised} -e 'g.v().count().next()'.",
                max.map(|max| format!(" of {max}")).unwrap_or_default(),
                flag = field.replace('_', "-"),
            )
        }
        other => format!(
            "The limit '{other}' was exceeded. Raise it through the option or configuration of \
             the same name, for example g.with(\"{other}\", {raised}).v().count()."
        ),
    }
}

/// Help for [`TraverserError::Cancelled`].
fn cancelled_help() -> String {
    "The query was stopped on request (the Stop button) and everything it changed was rolled \
     back; nothing of it is kept. Run it again to get its results. To bound a slow query instead \
     of stopping it by hand, give it a budget: g.with(\"evaluationTimeout\", 5000).v().out().count()."
        .to_string()
}

/// Help for [`TraverserError::BulkOverflow`].
fn bulk_overflow_help(step: &str) -> String {
    format!(
        "Equal traversers are counted as one record with a multiplicity, and the multiplicity at \
         step '{step}' grew beyond 9223372036854775807 (2^63 - 1), the largest exact count. \
         Narrow the start set, for example g.v().has_label(\"person\").repeat(__.out()).times(8).count() \
         instead of g.v().repeat(__.out()).times(8).count(), or bound the loop with a smaller \
         times(n) or an until() condition."
    )
}

/// Help for [`TraverserError::BulkExpansionLimit`].
fn bulk_expansion_limit_help(step: &str, requested: u64, limit: u64) -> String {
    format!(
        "Step '{step}' needs every value as its own item, but equal traversers are kept as one \
         record with a multiplicity (bulk). It has to expand each merged record into one value \
         per unit of multiplicity, which would produce {requested} values, more than the limit \
         of {limit} set by 'bulk.max_expansion'. Steps such as fold(), aggregate(), store(), \
         group() value lists and a terminal list do this. Prefer a step that works on the \
         multiplicity directly: count() instead of fold(), for example \
         g.v().repeat(__.out()).times(8).count(); group_count() to see how often each result \
         occurs, for example g.v().repeat(__.out()).times(8).values(\"name\").group_count(); \
         dedup() before the step to keep one item per distinct result, for example \
         g.v().repeat(__.out()).times(8).dedup().values(\"name\").fold(); or limit(n) before \
         the step to keep only the first n, for example \
         g.v().repeat(__.out()).times(8).limit(100).values(\"name\").fold(). If you really need \
         all {requested} values and have the memory for them, raise the limit when the traversal \
         source is created, for example \
         g.with(\"bulk.max_expansion\", {requested}).v().repeat(__.out()).times(8).values(\"name\").fold(). It is an administrative option: a script whose host restricts it needs Update on that Option to set it."
    )
}

fn invalid_option_help(key: &str) -> String {
    match key {
        "bulk.merge" => "Set 'bulk.merge' to true or false when the traversal source is created, \
             for example g.with(\"bulk.merge\", false).v().out().out().count(). Merged and \
             unmerged runs return the same results; false is a diagnosis aid."
            .to_string(),
        "traversal.max_traversers" => "Set 'traversal.max_traversers' to a positive integer number \
             of traversers when the traversal source is created, for example \
             g.with(\"traversal.max_traversers\", 50000000).v().out().out().count(); the default is \
             10000000, and 9223372036854775807 is as good as unlimited."
            .to_string(),
        "traversal.max_materialized_bytes" => "Set 'traversal.max_materialized_bytes' to a \
             positive integer number of bytes when the traversal source is created, for example \
             g.with(\"traversal.max_materialized_bytes\", 2147483648).v().repeat(__.both()).times(8).fold(); \
             the default is 1073741824 (1 GiB; 268435456 on wasm32)."
            .to_string(),
        "memory.limit" => "Set 'memory.limit' to a positive integer number of bytes, or to \
             \"auto\" for the cgroup memory limit of the process minus 'memory.headroom', for \
             example g.with(\"memory.limit\", 4294967296).v().out().fold() or \
             g.with(\"memory.limit\", \"auto\").v().out().fold(). Without the option there is \
             no memory budget (the default)."
            .to_string(),
        "memory.headroom" => "Set 'memory.headroom' to a non-negative integer number of bytes: \
             what memory.limit \"auto\" keeps free below the cgroup limit, for example \
             g.with(\"memory.limit\", \"auto\").with(\"memory.headroom\", 268435456).v().out().fold(). \
             The default is a tenth of the cgroup limit, at least 67108864 (64 MiB) and at most \
             half of the limit."
            .to_string(),
        "traversal.max_string_bytes" => "Set 'traversal.max_string_bytes' to a positive integer \
             number of bytes when the traversal source is created, for example \
             g.with(\"traversal.max_string_bytes\", 67108864).v().values(\"name\").replace(\"a\", \"aa\"); \
             the default is 16777216 (16 MiB)."
            .to_string(),
        "traversal.max_value_depth" => "Set 'traversal.max_value_depth' to a positive integer \
             number of nesting levels when the traversal source is created, for example \
             g.with(\"traversal.max_value_depth\", 256).inject(1).repeat(__.fold()).times(200).count(); \
             the default is 128."
            .to_string(),
        "bulk.max_expansion" => "Set 'bulk.max_expansion' to a positive integer number of values \
             when the traversal source is created, for example \
             g.with(\"bulk.max_expansion\", 1000000).v().out().fold(); the default is 10000000."
            .to_string(),
        "bulk.one" => "Set 'bulk.one' to true or false when the traversal source is created, \
             for example g.with(\"bulk.one\", true).v().out().barrier().count(), or use \
             with_bulk(false), which sets it. With bulk.one a merge keeps bulk 1, so duplicates collapse at barrier()."
            .to_string(),
        GLOB_PATH_MAX_DEPTH => glob_path_max_depth_help(None),
        "random.seed" => "Set 'random.seed' to an integer when the traversal source is created, \
             for example g.with(\"random.seed\", 42).v().sample(2); the same seed makes coin(), \
             sample() and order().by(Order.shuffle) draw the same values on every run. Without \
             the option the draws are seeded from the operating system's entropy."
            .to_string(),
        "choose().option" => "choose() picks at most one option, so it rejects a Pick.any option \
             and a traversal as an option key. Test the selector's value with a predicate or a \
             literal instead, for example g.v().choose(__.values(\"age\")).option(P.gt(30), \
             __.constant(\"old\")).option(Pick.none, __.constant(\"young\")), or use branch(), \
             which accepts a traversal key and Pick.any, for example \
             g.v().branch(__.identity()).option(__.has_label(\"software\"), __.values(\"name\")). \
             With no matching option choose() passes the traverser through unchanged."
            .to_string(),
        "render.spelling" => "Set 'render.spelling' to \"snake\" (the default: has_label(), \
             group_count()) or \"camel\" (Gremlin camelCase: hasLabel(), groupCount()), for \
             example g.with(\"render.spelling\", \"camel\").v().has_label(\"person\").profile(). \
             It changes only how .profile() and error messages spell the steps, never a result."
            .to_string(),
        "repeat.order" => "Set 'repeat.order' to \"bfs\" (breadth first, the default) or \"dfs\" \
             (depth first) when the traversal source is created, for example \
             g.with(\"repeat.order\", \"dfs\").v(\"1\").repeat(__.out()).times(2)."
            .to_string(),
        "repeat.max_loops" => "Set 'repeat.max_loops' to a positive integer number of iterations \
             when the traversal source is created, for example \
             g.with(\"repeat.max_loops\", 100).v(\"1\").repeat(__.out()).until(__.has(\"name\", \"<value>\")); \
             the default is 10000 and times(n) is never limited."
            .to_string(),
        "optimizer.disabled" | "optimizer.enabled" => format!(
            "Set 'optimizer.disabled'/'optimizer.enabled' to an array of optimizer rule names \
             when the traversal source is created, for example \
             g.with(\"optimizer.disabled\", [\"filter_reorder\"]).v().has_label(\"person\").count(); \
             every name must be one of the rules a profile lists as \"Optimizer rules applied\" \
             (optimizer_rules_applied of g.v().has_label(\"person\").count().profile()) \
             ({rules} — see the book's Query Optimizer chapter for each rule's default on/off \
             state) or the reserved name \"all\", which expands to every one of them — e.g. \
             g.with(\"optimizer.disabled\", [\"all\"]).v().has_label(\"person\").count() \
             to measure a query's genuinely unoptimized plan; and the same name cannot appear in \
             both lists at once.",
            rules = crate::traversal::optimizer::KNOWN_RULES
                .iter()
                .map(|(name, _)| *name)
                .collect::<Vec<_>>()
                .join(", ")
        ),
        "max_rows" | "max_items" => format!(
            "Set '{key}' to a positive integer for this call, for example \
             g.v().to_table(#{{{key}: 20}}). To show everything, remove both display limits \
             with no_limit: true instead, for example g.v().to_table(#{{no_limit: true}}); \
             0 is not a way to say \"unlimited\"."
        ),
        "no_limit" => "no_limit: true removes both display limits, so it cannot be combined \
             with max_rows or max_items in the same options map. Use either \
             g.v().to_table(#{no_limit: true}) to show everything, or \
             g.v().to_table(#{max_rows: 20, max_items: 10}) to set other limits; \
             no_limit: false keeps the session default."
            .to_string(),
        "options" => "Pass the display options as a map, for example \
             g.v().to_table(#{max_rows: 20, columns: [\"name\", \"age\"]}), or a list of columns, \
             for example g.v().to_table([\"name\", \"age\"])."
            .to_string(),
        "render.max_rows" | "render.max_items" => format!(
            "Set '{key}' to a positive integer, for example g.with(\"{key}\", 20).v(). It is the \
             session default of a display limit; to show everything for one call, use \
             g.v().to_table(#{{no_limit: true}})."
        ),
        _ => format!(
            "Set '{key}' to a non-negative integer number of milliseconds when the traversal \
             source is created, for example g.with(\"evaluationTimeout\", 5000).v().count(); \
             0 disables the timeout."
        ),
    }
}

/// The `InvalidOption` key of an out-of-range `glob_path()` `max_depth`.
const GLOB_PATH_MAX_DEPTH: &str =
    crate::traversal::step::flatmap_steps::step_glob_path::MAX_DEPTH_OPTION;

/// Splits a rendered `glob_path("..")` step right after the closing quote of its pattern
/// literal, so its options can be edited; `None` for any other step.
fn split_glob_path_step(step: &str) -> Option<(&str, &str)> {
    const PREFIX: &str = "glob_path(\"";
    let literal = step.strip_prefix(PREFIX)?;
    let mut escaped = false;
    for (i, c) in literal.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' => escaped = true,
            '"' => return Some(step.split_at(PREFIX.len() + i + 1)),
            _ => {}
        }
    }
    None
}

/// A rendered query with its `glob_path()` options maps written as Rhai map literals
/// (`#{max_depth: 3}`), so it can be run as it is.
fn runnable_glob_path_options(query: &str) -> String {
    query.replace("\", {", "\", #{")
}

/// The step with its out-of-range `max_depth` replaced by the nearest valid value; `None` when
/// the step is not a `glob_path()` with an out-of-range `max_depth`.
fn glob_path_step_with_valid_max_depth(step: &str) -> Option<String> {
    const OPTION: &str = ", {max_depth: ";
    let (head, rest) = split_glob_path_step(step)?;
    let value = rest.strip_prefix(OPTION)?;
    let end = value
        .char_indices()
        .find(|&(i, c)| !(c.is_ascii_digit() || (i == 0 && c == '-')))
        .map_or(value.len(), |(i, _)| i);
    let depth: i128 = value[..end].parse().ok()?;
    let valid = if depth < 1 {
        1
    } else if depth > i128::from(u32::MAX) {
        i128::from(u32::MAX)
    } else {
        return None;
    };
    Some(format!("{head}{OPTION}{valid}{}", &value[end..]))
}

/// Advice for an out-of-range `glob_path()` `max_depth`, with the failing query corrected when
/// it is known.
fn glob_path_max_depth_help(steps: Option<Vec<String>>) -> String {
    let corrected = steps.and_then(|steps| {
        let mut fixed = false;
        let rewritten: Vec<String> = steps
            .iter()
            .map(
                |step| match (fixed, glob_path_step_with_valid_max_depth(step)) {
                    (false, Some(valid)) => {
                        fixed = true;
                        valid
                    }
                    _ => step.clone(),
                },
            )
            .collect();
        fixed.then(|| runnable_glob_path_options(&rewritten.join(".")))
    });
    let example = corrected.unwrap_or_else(|| {
        "v(\"root\").glob_path(\"**/*.rs\", #{max_depth: 3}).by(\"name\")".to_string()
    });
    format!(
        "max_depth is the deepest level below the start vertex that glob_path() visits: the start \
         vertex is level 0 and its children are level 1, so max_depth is an integer from 1 to \
         4294967295. Leave it out to walk without a bound. For example g.{example}."
    )
}

/// The failing query with `max_depth: 3` added to its first `glob_path()` over `**` that has no
/// `max_depth` yet; `None` when there is no such step on the outermost level.
fn glob_path_query_with_max_depth(steps: &[String]) -> Option<String> {
    let position = steps.iter().position(|step| {
        split_glob_path_step(step)
            .is_some_and(|(head, rest)| head.contains("**") && !rest.starts_with(", {max_depth: "))
    })?;
    let mut rewritten = steps.to_vec();
    let (head, rest) = split_glob_path_step(&steps[position])?;
    rewritten[position] = match rest.strip_prefix(", {") {
        Some(options) => format!("{head}, {{max_depth: 3, {options}"),
        None => format!("{head}, {{max_depth: 3}}{rest}"),
    };
    Some(runnable_glob_path_options(&rewritten.join(".")))
}

/// Advice for a `g.with(key, ..)` a query attempted on a key the host has locked via
/// [`crate::graph::ExecutionPolicy::with_locked`]. Unlike `invalid_option_help`, this never
/// suggests "try a different value" — no value the query supplies is accepted for a locked key,
/// so the advice explains why (a host-level policy fixed at construction, not something the
/// query can influence) rather than how to satisfy it.
fn locked_option_help(key: &str) -> String {
    format!(
        "'{key}' is fixed by the execution policy of the environment running this query and \
         cannot be set or overridden with g.with(\"{key}\", ..), regardless of the value \
         supplied. This is a host-level safety ceiling (see `ExecutionPolicy::with_locked` in \
         the embedding application, and the \"Execution Options Reference\" book chapter for \
         which keys this instance may lock), not a malformed value — removing or changing the \
         g.with(\"{key}\", ..) call in the query has no effect either way, since the policy's own \
         default (or, absent one, the engine's default) applies regardless of what the query \
         asks for."
    )
}

/// Advice for a [`TraverserError::PermissionDenied`]: who decides, how a host allows the
/// request, and what the query can do instead.
fn permission_denied_help(step: &str, request: &crate::graph::AccessRequest<'_>) -> String {
    use crate::graph::{Action, Resource};
    let instead = match (request.action, request.resource) {
        (Action::Create | Action::Update | Action::Delete, Resource::Data { .. }) => format!(
            " A query that may not change the host graph can still build its own: a graph the \
             script builds itself is private and always writable, for example \
             GraphSource::empty().add_v(\"x\").next() or a subgraph() result; remove \
             {step}() from the query to only read."
        ),
        (Action::Read, Resource::Data { .. }) => {
            " Without reading data a script can only compute with its own values; it cannot \
             traverse the host graph."
                .to_string()
        }
        (_, Resource::Schema) => " The schema is protected separately from the data: \
             get_schema(), infer_schema(), validate_schema(..) and diff_schema(..) read it (Read), set_schema(..) and patch_schema(..) change it (Update)."
            .to_string(),
        (_, Resource::Definition { .. }) => {
            " The catalog of definitions (saved queries) is protected separately from the \
             data: listing and reading a definition asks Read, defining one Create (Update \
             to replace, move or describe it), removing one Delete, calling a saved query \
             Execute."
                .to_string()
        }
        (_, Resource::File { .. }) => {
            " File access (export_graphml, import_graphml, GraphSource::file, \
             Rhai's import) is decided per file. When the host set a file root \
             (AccessPolicy::with_file_root), use a relative path inside it, without '..'."
                .to_string()
        }
        (_, Resource::Option { .. }) => {
            " The administrative g.with() options (the resource ceilings evaluationTimeout, \
             repeat.max_loops, bulk.max_expansion, traversal.max_traversers and the engine \
             switches optimizer.disabled, optimizer.enabled, path.analysis, bulk.merge) are \
             the host's to set: remove the g.with(..) call; the host's settings apply."
                .to_string()
        }
        _ => String::new(),
    };
    format!(
        "'{step}' needs {request}, which the host running this script does not allow. \
         Everything is allowed by default; the host decides with an Authorizer, for example \
         the ready-made AccessPolicy::read_only().allow(ActionKind::{action}, \
         ResourceKind::{resource}) passed to script::engine_with_limits(..) and \
         script::graph_scope_with_options(..) (or eval_value_with_limits), or \
         GraphTraversalSource::with_authorizer(..) in Rust.{instead}",
        action = request.action.kind(),
        resource = request.resource.kind(),
    )
}

/// Advice for a `repeat()` that hit `repeat.max_loops`, with every suggestion written on the
/// failing loop body and, when known, the failing query.
fn repeat_limit_help(
    max_loops: u32,
    loop_name: Option<&str>,
    body: &str,
    steps: Option<Vec<String>>,
) -> String {
    let repeat = match loop_name {
        Some(name) => format!("repeat(\"{name}\", {body})"),
        None => format!("repeat({body})"),
    };
    let simple = match loop_name {
        Some(name) => format!("repeat(\"{name}\", {body}.simple_path())"),
        None => format!("repeat({body}.simple_path())"),
    };
    let steps = steps.filter(|steps| !steps.is_empty());
    let start = steps
        .as_deref()
        .and_then(glob_path_start)
        .unwrap_or_else(|| "v()".to_string());
    let query = steps
        .map(|steps| steps.join("."))
        .unwrap_or_else(|| format!("v().{repeat}"));
    let raised = u64::from(max_loops)
        .saturating_mul(2)
        .min(u64::from(u32::MAX));
    let repeat_barrier = match loop_name {
        Some(name) => format!("repeat(\"{name}\", {body}.barrier())"),
        None => format!("repeat({body}.barrier())"),
    };
    format!(
        "The loop ran {max_loops} iterations without stopping: it walks a cycle, or nothing \
         ends it.\n\
         Bound the number of iterations with times(), for example {repeat}.times(3).\n\
         Stop at a target with until(), for example {repeat}.until(__.has(\"name\", \"<value>\")).\n\
         On a cyclic graph, drop the paths that revisit an element with simple_path(), for \
         example {simple}.\n\
         Equal traversers are merged automatically inside repeat(), but path() and simple_path() \
         record full paths and prevent that merge, so exponential path counts stay expensive \
         with them. A sack merge operator or with_bulk(false) turns automatic merging off: add \
         barrier() inside the loop body, for example {repeat_barrier}.\n\
         Or raise the limit: g.with(\"repeat.max_loops\", {raised}).{query}. It is an administrative option: a script whose host restricts it needs Update on that Option to set it.\n\
         On a tree-shaped graph (directories, org charts, categories), walk the levels below a \
         vertex with glob_path() instead: it follows outgoing edges along a pattern, prunes \
         branches that cannot match and stops on cycles without a loop limit, for example \
         g.{start}.glob_path(\"**/*.rs\").by(\"name\"), or g.{start}.glob_path(\"**\").by(\"name\") \
         for every level below; bound how deep it walks with max_depth, for example \
         g.{start}.glob_path(\"**\", #{{max_depth: 3}}).by(\"name\")."
    )
}

/// The steps of a failing query before its loop (`repeat()` or a prefix `emit()`/`until()`/
/// `times()`), joined, as the start of a `glob_path()` rewrite; `None` when the loop is not on
/// that level or nothing precedes it.
fn glob_path_start(steps: &[String]) -> Option<String> {
    let loop_start = steps.iter().position(|step| {
        ["repeat(", "emit(", "until(", "times("]
            .iter()
            .any(|prefix| step.starts_with(prefix))
    })?;
    (loop_start > 0).then(|| steps[..loop_start].join("."))
}

/// Advice for `loops(name)` that names no enclosing loop.
fn unknown_loop_name_help(name: &str, active: &[String]) -> String {
    match active.first() {
        Some(innermost) => format!(
            "The enclosing named loops are: {}. Read one of them, for example \
             loops(\"{innermost}\"), or name the loop that loops(\"{name}\") should read: \
             repeat(\"{name}\", __.out()).",
            active.join(", ")
        ),
        None => format!(
            "No enclosing repeat() is named '{name}'. Name the loop, for example \
             repeat(\"{name}\", __.out()).until(__.loops(\"{name}\").is(2)), or read the \
             innermost loop with loops()."
        ),
    }
}

/// Advice for `times()`/`until()`/`emit()` without a `repeat()`, written on the steps of the
/// failing level before the modulator (`g.` or `__.` prefixed).
fn repeat_without_body_help(modulator: &str, prefix: Option<String>) -> String {
    let prefix = prefix.unwrap_or_else(|| "g.v()".to_string());
    let join = |rest: &str| {
        if prefix.ends_with('.') {
            format!("{prefix}{rest}")
        } else {
            format!("{prefix}.{rest}")
        }
    };
    format!(
        "Write the loop body with repeat(). Before repeat(), {modulator} is checked before each \
         iteration, for example {before}; after it, {modulator} is checked after each \
         iteration, for example {after}.",
        before = join(&format!("{modulator}.repeat(__.out())")),
        after = join(&format!("repeat(__.out()).{modulator}")),
    )
}

/// Advice for [`TraverserError::OptionWithoutBranch`]: `.option(pick, traversal)` written with
/// no `choose(traversal)`/`branch(traversal)` to attach to (or attached to the locked 3-argument
/// `choose(predicate, onTrue, onFalse)` form).
fn option_without_branch_help(modulator: &str) -> String {
    format!(
        "{modulator} must follow choose(traversal) or branch(traversal), for example \
         g.v().choose(__.label()).option(\"person\", __.out(\"knows\")).option(\"software\", \
         __.out(\"created\")), or g.v().branch(__.label()).option(\"person\", __.out(\"knows\")); \
         choose(predicate, onTrue, onFalse) (the 3-argument if/then/else form) already has its \
         two branches fixed and does not accept further .option() calls. \
         option(Merge.onCreate|onMatch, ..) must follow merge_v()/merge_e(), for example \
         g.merge_v(#{{\"T.label\": \"person\", \"name\": \"marko\"}}).option(Merge.onCreate, \
         #{{\"age\": 29}}); option(Merge.outV|inV, ..) must follow merge_e(), for example \
         g.merge_e(#{{\"Direction.OUT\": Merge.outV, \"Direction.IN\": \"2\"}}).option(Merge.outV, \
         #{{\"T.id\": \"1\"}})."
    )
}

/// Advice for [`TraverserError::InvalidMergeMap`], keyed on what is wrong with the map.
fn invalid_merge_map_help(step: &str, reason: &str) -> String {
    let specific = if reason.contains("hidden key: ~id") {
        format!(
            "Write the id with the reserved key \"T.id\" instead of \"~id\", for example \
             g.{step}(#{{\"T.id\": \"1\"}}). "
        )
    } else if reason.contains("hidden key: ~label")
        || reason.contains("Label can not be a hidden key")
    {
        format!(
            "Write the label with the reserved key \"T.label\" and a plain label value, for \
             example g.{step}(#{{\"T.label\": \"person\"}}). "
        )
    } else if reason.contains("option(onMatch)") {
        format!(
            "option(Merge.onMatch, ..) only updates properties of the matched element, for \
             example g.{step}(#{{\"name\": \"marko\"}}).option(Merge.onMatch, #{{\"age\": 30}}); \
             put T.id/T.label into the merge() map or option(Merge.onCreate, ..) instead. "
        )
    } else if reason.contains("vertex lookup map") {
        "The option(Merge.outV|inV, map) map is a vertex search (\"T.id\", \"T.label\" and \
         properties), for example option(Merge.outV, #{\"T.id\": \"1\"}); the edge's \
         Direction keys belong to the merge_e() map. "
            .to_string()
    } else if reason.contains("Direction.BOTH") {
        "An edge has two named ends: write \"Direction.OUT\" and \"Direction.IN\" instead of \
         \"Direction.BOTH\", for example g.merge_e(#{\"T.label\": \"knows\", \"Direction.OUT\": \
         \"1\", \"Direction.IN\": \"2\"}). "
            .to_string()
    } else if reason.contains("cannot take the placeholder") {
        "Each end takes its own placeholder: \"Direction.OUT\": Merge.outV and \"Direction.IN\": \
         Merge.inV, for example g.v(\"1\").as(\"a\").v(\"2\").as(\"b\").merge_e(#{\"Direction.OUT\": \
         Merge.outV, \"Direction.IN\": Merge.inV}).option(Merge.outV, \
         __.select(\"a\")).option(Merge.inV, __.select(\"b\")). "
            .to_string()
    } else if reason.contains("resolves an edge vertex of merge_e()") {
        "option(Merge.outV|inV, ..) belongs to merge_e(), for example \
         g.merge_e(#{\"T.label\": \"knows\", \"Direction.OUT\": Merge.outV, \"Direction.IN\": \
         \"2\"}).option(Merge.outV, #{\"T.id\": \"1\"}); merge_v() takes only \
         option(Merge.onCreate, ..) and option(Merge.onMatch, ..). "
            .to_string()
    } else if reason.contains("Direction keys") {
        "Vertices have no endpoints: Direction.OUT/Direction.IN keys belong to merge_e(), for \
         example g.merge_e(#{\"T.label\": \"knows\", \"Direction.OUT\": \"1\", \"Direction.IN\": \
         \"2\"}). "
            .to_string()
    } else if reason.contains("produced no map") || reason.contains("expects a map") {
        format!(
            "Pass a map, null or a traversal that yields a map, for example \
             g.{step}(#{{\"T.label\": \"person\", \"name\": \"marko\"}}) or \
             g.inject(#{{\"T.label\": \"person\", \"name\": \"marko\"}}).{step}(). "
        )
    } else {
        String::new()
    };
    let general = if step == "merge_e" {
        "A merge_e() map holds property keys plus the reserved keys \"T.id\", \"T.label\", \
         \"Direction.OUT\" and \"Direction.IN\", for example g.merge_e(#{\"T.label\": \"knows\", \
         \"Direction.OUT\": \"1\", \"Direction.IN\": \"2\"}).option(Merge.onCreate, \
         #{\"weight\": 0.5})"
    } else {
        "A merge_v() map holds property keys plus the reserved keys \"T.id\" and \"T.label\", for \
         example g.merge_v(#{\"T.label\": \"person\", \"name\": \"marko\"}).option(Merge.onCreate, \
         #{\"age\": 29})"
    };
    format!(
        "{specific}{general}; null or #{{}} matches every element. Keys starting with \"~\" and \
         other \"T.\"/\"Direction.\" keys are not allowed."
    )
}

/// Advice for [`TraverserError::MergeOverride`].
fn merge_override_help(step: &str, key: &str) -> String {
    let example = if step == "merge_e" {
        "g.merge_e(#{\"T.label\": \"knows\", \"Direction.OUT\": \"1\", \"Direction.IN\": \
         \"2\"}).option(Merge.onCreate, #{\"weight\": 0.5})"
    } else {
        "g.merge_v(#{\"T.label\": \"person\", \"name\": \"marko\"}).option(Merge.onCreate, \
         #{\"age\": 29})"
    };
    format!(
        "option(Merge.onCreate, ..) can only add keys to the merge() map: a key present in both \
         must have the same value there. Remove \"{key}\" from the onCreate map (the created \
         element inherits it from merge()), for example {example}, or change it in the merge() \
         map itself."
    )
}

/// `math("<expr>")` with a caret line under the offending token (1-based `column`, `width`
/// characters), for the `equation` detail of [`TraverserError::MathExpression`].
fn math_underline(expr: &str, column: usize, width: usize) -> String {
    const OPEN: usize = 6; // `math("`
    let (shown, column) = math_window(expr, column);
    format!(
        "math(\"{shown}\")\n{}{}",
        " ".repeat(OPEN + column.saturating_sub(1)),
        "^".repeat(width.clamp(1, crate::value::literal::MAX_LITERAL_CHARS))
    )
}

/// The part of a long equation shown above the underline: `MAX_LITERAL_CHARS` characters
/// around `column` (1-based), with `…` where it is cut, and the column inside that part.
fn math_window(expr: &str, column: usize) -> (String, usize) {
    let max = crate::value::literal::MAX_LITERAL_CHARS;
    let chars: Vec<char> = expr.chars().collect();
    if chars.len() <= max {
        return (expr.to_string(), column);
    }
    let start = column
        .saturating_sub(1)
        .saturating_sub(max / 2)
        .min(chars.len());
    let end = (start + max).min(chars.len());
    let mut shown = String::new();
    let mut shift = start;
    if start > 0 {
        shown.push('…');
        shift -= 1;
    }
    shown.extend(&chars[start..end]);
    if end < chars.len() {
        shown.push('…');
    }
    (shown, column.saturating_sub(shift))
}

/// `expr` with every identifier `name` (a whole token, not part of a longer name, a nested key
/// or a quoted string) replaced by `with`.
fn math_replace_identifier(expr: &str, name: &str, with: &str) -> String {
    let mut out = String::with_capacity(expr.len() + with.len());
    let mut rest = expr;
    // The previous character, to skip a key after `.` (`_.value`) and identifier tails.
    let mut prev: Option<char> = None;
    let mut quote: Option<char> = None;
    while let Some(c) = rest.chars().next() {
        if let Some(q) = quote {
            out.push(c);
            rest = &rest[c.len_utf8()..];
            if c == q {
                quote = None;
            } else if c == '\\'
                && let Some(escaped) = rest.chars().next()
            {
                out.push(escaped);
                rest = &rest[escaped.len_utf8()..];
            }
            prev = Some(c);
            continue;
        }
        if c == '"' || c == '\'' {
            quote = Some(c);
            out.push(c);
            rest = &rest[1..];
            prev = Some(c);
            continue;
        }
        if c.is_ascii_alphabetic() || c == '_' {
            let end = rest
                .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
                .unwrap_or(rest.len());
            let ident = &rest[..end];
            if ident == name && prev != Some('.') {
                out.push_str(with);
            } else {
                out.push_str(ident);
            }
            rest = &rest[end..];
            prev = ident.chars().last();
            continue;
        }
        out.push(c);
        rest = &rest[c.len_utf8()..];
        prev = Some(c);
    }
    out
}

/// The failing query with its top-level `math("<expr>")` step rewritten: `before` is inserted
/// right before the step, and the equation is replaced by `new_expr`. `None` when the query is
/// unknown, the `math()` step is not at its outermost level, or the step carries `by()`s.
fn math_rewrite_query(
    steps: Option<&[String]>,
    expr: &str,
    before: Option<&str>,
    new_expr: &str,
) -> Option<String> {
    let step = format!("math(\"{expr}\")");
    let mut rewritten: Vec<String> = Vec::new();
    let mut found = false;
    for s in steps? {
        if crate::traversal::source::is_display_only(s) {
            continue;
        }
        if !found && *s == step {
            found = true;
            if let Some(before) = before {
                rewritten.push(before.to_string());
            }
            rewritten.push(format!("math(\"{new_expr}\")"));
        } else {
            rewritten.push(s.clone());
        }
    }
    found.then(|| format!("g.{}", rewritten.join(".")))
}

/// Names of the built-in `math()` functions close to `name` (edit distance at most 2, or one a
/// prefix of the other), closest first.
fn math_close_functions(
    name: &str,
) -> Vec<&'static crate::value::math_expr::registry::FunctionDef> {
    fn distance(a: &str, b: &str) -> usize {
        let b: Vec<char> = b.chars().collect();
        let mut row: Vec<usize> = (0..=b.len()).collect();
        for (i, ca) in a.chars().enumerate() {
            let mut diagonal = row[0];
            row[0] = i + 1;
            for (j, cb) in b.iter().enumerate() {
                let above = row[j + 1];
                row[j + 1] = (diagonal + usize::from(ca != *cb))
                    .min(row[j] + 1)
                    .min(above + 1);
                diagonal = above;
            }
        }
        row[b.len()]
    }
    let lower = name.to_ascii_lowercase();
    let mut close: Vec<(
        usize,
        &'static crate::value::math_expr::registry::FunctionDef,
    )> = crate::value::math_expr::registry::FUNCTIONS
        .iter()
        .map(|f| (distance(&lower, f.name), f))
        .filter(|(d, f)| {
            *d <= 2
                || (lower.len() >= 2 && (f.name.starts_with(&lower) || lower.starts_with(f.name)))
        })
        .collect();
    close.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.name.cmp(b.1.name)));
    close.into_iter().map(|(_, f)| f).collect()
}

/// What the `math()` equation language is, shared by every `math()` advice.
fn math_language() -> String {
    let functions: Vec<&str> = crate::value::math_expr::registry::FUNCTIONS
        .iter()
        .map(|f| f.name)
        .collect();
    format!(
        "math() evaluates an equation like TinkerPop does: numbers, the operators + - * / % and \
         ^ (power), parentheses, the functions {} (log is the natural logarithm), the constants \
         pi, e, π and φ, the current value _ and variables that name a key of the current map, a \
         side effect or a step label. The result is always a double.",
        functions.join(", ")
    )
}

/// Advice for [`TraverserError::MathExpression`], with examples rewritten from the failing query
/// (`steps`, outermost level) when its `math()` step is at that level.
fn math_expression_help(expr: &str, kind: &MathErrorKind, steps: Option<Vec<String>>) -> String {
    let steps = steps.as_deref();
    let language = math_language();
    match kind {
        MathErrorKind::Syntax => format!(
            "{language} Fix the equation at the marked position, for example \
             g.v().values(\"age\").math(\"(_ + 1) * 2\")."
        ),
        MathErrorKind::UnknownFunction { name } => {
            let close = math_close_functions(name);
            match close.first() {
                Some(best) => {
                    let fixed = math_replace_identifier(expr, name, best.name);
                    let example = math_rewrite_query(steps, expr, None, &fixed)
                        .unwrap_or_else(|| format!("g.v().values(\"age\").math(\"{fixed}\")"));
                    format!(
                        "'{name}' is not a math() function; did you mean {}? For example \
                         {example}. {language}",
                        close
                            .iter()
                            .map(|f| format!("{} ({})", f.name, f.doc))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                }
                None => format!("'{name}' is not a math() function. {language}"),
            }
        }
        MathErrorKind::UnknownVariable { name } if name == "value" => {
            let fixed = math_replace_identifier(expr, "value", "_");
            let example = math_rewrite_query(steps, expr, None, &fixed)
                .unwrap_or_else(|| format!("g.v().values(\"age\").math(\"{fixed}\")"));
            format!(
                "The current value is named _ in math(), as in TinkerPop; value is not a name for \
                 it. For example {example}. {language}"
            )
        }
        MathErrorKind::UnknownVariable { name } => {
            let label = format!("as(\"{name}\")");
            let example =
                math_rewrite_query(steps, expr, Some(&label), expr).unwrap_or_else(|| {
                    format!("g.v().values(\"age\").as(\"{name}\").math(\"{expr}\")")
                });
            let nested = math_replace_identifier(expr, name, &format!("_.{name}"));
            format!(
                "math() reads a variable other than _ from, in this order, a key of the current \
                 map (project(\"{name}\", ...), value_map(), element_map()), a side effect \
                 (g.with_side_effect(\"{name}\", 10), aggregate(\"{name}\")) or a step label \
                 (as(\"{name}\")), and '{name}' is none of these for this traverser. Label the \
                 value it should read, for example {example}, or declare it as a side effect, \
                 for example g.with_side_effect(\"{name}\", 10).v().values(\"age\").math(\"{expr}\"). \
                 To read a key of the current value itself, use the nested form _.{name} (a \
                 Graphersal extension), for example g.v().element_map().math(\"{nested}\")."
            )
        }
        MathErrorKind::BadPath { path } => format!(
            "Nested access such as {path} is a Graphersal extension of math(): after a variable, \
             .key or [\"key\"] reads a key of a map (value_map(), element_map(), project(), a \
             map-valued property) or a property of a vertex or edge, and [n] an element of a \
             list (a negative n counts from the end). The path leads to no value for this \
             traverser: check the key or index against the value, for example \
             g.v().element_map().limit(1), and keep only traversers that have it before math(), \
             for example g.v().has(\"age\").element_map().math(\"_.age * 2\")."
        ),
        MathErrorKind::NotANumber { path, actual } => {
            let example = if path == "_" {
                math_rewrite_query(steps, expr, Some("as_number(GType.DOUBLE)"), expr)
            } else {
                None
            }
            .unwrap_or_else(|| {
                format!(
                    "g.v().values(\"age\").as_string().as_number(GType.DOUBLE).math(\"{expr}\")"
                )
            });
            format!(
                "math() computes with numbers only, and {path} is a {actual}. Convert the value \
                 with as_number(GType.DOUBLE) first, for example {example}, or inside the by() \
                 that reads it, for example by(__.values(\"age\").as_number(GType.DOUBLE))."
            )
        }
        MathErrorKind::Null { path } => {
            let example = if path == "_" { expr } else { "_ + 1" };
            format!(
                "{path} is null, and math() computes with numbers only. Keep only traversers that \
                 have the value before math(), for example \
                 g.v().has(\"age\").math(\"{example}\").by(\"age\"), or replace a missing value \
                 with a default inside the by(), for example \
                 by(__.coalesce(__.values(\"age\"), __.constant(0)))."
            )
        }
        MathErrorKind::DivisionByZero => format!(
            "math() follows TinkerPop: a zero divisor of / or % (or cot(x) where \
             tan(x) is 0) is an error, not infinity. Keep only traversers with a non-zero divisor \
             before math(), for example g.v().project(\"a\", \"b\").by(\"age\").by(__.out().count())\
             .where(__.select(\"b\").is(P.neq(0))).math(\"a / b\"). The failing equation was \
             math(\"{expr}\")."
        ),
        MathErrorKind::Internal => format!(
            "This is an internal error of the math() engine, not of the equation math(\"{expr}\"); \
             please report it together with the equation."
        ),
    }
}

impl TraverserError {
    /// Builds a [`TraverserError::MathExpression`] for the token at byte `offset` of `expr`
    /// (`width` characters long).
    pub(crate) fn math_expression(
        expr: &str,
        offset: usize,
        width: usize,
        kind: MathErrorKind,
        message: String,
    ) -> TraverserError {
        let column = expr.get(..offset).map_or(offset, |s| s.chars().count()) + 1;
        TraverserError::MathExpression {
            expr: expr.to_string(),
            offset,
            column,
            width: width.max(1),
            kind,
            message,
        }
    }
}

/// Advice for [`TraverserError::MergeVertexUnresolved`].
fn merge_vertex_unresolved_help(direction: crate::value::Direction, reason: &str) -> String {
    let (key, token) = match direction {
        crate::value::Direction::In => ("Direction.IN", "inV"),
        crate::value::Direction::Out | crate::value::Direction::Both => ("Direction.OUT", "outV"),
    };
    let specific = if reason.contains("could not be resolved") && !reason.contains("option(") {
        format!(
            "Give \"{key}\" the id of an existing vertex (check it with g.v(id)), or create the \
             vertex first, for example g.merge_v(#{{\"T.id\": \"1\"}}). "
        )
    } else if reason.contains("matched") {
        format!(
            "The option(Merge.{token}, map) map is a vertex search that must find exactly one \
             vertex: name it by id, for example option(Merge.{token}, #{{\"T.id\": \"1\"}}), \
             or add properties until only one vertex matches. "
        )
    } else if reason.contains("option(") {
        format!(
            "\"{key}\": Merge.{token} is resolved from option(Merge.{token}, ..), which takes a \
             vertex search map such as #{{\"T.id\": \"1\"}} or a traversal yielding a vertex, \
             for example g.v(\"1\").as(\"a\").v(\"2\").as(\"b\").merge_e(#{{\"T.label\": \
             \"knows\", \"Direction.OUT\": Merge.outV, \"Direction.IN\": Merge.inV}})\
             .option(Merge.outV, __.select(\"a\")).option(Merge.inV, __.select(\"b\")). "
        )
    } else {
        String::new()
    };
    format!(
        "{specific}An edge merge_e() creates needs both vertices: give \"Direction.OUT\" and \
         \"Direction.IN\" an existing vertex id, for example g.merge_e(#{{\"T.label\": \"knows\", \
         \"Direction.OUT\": \"1\", \"Direction.IN\": \"2\"}}), in the merge() map or in \
         option(Merge.onCreate, ..), or use the placeholders Merge.outV/Merge.inV with \
         option(Merge.outV, __.select(\"a\")) / option(Merge.inV, __.select(\"b\"))."
    )
}

/// Advice for `add_e()` without the endpoints it needs.
/// `help()` of `tree("a")` meeting a side effect `a` that is not a tree.
fn tree_key_clash_help(reason: &str) -> String {
    format!(
        "{reason}.\n\
         tree(\"a\") adds every path to the tree stored under \"a\" and passes the traversers on, so \
         the key must be unused or already hold a tree (an earlier tree(\"a\")). aggregate()/store() \
         keep a list, with_side_effect(\"a\", Set.of()) a set and with_side_effect(\"a\", 0, Operator.sum) \
         a reduced value under their key.\n\
         Use another key for the tree, for example g.v().aggregate(\"a\").out().tree(\"t\").cap(\"t\"), \
         or read the existing bucket with cap(\"a\")."
    )
}

/// `help()` of `group("a")`/`groupCount("a")` meeting a side effect `a` it cannot add to.
fn group_key_clash_help(reason: &str) -> String {
    format!(
        "{reason}.\n\
         group(\"a\") and group_count(\"a\") add every traverser to the map stored under \"a\" and \
         pass the traversers on, so the key must be unused or filled only by group steps that \
         reduce a key the same way (two group_count(\"a\"), or group(\"a\") steps with the same kind \
         of value by()). aggregate()/store() keep a list, tree(\"a\") a tree and \
         with_side_effect(\"a\", ...) a seed under their key.\n\
         Use another key for the map, for example \
         g.v().aggregate(\"a\").group_count(\"m\").by(T.label).cap(\"m\"), or read both with \
         cap(\"a\", \"m\")."
    )
}

/// `help()` of `to_graph()` over a stream that is not made of edges.
fn to_graph_help(reason: &str) -> String {
    format!(
        "{reason}.\n\
         to_graph() builds a graph from edges: every edge is copied with both endpoint vertices \
         (ids, labels and properties included). Select edges first, for example \
         g.e(0).to_graph(), g.v(1).both_e().to_graph() or g.v(1).out_e().has_label(\"knows\").to_graph(). \
         subgraph(\"sg\").cap(\"sg\") is the long form of the same result."
    )
}

/// `help()` of `subgraph()` failing while it collects or writes its graph.
fn subgraph_help(reason: &str) -> String {
    format!(
        "{reason}.\n\
         subgraph(\"sg\") collects edges under the key \"sg\" and cap(\"sg\") returns them as a \
         graph, so the stream must be made of edges (select them with out_e()/in_e()/both_e(), for \
         example g.v(1).both_e().subgraph(\"sg\").cap(\"sg\")) and the key must be unused. To write into your own graph, declare it with \
         with_side_effect(\"sg\", target) where target is another graph (for example \
         GraphSource::empty() or an earlier to_graph() result), never the graph you traverse: \
         let target = g.e(0).to_graph(); g.with_side_effect(\"sg\", target).e().subgraph(\"sg\").to_list()."
    )
}

fn add_e_endpoint_help() -> String {
    "After a vertex, add_e(label) creates its edge from that vertex: to(..) names the in-vertex \
     (g.v(\"1\").add_e(\"knows\").to(\"2\")), from(..) the out-vertex \
     (g.v(\"2\").add_e(\"knows\").from(\"1\")), and neither makes a self-loop \
     (g.v(\"1\").add_e(\"self\")). As a start step add_e() has no incoming vertex, so it needs \
     both: g.add_e(\"knows\").from(\"1\").to(\"2\"). from()/to() take a vertex id or a step label \
     set with as(), for example g.v(\"1\").as(\"a\").v(\"2\").add_e(\"knows\").from(\"a\"). To \
     create the edge only when it does not exist yet, use mergeE, for example \
     g.merge_e(#{\"T.label\": \"knows\", \"Direction.OUT\": \"1\", \"Direction.IN\": \"2\"})."
        .to_string()
}

/// Advice for an invalid `property(map)` argument or map key.
fn property_map_help() -> String {
    "property(map) writes one property per map entry, for example \
     g.v(\"1\").property(#{\"name\": \"marko\", \"age\": 29}); null or #{} writes nothing. Keys \
     are plain property names: keys starting with \"T.\", \"Direction.\" or \"~\" are reserved. \
     To set the id or label of a new vertex, use property(T.id, v) / property(T.label, v) right \
     after add_v(), for example g.add_v(\"person\").property(T.id, \"p1\"); a property literally \
     named like a reserved key can still be written one at a time, for example \
     g.v(\"1\").property(\"T.label\", \"x\")."
        .to_string()
}

/// Advice for [`TraverserError::UnsupportedCardinality`].
fn unsupported_cardinality_help(step: &str, on_edge: bool) -> String {
    if on_edge && step == "merge_e" {
        "Edge properties have no cardinality: drop the Cardinality argument of option() and any \
         Cardinality.single(v) wrapper in the merge_e() maps, for example \
         g.merge_e(#{\"T.label\": \"knows\", \"Direction.OUT\": \"1\", \"Direction.IN\": \
         \"2\"}).option(Merge.onMatch, #{\"weight\": 0.5})."
            .to_string()
    } else if on_edge {
        "Edge properties have no cardinality: drop the Cardinality argument (and any \
         Cardinality.single(v) wrapper in a map), for example g.e(\"0\").property(\"weight\", 0.5) \
         or g.e(\"0\").property(#{\"weight\": 0.5})."
            .to_string()
    } else {
        "Graphersal stores one value per property key, so only Cardinality.single can be \
         written: it replaces the current value, for example \
         g.v(\"1\").property(Cardinality.single, \"age\", 30) (the same as \
         g.v(\"1\").property(\"age\", 30)). To keep several values, store them as one array \
         value: g.v(\"1\").property(\"tags\", [\"a\", \"b\"])."
            .to_string()
    }
}

/// Advice for [`TraverserError::TokenPropertyOutsideAdd`].
fn token_property_outside_add_help(token: &str) -> String {
    if token == "T.label" {
        "property(T.label, v) sets the label of the vertex add_v() is creating; write it right \
         after add_v() (other property() calls may come in between), for example \
         g.add_v().property(T.label, \"person\"), or pass the label to add_v(\"person\") directly. \
         An edge's label comes from add_e(label), for example g.v(\"1\").add_e(\"knows\").to(\"2\"). \
         The label of an existing element cannot be changed with property(); to store data \
         under the key \"label\", write a normal property: g.v(\"1\").property(\"label\", \"x\")."
            .to_string()
    } else {
        "property(T.id, v) sets the id of the element add_v()/add_e() is creating; write it right \
         after add_v()/add_e() (other property() calls may come in between), for example \
         g.add_v(\"person\").property(T.id, \"p1\"). The id of an existing element cannot be \
         changed; to store data on it, write a normal property, for example \
         g.v(\"1\").property(\"code\", 5)."
            .to_string()
    }
}

impl TraverserError {
    /// The steps before the failing step of the innermost failing level, as written, prefixed
    /// with `g.` for the outermost level and `__.` for a child traversal.
    fn failing_level_prefix(&self) -> Option<String> {
        let frames = self.step_trace();
        let frame = frames.last()?;
        let before: Vec<String> = match &frame.logical {
            Some(logical) => {
                let first = logical.positions.first().copied().unwrap_or(0);
                logical.steps.iter().take(first).cloned().collect()
            }
            None => frame.steps.iter().take(frame.position).cloned().collect(),
        };
        let start = if frames.len() <= 1 { "g." } else { "__." };
        Some(if before.is_empty() {
            start.to_string()
        } else {
            format!("{start}{}", before.join("."))
        })
    }

    /// Rendered steps of the outermost failing level: as the user wrote it when the optimizer
    /// rewrote it, otherwise as executed.
    fn outermost_steps(&self) -> Option<Vec<String>> {
        let frame = self.step_trace().into_iter().next()?;
        Some(match &frame.logical {
            Some(logical) => logical.steps.clone(),
            None => frame.steps.clone(),
        })
    }

    /// Returns the outermost failing level as the user wrote it, before optimization.
    ///
    /// `None` when provenance was not tracked, or when the optimizer left the query unchanged
    /// and the executed plan already is the user's query.
    pub fn query(&self) -> Option<String> {
        match self {
            TraverserError::StepFailed { frame, .. } => frame
                .as_ref()
                .and_then(|frame| frame.logical.as_ref())
                .map(|logical| logical.steps.join(".")),
            _ => None,
        }
    }

    /// Collects the physical plan frames of nested step failures, outermost level first.
    pub fn step_trace(&self) -> Vec<&StepFrame> {
        let mut frames = Vec::new();
        let mut current = self;
        while let TraverserError::StepFailed { frame, source, .. } = current {
            if let Some(frame) = frame {
                frames.push(&**frame);
            }
            current = source;
        }
        frames
    }

    /// Returns the innermost error of a nested step failure chain (also through the
    /// [`TraverserError::Spelled`] wrapper).
    pub fn root_cause(&self) -> &TraverserError {
        let mut current = self;
        while let TraverserError::StepFailed { source, .. }
        | TraverserError::Spelled { source, .. } = current
        {
            current = source;
        }
        current
    }

    fn root_cause_mut(&mut self) -> &mut TraverserError {
        match self {
            TraverserError::StepFailed { source, .. } | TraverserError::Spelled { source, .. } => {
                source.root_cause_mut()
            }
            other => other,
        }
    }

    /// Where in the optimized plan the error happened: the id of the failing step (the same
    /// numbering as [`Metrics::id`](crate::Metrics::id), `<step>.<child>.<step>...`) and the
    /// chain of steps from the top level down to it. A plan-time error (a rejected modulator, an
    /// invalid constant argument, an undeclared step label) and a denied step are located at
    /// the step they are about, before anything runs. `None` for an error that has no step (an
    /// invalid or locked option, a script error).
    ///
    /// Ids are static positions in the plan `.profile()` shows (fused steps under their real
    /// names), so the location joins a partial profile of an [`Execution`](crate::Execution)
    /// by id.
    pub fn step_location(&self) -> Option<StepLocation> {
        let mut segments: Vec<String> = Vec::new();
        let mut step_path = Vec::new();
        let mut current = self;
        while let TraverserError::StepFailed {
            step_name,
            step_index,
            child_index,
            source,
            ..
        } = current
        {
            if let Some(index) = step_index {
                if let Some(child) = child_index
                    && !segments.is_empty()
                {
                    segments.push(child.to_string());
                }
                segments.push(index.to_string());
                step_path.push(StepPathEntry {
                    id: segments.join("."),
                    name: step_name.clone(),
                });
            }
            current = source;
        }
        let last = step_path.last()?;
        Some(StepLocation {
            step_id: last.id.clone(),
            step_path,
        })
    }
}

/// The location of a failing step in the optimized plan; see
/// [`TraverserError::step_location`].
///
/// `#[non_exhaustive]`: a source span of the written query is a planned, additive field.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StepLocation {
    /// Id of the failing step, numbered like [`Metrics::id`](crate::Metrics::id) (`"3.1.0"`).
    pub step_id: String,
    /// The steps from the top level down to the failing one (the last entry).
    pub step_path: Vec<StepPathEntry>,
}

/// One step of a [`StepLocation::step_path`]. `#[non_exhaustive]`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StepPathEntry {
    /// The step's id (`"3"`, `"3.1.0"`).
    pub id: String,
    /// The step's name in the optimized plan, the same text as [`Metrics::name`](crate::Metrics::name).
    pub name: String,
}

impl TraverserError {
    pub(crate) fn cast_exception<S: GraphStorage>(
        expected: &[&'static str],
        value: &TraverserValue<S>,
    ) -> TraverserError {
        TraverserError::Value(ValueError::CastException {
            expected: expected.join(" or "),
            actual: value.type_name().to_string(),
            value: None,
            origin: None,
        })
    }

    pub(crate) fn cast_exception_str(expected: &[&'static str], actual: String) -> TraverserError {
        TraverserError::Value(ValueError::CastException {
            expected: expected.join(" or "),
            actual,
            value: None,
            origin: None,
        })
    }

    /// Builds a cast error carrying the offending value and the graph element it came from.
    pub(crate) fn cast_exception_at(
        expected: &[&'static str],
        actual: String,
        value: Option<String>,
        origin: Option<ValueOrigin>,
    ) -> TraverserError {
        TraverserError::Value(ValueError::CastException {
            expected: expected.join(" or "),
            actual,
            value,
            origin: origin.map(Box::new),
        })
    }

    /// Builds a cast error whose expected type is computed rather than a fixed literal.
    pub(crate) fn cast_exception_target(
        expected: impl Into<String>,
        actual: String,
        value: Option<String>,
        origin: Option<ValueOrigin>,
    ) -> TraverserError {
        TraverserError::Value(ValueError::CastException {
            expected: expected.into(),
            actual,
            value,
            origin: origin.map(Box::new),
        })
    }

    /// Builds the error of a label step (`add_label`, `drop_label`, `set_label`) that met a
    /// value of the wrong kind.
    pub(crate) fn label_step_element_kind<S: GraphStorage>(
        step: &'static str,
        value: &TraverserValue<S>,
    ) -> TraverserError {
        TraverserError::Value(ValueError::LabelStepElementKind {
            step,
            expected: if step == "set_label" {
                "an edge"
            } else {
                "a vertex"
            },
            actual: value.kind_name(),
        })
    }

    /// Builds the error of a `Scope.local` step that met a list element it cannot take.
    pub(crate) fn local_element_type(
        step: &'static str,
        accepts: &'static str,
        index: usize,
        actual: String,
    ) -> TraverserError {
        TraverserError::Value(ValueError::LocalElementType {
            step,
            accepts,
            index,
            actual,
        })
    }

    /// Builds the error for a conversion target the engine cannot produce yet.
    pub(crate) fn unsupported_cast_target(
        target: impl Into<String>,
        reason: &'static str,
    ) -> TraverserError {
        TraverserError::Value(ValueError::UnsupportedCastTarget {
            target: target.into(),
            reason,
        })
    }

    #[allow(dead_code)]
    pub(crate) fn property_not_found(key: impl Into<String>) -> TraverserError {
        TraverserError::Value(ValueError::PropertyNotFound {
            key: key.into(),
            element_type: "element",
        })
    }

    pub(crate) fn property_not_found_on_element(
        key: impl Into<String>,
        element_type: &'static str,
    ) -> TraverserError {
        TraverserError::Value(ValueError::PropertyNotFound {
            key: key.into(),
            element_type,
        })
    }

    #[allow(dead_code)]
    pub(crate) fn wrong_query(reason: impl Into<String>) -> TraverserError {
        TraverserError::QueryExecution {
            query: "<query>".to_string(),
            reason: reason.into(),
        }
    }

    pub(crate) fn not_implemented(feature: &'static str) -> TraverserError {
        TraverserError::NotImplemented { feature }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The `path` help (a label that is not set on the traverser's path) names the `Pop` forms; a
    /// named-field variant, so built by hand here.
    #[test]
    fn path_label_help_names_the_pop_forms() {
        let help = ValueError::PropertyNotFound {
            key: "x".to_string(),
            element_type: "path",
        }
        .help()
        .expect("help");
        assert!(help.contains("select(Pop.all, \"x\")"), "{help}");
        assert!(
            help.contains("Pop.first") && help.contains("Pop.mixed"),
            "{help}"
        );
    }

    /// `OperatorFailed` is a named-field variant, so it is built by hand here; the queries that
    /// reach it (`sack(Operator)`) are asserted in `tests/all/error_diagnostics_tests.rs`.
    #[test]
    fn operator_failed_message_and_help() {
        let incompatible = ValueError::OperatorFailed {
            operator: "sum",
            kind: OperatorFailure::IncompatibleOperands { expected: "number" },
            left: "3 (int64)".into(),
            right: "\"a\" (string)".into(),
        };
        assert_eq!(
            incompatible.to_string(),
            "Operator 'sum' cannot combine 3 (int64) with \"a\" (string): expected number"
        );
        let help = incompatible.help().expect("help");
        for needle in [
            "as_number()",
            "as_bool()",
            "min and max",
            "sumLong takes int64",
            "addAll",
        ] {
            assert!(help.contains(needle), "{needle} missing from: {help}");
        }
        let overflow = ValueError::OperatorFailed {
            operator: "sumLong",
            kind: OperatorFailure::Overflow,
            left: "9223372036854775807 (int64)".into(),
            right: "1 (int64)".into(),
        };
        assert!(overflow.to_string().contains("overflowed"));
        assert!(
            overflow
                .help()
                .expect("help")
                .contains("does not widen or wrap")
        );
        let zero = ValueError::OperatorFailed {
            operator: "div",
            kind: OperatorFailure::DivisionByZero,
            left: "1 (int64)".into(),
            right: "0 (int64)".into(),
        };
        assert!(zero.to_string().contains("division by zero"));
    }
    /// `SackArenaExhausted` needs 2^32 distinct sack values, so it is built by hand.
    #[test]
    fn sack_arena_exhausted_help_names_the_update_step() {
        let help = TraverserError::SackArenaExhausted { capacity: 1 }
            .help()
            .expect("help");
        assert!(
            help.contains(
                "g.with_sack(0).v().limit(1000).out().sack(Operator.sum).by(__.constant(1)).sack()"
            ),
            "{help}"
        );
    }

    use std::error::Error;

    /// Every public error enum stays within `clippy::result_large_err`'s 128-byte threshold, so
    /// a `Result<T, E>` carrying one stays cheap to move on the success path. Rarely-read
    /// diagnostic payloads (`ValueOrigin`, `StepFrame`) are boxed to keep it that way; a new
    /// variant or field that crosses the bound should box its payload the same way.
    #[test]
    fn test_error_enums_stay_small() {
        use std::mem::size_of;
        const LIMIT: usize = 128;
        let sizes = [
            ("ValueError", size_of::<ValueError>()),
            ("GraphError", size_of::<GraphError>()),
            ("IOError", size_of::<IOError>()),
            ("ScriptError", size_of::<ScriptError>()),
            ("SchemaError", size_of::<SchemaError>()),
            ("TraverserError", size_of::<TraverserError>()),
        ];
        for (name, size) in sizes {
            assert!(
                size <= LIMIT,
                "{name} is {size} bytes, above the {LIMIT}-byte bound"
            );
        }
    }

    #[test]
    fn test_value_error_display_and_help() {
        let err = ValueError::CastException {
            expected: "string".to_string(),
            actual: "number".to_string(),
            value: None,
            origin: None,
        };
        assert_eq!(
            err.to_string(),
            "Cast exception: expected type [string], got type 'number'"
        );
        assert!(err.help().is_some());
        assert!(err.help().unwrap().contains("Check the value type"));

        let err_prop = ValueError::PropertyNotFound {
            key: "age".to_string(),
            element_type: "vertex",
        };
        assert_eq!(
            err_prop.to_string(),
            "Property 'age' not found on element type 'vertex'"
        );
        assert!(err_prop.help().unwrap().contains(".has() filter"));
    }

    #[test]
    fn test_graph_error_display_and_help() {
        let err = GraphError::VertexNotFound {
            id: "v1".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Vertex with ID 'v1' was not found in the graph"
        );
        assert!(
            err.help()
                .unwrap()
                .contains("Verify that the vertex ID exists")
        );
    }

    #[test]
    fn test_io_error_source_chain_and_help() {
        let io_source = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err = IOError::FileRead {
            path: "/tmp/test.graphml".to_string(),
            source: io_source,
        };
        assert!(
            err.to_string()
                .contains("Failed to read file '/tmp/test.graphml'")
        );
        assert!(err.source().is_some());
        assert!(
            err.help()
                .unwrap()
                .contains("Check if the file path is correct")
        );
    }

    #[test]
    fn test_schema_error_display_and_help() {
        let err = SchemaError::UnknownVertexLabel {
            label: "User".to_string(),
            allowed: vec!["Person".to_string(), "Software".to_string()],
        };
        assert_eq!(
            err.to_string(),
            "Unknown vertex label 'User' is not declared in the closed schema"
        );
        let help = err.help().unwrap();
        assert!(help.contains("[Person, Software]"), "{help}");
        assert!(help.contains("patch_schema"), "{help}");

        let err_edge = SchemaError::UnknownEdgeLabel {
            label: "manages".to_string(),
            allowed: vec!["knows".to_string(), "created".to_string()],
        };
        assert_eq!(
            err_edge.to_string(),
            "Unknown edge label 'manages' is not declared in the closed schema"
        );
        assert!(err_edge.help().unwrap().contains("[knows, created]"));

        let err_topo = SchemaError::InvalidEdgeTopology {
            source_label: "Person".to_string(),
            edge_label: "created".to_string(),
            target_label: "Person".to_string(),
            allowed: vec!["(:Person)-[:created]->(:Software)".to_string()],
        };
        assert_eq!(
            err_topo.to_string(),
            "Disallowed edge connection: '(:Person)-[:created]->(:Person)' is not defined in schema"
        );
        let help = err_topo.help().unwrap();
        assert!(
            help.contains("[(:Person)-[:created]->(:Software)]"),
            "{help}"
        );
        assert!(help.contains("connections"), "{help}");

        let err_prop = SchemaError::UndeclaredProperty {
            element_type: "vertex",
            label: "Person".to_string(),
            property_name: "nickname".to_string(),
        };
        assert_eq!(
            err_prop.to_string(),
            "Undeclared property 'nickname' on vertex 'Person' is not declared and not admitted by the schema"
        );
        let help = err_prop.help().unwrap();
        assert!(help.contains("\"additionalProperties\": true"), "{help}");
        assert!(!help.contains("Partial"), "{help}");

        let err_req = SchemaError::MissingRequiredProperty {
            element_type: "vertex",
            label: "Person".to_string(),
            property_name: "name".to_string(),
        };
        assert_eq!(
            err_req.to_string(),
            "Missing required property 'name' on vertex 'Person'"
        );
        let req_help = err_req.help().unwrap();
        assert!(
            req_help.starts_with(
                "Provide a value for 'name' or remove it from the label's \"required\""
            )
        );
        assert!(
            req_help.contains("\"default\" is an annotation only"),
            "{req_help}"
        );
        assert!(req_help.contains("add_property_fold"), "{req_help}");

        let err_mismatch = SchemaError::TypeMismatch {
            element_type: "vertex",
            label: "Person".to_string(),
            property_name: "age".to_string(),
            expected_type: "int64".to_string(),
            actual_type: "string".to_string(),
        };
        assert_eq!(
            err_mismatch.to_string(),
            "Type mismatch on vertex 'Person.age': expected int64, got string"
        );
        assert_eq!(
            err_mismatch.help(),
            Some(
                "Convert value to expected type 'int64' before inserting.\n\
                 In a query, convert the values with values(\"age\").as_number(GType.LONG).\n\
                 Find every offending value with values(\"age\").is(typeOf(GType.STRING))."
                    .to_string()
            )
        );

        let err_null = SchemaError::TypeMismatch {
            element_type: "vertex",
            label: "Person".to_string(),
            property_name: "age".to_string(),
            expected_type: "int64".to_string(),
            actual_type: "null".to_string(),
        };
        assert!(
            err_null
                .help()
                .unwrap()
                .starts_with("'age' does not admit null")
        );

        let err_constraint = SchemaError::ConstraintViolation {
            label: "Person".to_string(),
            property_name: "age".to_string(),
            constraint_rule: "value >= 0".to_string(),
            actual_value: "-5".to_string(),
        };
        assert_eq!(
            err_constraint.to_string(),
            "Constraint violation on 'Person.age': value >= 0 (actual: -5)"
        );
        assert_eq!(
            err_constraint.help(),
            Some("Ensure value complies with validation constraint: value >= 0.".to_string())
        );

        let err_def = SchemaError::InvalidSchema {
            path: "/vertices/person/schema/properties/age".to_string(),
            reason: "unknown keyword 'minimun'".to_string(),
            hint: "The supported keywords are: ...".to_string(),
        };
        assert_eq!(
            err_def.to_string(),
            "Invalid schema at /vertices/person/schema/properties/age: unknown keyword 'minimun'"
        );
        let help = err_def.help().unwrap();
        assert!(
            help.starts_with("The supported keywords are: ..."),
            "{help}"
        );
        assert!(help.contains("JSON Schema 2020-12"), "{help}");
    }
    #[test]
    fn test_script_error_display_and_help() {
        let err = ScriptError::UnsupportedStep {
            step_name: "unknown_step".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Unsupported step 'unknown_step' in script context"
        );
        assert!(err.help().unwrap().contains("Verify step name"));
    }

    #[test]
    fn test_traverser_error_propagation_and_cause_chain() {
        let val_err = ValueError::PathNotDefined;
        let trav_err: TraverserError = val_err.into();

        assert_eq!(
            trav_err.to_string(),
            "Path is not defined or initialized for traverser"
        );
        assert_eq!(trav_err.help(), ValueError::PathNotDefined.help());
        assert!(
            trav_err
                .help()
                .unwrap_or_default()
                .contains("g.v(\"1\").as(\"a\").out().select(\"a\")")
        );

        let step_failed = TraverserError::StepFailed {
            spelling: crate::traversal::Spelling::Snake,
            step_name: "out".to_string(),
            step_index: None,
            child_index: None,
            frame: None,
            element_id: Some("v1".to_string()),
            source: Box::new(trav_err),
        };

        assert!(
            step_failed
                .to_string()
                .contains("Step 'out' execution failed")
        );
        assert!(step_failed.source().is_some());
        assert_eq!(step_failed.help(), ValueError::PathNotDefined.help());
    }

    #[test]
    fn test_step_frame_marks_every_originating_step() {
        // `v().has_label("person").count()` executes as a single fused scan, so the failure
        // traces back to all three steps the user wrote.
        let frame = StepFrame::new(vec!["v(labels: \"person\", count_only)".to_string()], 0)
            .with_logical(LogicalFrame {
                steps: vec![
                    "v()".to_string(),
                    "has_label(\"person\")".to_string(),
                    "count()".to_string(),
                ],
                positions: vec![0, 1, 2],
            });

        let rendered = frame.render_logical().expect("the plans differ");
        let (plan, caret) = rendered.split_once('\n').expect("a caret line is rendered");
        assert_eq!(plan, "v().has_label(\"person\").count()");
        assert_eq!(
            caret,
            "^".repeat(plan.chars().count()),
            "a fully folded level is underlined as one run"
        );

        let partial =
            StepFrame::new(vec!["a".to_string(), "b".to_string()], 1).with_logical(LogicalFrame {
                steps: vec!["a()".to_string(), "b()".to_string(), "c()".to_string()],
                positions: vec![2],
            });
        assert_eq!(
            partial.render_logical().expect("the plans differ"),
            "a().b().c()\n        ^^^"
        );
    }

    #[test]
    fn test_step_frame_hides_an_unchanged_plan() {
        let frame = StepFrame::new(vec!["v()".to_string(), "max()".to_string()], 1).with_logical(
            LogicalFrame {
                steps: vec!["v()".to_string(), "max()".to_string()],
                positions: vec![1],
            },
        );
        assert_eq!(
            frame.render_logical(),
            None,
            "an untouched level must not be printed twice"
        );
    }

    #[test]
    fn test_result_ext_trait() {
        let res: Result<(), ValueError> = Err(ValueError::PathNotDefined);
        let step_res = res.with_step("values");
        assert!(step_res.is_err());
        if let Err(boxed) = step_res {
            if let TraverserError::StepFailed {
                step_name,
                element_id,
                source,
                ..
            } = *boxed
            {
                assert_eq!(step_name, "values");
                assert_eq!(element_id, None);
                assert!(source.to_string().contains("Path is not defined"));
            } else {
                panic!("Expected StepFailed error variant");
            }
        } else {
            panic!("Expected StepFailed error variant");
        }

        let res_elem: Result<(), ValueError> = Err(ValueError::PathNotDefined);
        let step_elem_res = res_elem.with_step_element("out", "v1");
        assert!(step_elem_res.is_err());
        if let Err(boxed) = step_elem_res {
            if let TraverserError::StepFailed {
                step_name,
                element_id,
                source,
                ..
            } = *boxed
            {
                assert_eq!(step_name, "out");
                assert_eq!(element_id, Some("v1".to_string()));
                assert!(source.to_string().contains("Path is not defined"));
            } else {
                panic!("Expected StepFailed error variant");
            }
        } else {
            panic!("Expected StepFailed error variant");
        }
    }

    /// D5/D6 regression: `TraverserResult<T>`'s `Err` side must stay a single boxed pointer.
    ///
    /// `TraverserError` itself is large (its fattest variants wrap `SchemaError`, up to 128 bytes
    /// on a 64-bit target), so an unboxed `Result<T, TraverserError>` costs at least that much to
    /// move on every call, even along the `Ok` path. Boxing the error keeps that cost to one
    /// pointer. The bound is `<=`, not `==`, so it doesn't need updating for unrelated,
    /// pointer-width-independent changes; it only fails if someone defeats the boxing (e.g. by
    /// adding a fat field directly to a hot-path `Ok` type, or by accidentally un-boxing the
    /// error again).
    #[test]
    fn traverser_result_err_side_stays_a_single_pointer() {
        assert!(
            std::mem::size_of::<TraverserError>() > 24,
            "this test assumes TraverserError is large enough that boxing it is worthwhile; \
             got {} bytes",
            std::mem::size_of::<TraverserError>()
        );
        assert!(
            std::mem::size_of::<TraverserResult<()>>() <= 24,
            "TraverserResult<()> grew to {} bytes; Box<TraverserError> should keep it small \
             regardless of TraverserError's own size",
            std::mem::size_of::<TraverserResult<()>>()
        );
    }

    // Help-wording tests that need a hand-built error value. Named-field error variants are
    // `#[non_exhaustive]`, so only code inside this crate can construct them; the integration
    // tests in `tests/all/error_diagnostics_tests.rs` drive errors through real queries instead.
    mod help_wording {
        use super::super::*;
        use crate::prelude::*;

        /// An incompatible operand pair is repaired by converting one side, so the help says so.
        #[test]
        fn an_invalid_type_operation_points_at_the_coercion_steps() {
            let err = ValueError::InvalidTypeOperation {
                op: "+",
                type_a: "string",
                type_b: "int64",
            };
            let report = format_diagnostic(&err);
            assert!(
                report.contains(
                    "Ensure operand types are compatible for operation, or convert one side first with .as_string(), .as_bool() or .as_number(GType.LONG)."
                ),
                "the help must name the coercion steps in: {report}"
            );
        }

        /// Compiles `pattern`, which must fail, and returns the rendered diagnostic.
        fn glob_report(pattern: &str) -> String {
            match crate::value::glob_path::GlobPattern::compile(pattern) {
                Err(err) => format_diagnostic(&TraverserError::from(err)),
                Ok(_) => panic!("'{pattern}' should not compile"),
            }
        }

        #[test]
        fn invalid_glob_pattern_display_names_pattern_position_and_reason() {
            let err = ValueError::InvalidGlobPattern {
                pattern: "a**b".to_string(),
                position: 1,
                reason: crate::value::glob_path::reason::DOUBLE_STAR_IN_SEGMENT.to_string(),
            };
            assert_eq!(
                err.to_string(),
                "Invalid glob pattern 'a**b' at position 1: '**' must be a whole segment"
            );
            let help = err.help().unwrap_or_default();
            assert!(
                help.starts_with(
                    "'**' spans whole levels, so it must stand alone between slashes. Write \
                     glob_path(\"a*/**/*b\") instead, or plain glob_path(\"**\") to match every \
                     level below the start vertex. A literal '*' is written '\\*'."
                ),
                "unexpected help: {help}"
            );
            assert!(help.contains("for example glob_path(\"**/src/*.{rs,toml}\")."));
        }

        #[test]
        fn invalid_glob_pattern_help_rewrites_misplaced_double_stars() {
            assert!(glob_report("a**").contains("Write glob_path(\"a*/**\") instead"));
            assert!(glob_report("**b").contains("Write glob_path(\"**/*b\") instead"));
            assert!(
                glob_report("src/a**b/c").contains("Write glob_path(\"src/a*/**/*b/c\") instead")
            );
        }

        #[test]
        fn invalid_glob_pattern_help_splits_a_slash_in_alternatives() {
            let report = glob_report("{src/a,lib/b}");
            assert!(
                report.contains("at position 4: alternatives '{..}' cannot contain '/'"),
                "{report}"
            );
            assert!(
                report.contains(
                    "Split the alternative into two queries, for example glob_path(\"src/a\") and \
                     glob_path(\"lib/b\") instead of glob_path(\"{src/a,lib/b}\"), or use '**' to \
                     span levels, for example glob_path(\"**/{a,b}\")."
                ),
                "{report}"
            );
        }

        #[test]
        fn invalid_glob_pattern_help_explains_reserved_dot_segments() {
            let report = glob_report("docs/..");
            assert!(
                report.contains("'.' and '..' are reserved as whole segments"),
                "{report}"
            );
            assert!(
                report.contains(
                    "To walk back up use .in() or repeat(__.in()) before the step, for example \
                     g.v(\"x\").in().glob_path(\"docs/*\")."
                ),
                "{report}"
            );
        }

        #[test]
        fn invalid_glob_pattern_help_splits_too_many_segments() {
            let report = glob_report(&vec!["a"; 64].join("/"));
            assert!(
                report.contains("at position 126: the pattern has more than 63 segments"),
                "{report}"
            );
            assert!(
                report.contains(
                    "Split the walk into two consecutive steps, each matching below the vertices \
                     the previous one emits, for example glob_path(\"a/b/c\").glob_path(\"d/e/f\")"
                ),
                "{report}"
            );
        }

        #[test]
        fn invalid_glob_pattern_help_closes_classes_and_alternatives() {
            let class = glob_report("file[0-9.txt");
            assert!(
                class.contains("at position 4: unclosed character class '['"),
                "{class}"
            );
            assert!(
                class.contains(
                    "Close the character class with ']' in the same segment, for example \
                     glob_path(\"file[0-9].txt\"); match a literal '[' with '\\['."
                ),
                "{class}"
            );
            let alternatives = glob_report("*.{rs,toml");
            assert!(
                alternatives.contains("at position 2: unclosed alternatives '{'"),
                "{alternatives}"
            );
            assert!(
                alternatives.contains(
                    "Close the alternatives with '}', for example glob_path(\"*.{rs,toml}\"); \
                     match a literal '{' with '\\{'."
                ),
                "{alternatives}"
            );
        }

        #[test]
        fn invalid_script_parameter_help_names_both_binding_forms() {
            let err = ScriptError::InvalidParameter {
                parameter: "g".to_string(),
                message: "'g' is reserved by the script scope for the Gremlin DSL".to_string(),
            };
            let rendered = format_diagnostic(&err);

            assert!(
                rendered.contains("Invalid script parameter 'g'"),
                "the message must name the offending parameter:\n{rendered}"
            );
            assert!(
                rendered.contains("`Order`") && rendered.contains("token class"),
                "the help must describe the token class globals:\n{rendered}"
            );
            assert!(
                rendered.contains("eval_with_params"),
                "the help must name the named-parameter entry point:\n{rendered}"
            );
            assert!(
                rendered.contains("eval_with_positional_params"),
                "the help must name the positional entry point:\n{rendered}"
            );
            assert!(
                rendered.contains("g.v().has_label(label).to_list()"),
                "the help must carry a runnable named-parameter example:\n{rendered}"
            );
            assert!(
                rendered.contains("g.v().has_label($1).to_list()"),
                "the help must carry a runnable positional example:\n{rendered}"
            );
            assert!(
                rendered.contains("1-based"),
                "the help must state that placeholders start at $1:\n{rendered}"
            );
        }

        #[test]
        fn mark_unavailable_help_covers_a_storage_without_a_journal() {
            let err = GraphError::mark_unavailable("this storage keeps no journal");
            let rendered = format_diagnostic(&err);
            assert!(
                rendered.contains("Cannot set a mark: this storage keeps no journal"),
                "{rendered}"
            );
            assert!(
                rendered.contains("A storage that keeps no journal (a custom GraphStorage"),
                "{rendered}"
            );
            assert!(rendered.contains("g.mark(\"before-import\")"), "{rendered}");
        }

        #[test]
        fn unsupported_graph_file_help_names_both_formats_and_their_extensions() {
            let err = IOError::UnsupportedFormat {
                path: "graph.csv".to_string(),
            };
            let rendered = format_diagnostic(&err);

            assert!(
                rendered.contains("Unsupported graph file format: 'graph.csv'"),
                "the message must name the offending file:\n{rendered}"
            );
            assert!(
                rendered.contains("GraphSON") && rendered.contains("GraphML"),
                "the help must name both supported graph formats:\n{rendered}"
            );
            for ext in [".json", ".jsonl", ".graphson", ".xml", ".graphml"] {
                assert!(
                    rendered.contains(ext),
                    "the help must name the extension {ext}:\n{rendered}"
                );
            }
            assert!(
                rendered.contains("GraphSource::file(\"graph.json\")"),
                "the help must carry a runnable example:\n{rendered}"
            );
        }

        #[test]
        fn graphson_errors_have_help() {
            for err in [
                IOError::GraphSONParse {
                    line: 2,
                    message: "expected ',' or '}' in an object at byte 7".to_string(),
                },
                IOError::UnsupportedGraphSON {
                    line: 1,
                    reason: "this is typed GraphSON 1.0 (@class)".to_string(),
                },
                IOError::InputTooLarge { line: 1, limit: 64 },
            ] {
                let rendered = format_diagnostic(&err);
                assert!(rendered.contains("line"), "{rendered}");
                assert!(
                    err.help()
                        .is_some_and(|h| h.contains("GraphSON") || h.contains("line form")),
                    "{rendered}"
                );
            }
            let too_large = IOError::InputTooLarge { line: 1, limit: 64 };
            assert!(
                too_large
                    .help()
                    .is_some_and(|h| h.contains("with_max_text_bytes")),
                "{too_large}"
            );
        }

        #[test]
        fn path_arena_exhaustion_help_names_limit_and_simple_path() {
            let err = TraverserError::PathArenaExhausted { capacity: 4 };
            assert!(err.to_string().contains("4 path positions"), "{err}");
            let help = err.help().expect("help");
            assert!(help.contains("g.v().out().limit(1000).path()"), "{help}");
            assert!(help.contains("g.v(\"1\").out().path()"), "{help}");
            assert!(help.contains("remove the path consumer"), "{help}");
            assert!(
                help.contains("g.v().both().both().simple_path().path()"),
                "{help}"
            );
            assert!(
                help.contains("g.v().repeat(__.both().simple_path()).times(2).path()"),
                "{help}"
            );
            assert!(
                help.contains("g.v().local(__.out().limit(2)).path()"),
                "{help}"
            );
        }

        #[test]
        fn timeout_help_without_a_query_uses_an_example() {
            let err = TraverserError::Timeout {
                limit_ms: 250,
                elapsed_ms: 251,
            };
            assert_eq!(
                err.to_string(),
                "Traversal exceeded evaluationTimeout of 250 ms (ran 251 ms)"
            );
            let help = err.help().expect("help");
            assert!(
                help.contains("g.v().limit(1000).out().out().count()"),
                "{help}"
            );
            assert!(
                help.contains("g.with(\"evaluationTimeout\", 500).v().out().out().count()"),
                "{help}"
            );
        }

        #[test]
        fn timeout_help_without_a_repeat_does_not_mention_loops() {
            let err = TraverserError::Timeout {
                limit_ms: 250,
                elapsed_ms: 251,
            };
            assert!(!err.help().expect("help").contains("repeat()"));
        }

        #[test]
        fn bulk_expansion_limit_help_explains_why_and_what_to_do() {
            let err = TraverserError::BulkExpansionLimit {
                step: "fold".to_string(),
                requested: 2_505_037_961,
                limit: 100_000_000,
            };
            assert_eq!(
                err.to_string(),
                "Step 'fold' would have to materialize 2505037961 values, more than the limit of \
                 100000000 (bulk.max_expansion)"
            );
            let help = err.help().expect("help");
            assert!(help.contains("record with a multiplicity"), "{help}");
            assert!(
                help.contains("2505037961 values, more than the limit of 100000000"),
                "{help}"
            );
            for advice in ["count()", "group_count()", "dedup()", "limit(n)"] {
                assert!(help.contains(advice), "{advice}: {help}");
            }
            assert!(
                help.contains(
                    "g.with(\"bulk.max_expansion\", 2505037961).v().repeat(__.out()).times(8)"
                ),
                "{help}"
            );
            // The same advice reaches the user when the step failed inside a query.
            let wrapped = TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: "fold".to_string(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: None,
                source: Box::new(err),
            };
            assert!(wrapped.help().expect("help").contains("bulk.max_expansion"));
        }

        #[test]
        fn bulk_overflow_help_names_the_step_and_the_remedy() {
            let err = TraverserError::BulkOverflow {
                step: "count".to_string(),
            };
            assert!(err.to_string().contains("step 'count'"));
            let help = err.help().expect("help");
            assert!(help.contains("9223372036854775807"), "{help}");
            assert!(help.contains("Narrow the start set"), "{help}");
            assert!(help.contains("times(n)"), "{help}");
        }

        #[test]
        fn bulk_option_help_shows_a_runnable_example() {
            for key in ["bulk.merge", "bulk.one", "bulk.max_expansion"] {
                let err = TraverserError::InvalidOption {
                    key: key.to_string(),
                    reason: "bad".to_string(),
                };
                assert!(
                    err.help()
                        .expect("help")
                        .contains(&format!("g.with(\"{key}\""))
                );
            }
        }

        #[test]
        fn resource_limit_help_names_the_option_and_shows_an_example() {
            let err = TraverserError::ResourceLimitExceeded {
                limit: "traversal.max_traversers".to_string(),
                max: Some(1000),
                observed: Some(1500),
            };
            assert_eq!(
                err.to_string(),
                "Resource limit 'traversal.max_traversers' exceeded (limit 1000, reached 1500)"
            );
            let help = err.help().expect("help");
            assert!(
                help.contains("g.with(\"traversal.max_traversers\", 2000).v().out().out().count()"),
                "{help}"
            );
            assert!(help.contains("ExecutionPolicy::with_locked"), "{help}");
        }

        #[test]
        fn resource_limit_help_for_a_script_limit_names_the_builder_and_the_flag() {
            let err = TraverserError::ResourceLimitExceeded {
                limit: "script.max_operations".to_string(),
                max: Some(10_000_000),
                observed: None,
            };
            assert_eq!(
                err.to_string(),
                "Resource limit 'script.max_operations' exceeded (limit 10000000)"
            );
            let help = err.help().expect("help");
            assert!(
                help.contains("ScriptLimits::default().with_max_operations(20000000)"),
                "{help}"
            );
            assert!(help.contains("ScriptLimits::unlimited()"), "{help}");
            assert!(
                help.contains("graphersal --max-operations 20000000 -e 'g.v().count().next()'"),
                "{help}"
            );
        }

        #[test]
        fn invalid_traverser_cap_help_shows_the_option() {
            let err = TraverserError::InvalidOption {
                key: "traversal.max_traversers".to_string(),
                reason: "expected a positive integer number of values, got 0".to_string(),
            };
            let help = err.help().expect("help");
            assert!(
                help.contains(
                    "g.with(\"traversal.max_traversers\", 50000000).v().out().out().count()"
                ),
                "{help}"
            );
        }

        #[test]
        fn repeat_limit_help_keeps_the_loop_name() {
            let err = TraverserError::RepeatLimitExceeded {
                max_loops: 10_000,
                loop_name: Some("walk".to_string()),
                body: "__.out()".to_string(),
            };
            assert_eq!(
                err.to_string(),
                "repeat() loop 'walk' exceeded the loop limit of 10000 iterations"
            );
            let help = err.help().expect("help");
            assert!(
                help.contains("repeat(\"walk\", __.out()).times(3)"),
                "{help}"
            );
            assert!(
                help.contains("repeat(\"walk\", __.out().simple_path())"),
                "{help}"
            );
            assert!(
                help.contains(
                    "g.with(\"repeat.max_loops\", 20000).v().repeat(\"walk\", __.out())."
                ),
                "{help}"
            );
            // Without the failing query, the glob_path() alternative starts from every vertex.
            assert!(
                help.ends_with(
                    "\nOn a tree-shaped graph (directories, org charts, categories), walk the \
                     levels below a vertex with glob_path() instead: it follows outgoing edges \
                     along a pattern, prunes branches that cannot match and stops on cycles \
                     without a loop limit, for example g.v().glob_path(\"**/*.rs\").by(\"name\"), \
                     or g.v().glob_path(\"**\").by(\"name\") for every level below; bound how \
                     deep it walks with max_depth, for example \
                     g.v().glob_path(\"**\", #{max_depth: 3}).by(\"name\")."
                ),
                "{help}"
            );
        }

        #[test]
        fn glob_path_max_depth_help_without_a_query_uses_an_example() {
            let err = TraverserError::InvalidOption {
                key: GLOB_PATH_MAX_DEPTH.to_string(),
                reason: "must be at least 1, got 0".to_string(),
            };
            assert_eq!(
                err.to_string(),
                "Invalid value for option 'glob_path.max_depth': must be at least 1, got 0"
            );
            assert_eq!(
                err.help().expect("help"),
                "max_depth is the deepest level below the start vertex that glob_path() visits: \
                 the start vertex is level 0 and its children are level 1, so max_depth is an \
                 integer from 1 to 4294967295. Leave it out to walk without a bound. For example \
                 g.v(\"root\").glob_path(\"**/*.rs\", #{max_depth: 3}).by(\"name\")."
            );
        }

        #[test]
        fn glob_path_option_rewrites_keep_other_steps() {
            let steps = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::<Vec<_>>();
            // A pattern literal that contains a quote and a brace is not mistaken for options.
            assert_eq!(
                split_glob_path_step(r#"glob_path("a\", {b", {max_depth: 0}).by("name")"#),
                Some((r#"glob_path("a\", {b""#, r#", {max_depth: 0}).by("name")"#))
            );
            assert_eq!(split_glob_path_step("out()"), None);
            assert_eq!(
                glob_path_step_with_valid_max_depth(
                    r#"glob_path("**", {max_depth: -7}).by("name")"#
                ),
                Some(r#"glob_path("**", {max_depth: 1}).by("name")"#.to_string())
            );
            assert_eq!(
                glob_path_step_with_valid_max_depth(r#"glob_path("**", {max_depth: 7})"#),
                None
            );
            // Only a '**' walk without max_depth is bounded.
            assert_eq!(
                glob_path_query_with_max_depth(&steps(&[
                    "v()",
                    "glob_path(\"src/*\").by(\"name\")"
                ])),
                None
            );
            assert_eq!(
                glob_path_query_with_max_depth(&steps(&[
                    "v()",
                    "glob_path(\"**\", {max_depth: 9})"
                ])),
                None
            );
            assert_eq!(
                glob_path_query_with_max_depth(&steps(&[
                    "v()",
                    "glob_path(\"**/*.rs\").by(\"name\")",
                    "count()"
                ])),
                Some(
                    "v().glob_path(\"**/*.rs\", #{max_depth: 3}).by(\"name\").count()".to_string()
                )
            );
        }

        #[test]
        fn glob_path_start_keeps_the_steps_before_the_loop() {
            let steps = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::<Vec<_>>();
            assert_eq!(
                glob_path_start(&steps(&[
                    "v(\"root\")",
                    "has_label(\"directory\")",
                    "repeat(__.out())"
                ])),
                Some("v(\"root\").has_label(\"directory\")".to_string())
            );
            assert_eq!(
                glob_path_start(&steps(&["v(\"root\")", "emit()", "repeat(__.out())"])),
                Some("v(\"root\")".to_string())
            );
            // The loop is nested in another step: no top-level position to rewrite.
            assert_eq!(
                glob_path_start(&steps(&["v(\"root\")", "local(__.repeat(__.out()))"])),
                None
            );
            assert_eq!(glob_path_start(&steps(&["repeat(__.out())"])), None);
        }

        /// Step 3 of the type system: storing a vertex as a property value is rejected, and the help
        /// shows how to store its id instead, built from the failing property name.
        #[test]
        fn invalid_property_value_help_stores_the_id_instead() {
            let graph = GraphSource::tinkerpop_modern();
            let err = graph
                .write()
                .traversal_mut()
                .v("1")
                .property_by("friend", __::out(None))
                .next()
                .expect_err("a vertex must not be stored as a property value");
            let root = err.root_cause();
            assert_eq!(
                root.to_string(),
                "Property 'friend' cannot hold a vertex: vertices and edges are not property values"
            );
            assert_eq!(
                root.help().expect("help"),
                "Store the vertex's id instead of the vertex itself, e.g. \
                 property(\"friend\", __.out(\"knows\").id()), and look the vertex up again with g.v(id)."
            );

            let edge_err = GraphError::InvalidPropertyValue {
                property_name: "via".to_string(),
                kind: "edge",
            };
            assert_eq!(
                edge_err.to_string(),
                "Property 'via' cannot hold an edge: vertices and edges are not property values"
            );
            assert_eq!(
                edge_err.help().expect("help"),
                "Store the edge's id instead of the edge itself, e.g. \
                 property(\"via\", __.out_e(\"knows\").id()), and look the edge up again with g.e(id)."
            );
        }

        /// A failed coercion on write names the declared type, the offending value and the reason, and
        /// the help shows the accepted form.
        #[test]
        fn coercion_failed_help_names_the_accepted_form() {
            let coercion_failed =
                |declared_type: &str, actual_value: &str, reason: &'static str| {
                    SchemaError::CoercionFailed {
                        element_type: "vertex",
                        label: "person".to_string(),
                        property_name: "uid".to_string(),
                        declared_type: declared_type.to_string(),
                        actual_value: actual_value.into(),
                        reason,
                    }
                };

            let uuid = coercion_failed(
                "uuid",
                "\"abc\"",
                "not a canonical UUID (8-4-4-4-12 lowercase hex)",
            );
            assert_eq!(
                uuid.to_string(),
                "Cannot store \"abc\" in vertex 'person.uid' declared as uuid: not a canonical UUID \
                 (8-4-4-4-12 lowercase hex)"
            );
            assert_eq!(
                uuid.help().expect("help"),
                "UUIDs are written as 8-4-4-4-12 lowercase hex, e.g. \
                 `550e8400-e29b-41d4-a716-446655440000`."
            );

            let float = coercion_failed(
                "float64",
                "9007199254740993",
                "integer cannot be represented exactly as float64",
            );
            assert_eq!(
                float.help().expect("help"),
                "The integer is too large to be represented exactly as float64; store it in an int64 \
                 field."
            );
        }

        /// A declared `uuid` given a non-string value: the help names the explicit conversion in both
        /// the Rust and the Rhai spelling, since only a canonical string converts on write.
        #[test]
        fn type_mismatch_on_uuid_help_names_the_cast_in_both_spellings() {
            let err = SchemaError::TypeMismatch {
                element_type: "vertex",
                label: "person".to_string(),
                property_name: "uid".to_string(),
                expected_type: "uuid".to_string(),
                actual_type: "int64".to_string(),
            };
            assert_eq!(
                err.help().expect("help"),
                "Convert value to expected type 'uuid' before inserting.\n\
                 In a query, convert the values with values(\"uid\").cast(GType.UUID).\n\
                 Only a canonical UUID string is converted to a uuid on write; convert a string value \
                 explicitly with .cast(GType.UUID).\n\
                 Find every offending value with values(\"uid\").is(typeOf(GType.LONG))."
            );

            // A mismatch on any other declared type does not mention it.
            let other = SchemaError::TypeMismatch {
                element_type: "vertex",
                label: "person".to_string(),
                property_name: "name".to_string(),
                expected_type: "string".to_string(),
                actual_type: "uuid".to_string(),
            };
            assert!(
                !other
                    .help()
                    .expect("help")
                    .contains("Only a canonical UUID string")
            );
        }

        #[test]
        fn ambiguous_container_import_help_names_both_ways_out() {
            let err = IOError::AmbiguousContainerImport {
                key: "tags".to_string(),
                declared: "union<string|array<int64>>".to_string(),
            };
            let rendered = format_diagnostic(&err);
            assert!(
                rendered.contains(
                    "Property 'tags' is declared as union<string|array<int64>>, a union of an \
                     array/object and a text type"
                ),
                "the message must name the property and its type:\n{rendered}"
            );
            let help = err.help().expect("help");
            assert!(
                help.contains("Declare 'tags' either as an array/object"),
                "{help}"
            );
            assert!(help.contains("before importing"), "{help}");
        }

        #[test]
        fn invalid_json_value_help_shows_the_expected_text() {
            let err = IOError::InvalidJsonValue {
                key: "config".to_string(),
                declared: "object".to_string(),
                reason: "expected ',' or '}' in an object at byte 7".to_string(),
            };
            let rendered = format_diagnostic(&err);
            assert!(
                rendered.contains(
                    "Property 'config' is declared as object, but its GraphML value is not valid \
                     JSON: expected ',' or '}' in an object at byte 7"
                ),
                "{rendered}"
            );
            let help = err.help().expect("help");
            assert!(help.contains(r#"{"cpu":2}"#), "{help}");
            assert!(help.contains("declare 'config' as `string`"), "{help}");
        }

        #[test]
        fn non_finite_float_export_help_names_the_repairing_steps() {
            let err = IOError::NonFiniteFloat {
                key: "w".to_string(),
                value: "NaN".to_string(),
            };
            let rendered = format_diagnostic(&err);

            assert!(
                rendered.contains("Property 'w' holds the non-finite float NaN"),
                "the message must name the property and the value:\n{rendered}"
            );
            assert!(
                rendered.contains(".property(\"w\", 0.0)")
                    && rendered.contains(".properties(\"w\").drop()")
                    && rendered.contains(".remove_property(\"w\")"),
                "the help must carry runnable repairs for the offending key:\n{rendered}"
            );
        }
    }

    // Cause-chain and help-coverage tests moved from `tests/all/error_handling_tests.rs`: they build
    // errors by hand, and named-field error variants are `#[non_exhaustive]`, so only code inside
    // this crate can construct them.
    mod constructed_errors {
        use super::super::*;

        /// Asserts that a rendered diagnostic carries `expected_help`, allowing for the indentation
        /// `format_diagnostic` adds to every line after the first.
        fn assert_help_rendered(formatted: &str, expected_help: &str) {
            for (index, line) in expected_help.lines().enumerate() {
                let expected_line = if index == 0 {
                    format!("Help: {line}")
                } else {
                    format!("      {line}")
                };
                assert!(
                    formatted.contains(&expected_line),
                    "missing help line `{expected_line}` in: {formatted}"
                );
            }
        }

        #[test]
        fn test_cause_chain_propagation() {
            use std::error::Error;

            let inner_graph_err = GraphError::VertexNotFound {
                id: "v_999".to_string(),
            };
            let step_err = TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: "out".to_string(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: Some("v_1".to_string()),
                source: Box::new(TraverserError::Graph(inner_graph_err)),
            };

            assert!(step_err.source().is_some());
            let cause = step_err.source().unwrap();
            assert!(cause.to_string().contains("v_999"));

            let formatted = format_diagnostic(&step_err);
            assert!(formatted.starts_with("Error: Step 'out' execution failed"));
            assert!(
                formatted.contains("Caused by: Vertex with ID 'v_999' was not found in the graph")
            );
            assert!(formatted.contains(
                "Help: Verify that the vertex ID exists in the graph before referencing it."
            ));
        }

        #[test]
        fn test_diagnostic_error_help_coverage() {
            let err_v_not_found = GraphError::VertexNotFound {
                id: "100".to_string(),
            };
            assert!(err_v_not_found.help().is_some());
            assert!(!err_v_not_found.help().unwrap().is_empty());

            let err_prop_not_found = ValueError::PropertyNotFound {
                key: "age".to_string(),
                element_type: "vertex",
            };
            assert!(err_prop_not_found.help().is_some());
            assert!(!err_prop_not_found.help().unwrap().is_empty());

            let err_cast = ValueError::CastException {
                expected: "number".to_string(),
                actual: "string".to_string(),
                value: None,
                origin: None,
            };
            assert!(err_cast.help().is_some());
            assert!(!err_cast.help().unwrap().is_empty());

            let err_missing_attr = IOError::MissingAttribute {
                element: "node".to_string(),
                attribute: "id".to_string(),
            };
            assert!(err_missing_attr.help().is_some());
            assert!(!err_missing_attr.help().unwrap().is_empty());

            let err_invalid_attr = IOError::InvalidAttributeValue {
                key: "weight".to_string(),
                attribute: "value".to_string(),
                value: "not_a_number".to_string(),
                expected_type: "float".to_string(),
            };
            assert!(err_invalid_attr.help().is_some());
            assert!(!err_invalid_attr.help().unwrap().is_empty());
        }

        #[test]
        fn test_schema_error_diagnostics_and_formatting() {
            let variants: Vec<(SchemaError, &str, &str)> = vec![
                (
                    SchemaError::UnknownVertexLabel {
                        label: "Alien".to_string(),
                        allowed: vec!["Human".to_string(), "Robot".to_string()],
                    },
                    "Unknown vertex label 'Alien' is not declared in the closed schema",
                    "A closed schema admits only declared vertex labels: use one of [Human, Robot]",
                ),
                (
                    SchemaError::UnknownEdgeLabel {
                        label: "teleports_to".to_string(),
                        allowed: vec!["walks_to".to_string(), "flies_to".to_string()],
                    },
                    "Unknown edge label 'teleports_to' is not declared in the closed schema",
                    "A closed schema admits only declared edge labels: use one of [walks_to, flies_to]",
                ),
                (
                    SchemaError::InvalidEdgeTopology {
                        source_label: "Human".to_string(),
                        edge_label: "operates".to_string(),
                        target_label: "Planet".to_string(),
                        allowed: vec!["(:Human)-[:operates]->(:Vehicle)".to_string()],
                    },
                    "Disallowed edge connection: '(:Human)-[:operates]->(:Planet)' is not defined in schema",
                    "A closed schema admits an edge only between the labels of a declared connection",
                ),
                (
                    SchemaError::UndeclaredProperty {
                        element_type: "vertex",
                        label: "Human".to_string(),
                        property_name: "mana".to_string(),
                    },
                    "Undeclared property 'mana' on vertex 'Human' is not declared and not admitted by the schema",
                    "Declare 'mana' in the label's \"properties\"",
                ),
                (
                    SchemaError::MissingRequiredProperty {
                        element_type: "edge",
                        label: "created".to_string(),
                        property_name: "weight".to_string(),
                    },
                    "Missing required property 'weight' on edge 'created'",
                    "Provide a value for 'weight' or remove it from the label's \"required\"",
                ),
                (
                    SchemaError::TypeMismatch {
                        element_type: "vertex",
                        label: "Robot".to_string(),
                        property_name: "serial_no".to_string(),
                        expected_type: "int64".to_string(),
                        actual_type: "string".to_string(),
                    },
                    "Type mismatch on vertex 'Robot.serial_no': expected int64, got string",
                    "Convert value to expected type 'int64' before inserting.\n\
                     In a query, convert the values with values(\"serial_no\").as_number(GType.LONG).\n\
                     Find every offending value with values(\"serial_no\").is(typeOf(GType.STRING)).",
                ),
                (
                    SchemaError::ConstraintViolation {
                        label: "Robot".to_string(),
                        property_name: "battery".to_string(),
                        constraint_rule: "value <= 100".to_string(),
                        actual_value: "120".to_string(),
                    },
                    "Constraint violation on 'Robot.battery': value <= 100 (actual: 120)",
                    "Ensure value complies with validation constraint: value <= 100.",
                ),
                (
                    SchemaError::InvalidSchema {
                        path: "/mdoe".to_string(),
                        reason: "unknown key 'mdoe'".to_string(),
                        hint: "The envelope keys are $schema, meta, mode, vertices and edges."
                            .to_string(),
                    },
                    "Invalid schema at /mdoe: unknown key 'mdoe'",
                    "The envelope keys are $schema, meta, mode, vertices and edges.",
                ),
            ];

            for (schema_err, expected_msg, expected_help) in variants {
                assert_eq!(schema_err.to_string(), expected_msg);
                // A help may continue past the expected first line (the missing-property help
                // appends the add_property_fold advice).
                let help = schema_err.help().expect("schema errors carry help");
                assert!(help.starts_with(expected_help), "{help}");

                let formatted = format_diagnostic(&schema_err);
                assert!(
                    formatted.contains(&format!("Error: {}", expected_msg)),
                    "format_diagnostic missing main error message in: {}",
                    formatted
                );
                assert_help_rendered(&formatted, expected_help);

                // Verify conversion into TraverserError
                let trav_err: TraverserError = schema_err.into();
                assert_eq!(trav_err.to_string(), expected_msg);
                assert!(trav_err.help().expect("help").starts_with(expected_help));
                let formatted_trav = format_diagnostic(&trav_err);
                assert!(
                    formatted_trav.contains(&format!("Error: {}", expected_msg)),
                    "format_diagnostic on TraverserError missing error message in: {}",
                    formatted_trav
                );
                assert_help_rendered(&formatted_trav, expected_help);
            }
        }

        #[test]
        fn test_step_failure_context() {
            let inner_err = TraverserError::Value(ValueError::PropertyNotFound {
                key: "non_existent".to_string(),
                element_type: "vertex",
            });

            let step_err = TraverserError::StepFailed {
                spelling: crate::traversal::Spelling::Snake,
                step_name: "values".to_string(),
                step_index: None,
                child_index: None,
                frame: None,
                element_id: Some("vertex_42".to_string()),
                source: Box::new(inner_err),
            };

            if let TraverserError::StepFailed {
                step_name,
                element_id,
                source,
                ..
            } = &step_err
            {
                assert_eq!(step_name, "values");
                assert_eq!(element_id.as_deref(), Some("vertex_42"));
                assert!(source.help().is_some());
            } else {
                panic!("Expected StepFailed variant");
            }
        }
    }
}