overgraph 0.8.0

An absurdly fast embedded graph database. Pure Rust, sub-microsecond reads.
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
# OverGraph API Reference

Complete reference for OverGraph's public API across **Rust**, **Node.js**, and **Python**. Every method, parameter, type, and return value is documented.

> **Conventions used in this document:**
>
> - Parameters marked **required** must always be provided. Parameters marked **optional** may be omitted and will use documented defaults.
> - `u32` / `u64` / `i64` / `f32` / `f64` refer to fixed-width numeric types. In Node.js these map to `number`; in Python to `int` or `float`.
> - All timestamps are **milliseconds since Unix epoch** (January 1, 1970 00:00:00 UTC).
> - All IDs (`node_id`, `edge_id`) are unsigned 64-bit integers. In Node.js they are represented as `number` (safe up to 2^53 - 1). In Python they are `int` (unlimited precision).
> - Code examples show all three languages. Rust examples assume `use overgraph::*;` is in scope.

---

## Table of Contents

- [Installation](#installation)
- [Database Lifecycle](#database-lifecycle)
  - [open](#open)
  - [close](#close)
  - [close_fast](#close_fast)
  - [stats](#stats)
- [Configuration](#configuration)
  - [DbOptions](#dboptions)
  - [WalSyncMode](#walsyncmode)
  - [DenseVectorConfig](#densevectorconfig)
- [Data Model](#data-model)
  - [Node Records](#node-records)
  - [Edge Records](#edge-records)
  - [PropValue](#propvalue)
  - [IntoNodeLabels](#intonodelabels-rust-only)
  - [Direction](#direction)
  - [NodeLabelFilter / LabelMatchMode](#nodelabelfilter--labelmatchmode)
- [Catalog APIs](#catalog-apis)
  - [ensure_node_label / ensure_edge_label](#ensure_node_label--ensure_edge_label)
  - [get_node_label_id / get_edge_label_id](#get_node_label_id--get_edge_label_id)
  - [get_node_label / get_edge_label](#get_node_label--get_edge_label)
  - [list_node_labels / list_edge_labels](#list_node_labels--list_edge_labels)
- [Node Operations](#node-operations)
  - [upsert_node](#upsert_node)
  - [get_node](#get_node)
  - [get_node_by_key](#get_node_by_key)
  - [add_node_label / remove_node_label](#add_node_label--remove_node_label)
  - [delete_node](#delete_node)
  - [batch_upsert_nodes](#batch_upsert_nodes)
  - [get_nodes](#get_nodes)
  - [get_nodes_by_keys](#get_nodes_by_keys)
- [Edge Operations](#edge-operations)
  - [upsert_edge](#upsert_edge)
  - [get_edge](#get_edge)
  - [get_edge_by_triple](#get_edge_by_triple)
  - [delete_edge](#delete_edge)
  - [invalidate_edge](#invalidate_edge)
  - [batch_upsert_edges](#batch_upsert_edges)
  - [get_edges](#get_edges)
- [Atomic Operations](#atomic-operations)
  - [graph_patch](#graph_patch)
  - [write transactions](#write-transactions)
- [Label and Edge-Label Queries](#label-and-edge-label-queries)
  - [nodes_by_labels](#nodes_by_labels)
  - [edges_by_label](#edges_by_label)
  - [get_nodes_by_labels](#get_nodes_by_labels)
  - [get_edges_by_label](#get_edges_by_label)
  - [count_nodes_by_labels](#count_nodes_by_labels)
  - [count_edges_by_label](#count_edges_by_label)
- [Property Index Management](#property-index-management)
  - [ensure_node_property_index](#ensure_node_property_index)
  - [drop_node_property_index](#drop_node_property_index)
  - [list_node_property_indexes](#list_node_property_indexes)
  - [NodePropertyIndexInfo](#nodepropertyindexinfo)
  - [ensure_edge_property_index](#ensure_edge_property_index)
  - [drop_edge_property_index](#drop_edge_property_index)
  - [list_edge_property_indexes](#list_edge_property_indexes)
  - [EdgePropertyIndexInfo](#edgepropertyindexinfo)
  - [PropertyRangeBound](#propertyrangebound)
  - [PropertyRangeCursor](#propertyrangecursor)
  - [PropertyRangePageRequest](#propertyrangepagerequest-rust-only)
  - [PropertyRangePageResult](#propertyrangepageresult)
- [Property & Time Queries](#property--time-queries)
  - [find_nodes](#find_nodes)
  - [find_nodes_range](#find_nodes_range)
  - [find_nodes_by_time_range](#find_nodes_by_time_range)
- [Queries](#queries)
  - [Node Queries](#node-queries)
    - [query_node_ids](#query_node_ids)
    - [query_nodes](#query_nodes)
    - [explain_node_query](#explain_node_query)
  - [Direct Edge Queries](#direct-edge-queries)
    - [query_edge_ids](#query_edge_ids)
    - [query_edges](#query_edges)
    - [explain_edge_query](#explain_edge_query)
  - [Graph Pattern Queries](#graph-pattern-queries)
    - [query_pattern](#query_pattern)
    - [explain_pattern_query](#explain_pattern_query)
  - [Query Request Types and Plans](#query-request-types-and-plans)
    - [NodeQuery](#nodequery)
    - [NodeFilter / QueryNodeFilter](#nodefilter--querynodefilter)
    - [EdgeQuery](#edgequery)
    - [EdgeFilter / QueryEdgeFilter](#edgefilter--queryedgefilter)
    - [GraphPatternQuery](#graphpatternquery)
    - [QueryPlan](#queryplan)
    - [Validation notes](#validation-notes)
- [Pagination](#pagination)
  - [nodes_by_labels_paged](#nodes_by_labels_paged)
  - [edges_by_label_paged](#edges_by_label_paged)
  - [get_nodes_by_labels_paged](#get_nodes_by_labels_paged)
  - [get_edges_by_label_paged](#get_edges_by_label_paged)
  - [find_nodes_paged](#find_nodes_paged)
  - [find_nodes_range_paged](#find_nodes_range_paged)
  - [find_nodes_by_time_range_paged](#find_nodes_by_time_range_paged)
- [Traversal](#traversal)
  - [neighbors](#neighbors)
  - [neighbors_paged](#neighbors_paged)
  - [neighbors_batch](#neighbors_batch)
  - [top_k_neighbors](#top_k_neighbors)
  - [traverse](#traverse)
  - [extract_subgraph](#extract_subgraph)
  - [shortest_path](#shortest_path)
  - [all_shortest_paths](#all_shortest_paths)
  - [is_connected](#is_connected)
- [Degree & Weight Aggregation](#degree--weight-aggregation)
  - [degree](#degree)
  - [degrees](#degrees)
  - [sum_edge_weights](#sum_edge_weights)
  - [avg_edge_weight](#avg_edge_weight)
- [Graph Analytics](#graph-analytics)
  - [connected_components](#connected_components)
  - [component_of](#component_of)
  - [personalized_pagerank](#personalized_pagerank)
  - [export_adjacency](#export_adjacency)
- [Vector Search](#vector-search)
  - [vector_search](#vector_search)
- [Retention & Pruning](#retention--pruning)
  - [prune](#prune)
  - [set_prune_policy](#set_prune_policy)
  - [remove_prune_policy](#remove_prune_policy)
  - [list_prune_policies](#list_prune_policies)
- [Maintenance](#maintenance)
  - [sync](#sync)
  - [flush](#flush)
  - [compact](#compact)
  - [compact_with_progress](#compact_with_progress)
  - [ingest_mode](#ingest_mode)
  - [end_ingest](#end_ingest)
  - [scrub](#scrub)
- [Introspection](#introspection)
  - [node_count](#node_count)
  - [edge_count](#edge_count)
  - [next_node_id](#next_node_id)
  - [next_edge_id](#next_edge_id)
  - [segment_count](#segment_count)
  - [segment_tombstone_node_count](#segment_tombstone_node_count)
  - [segment_tombstone_edge_count](#segment_tombstone_edge_count)
  - [path](#path)
  - [manifest](#manifest)
  - [manifest::load_manifest_readonly](#manifestload_manifest_readonly-rust-only)
- [Binary Batch Ingestion](#binary-batch-ingestion)
  - [batch_upsert_nodes_binary](#batch_upsert_nodes_binary)
  - [batch_upsert_edges_binary](#batch_upsert_edges_binary)
- [Error Handling](#error-handling)
- [Async API](#async-api)

---

## Installation

**Rust** - add to `Cargo.toml`:
```toml
[dependencies]
overgraph = "0.7"
```

**Node.js**:
```bash
npm install overgraph
```

**Python**:
```bash
pip install overgraph
```

Prebuilt binaries are published for Linux (x86_64, aarch64), macOS (x86_64, Apple Silicon), and Windows (x86_64). If no prebuilt binary exists for your platform, install a Rust toolchain and the package will compile from source.

---

## Database Lifecycle

### open

Opens an existing database or creates a new one. A database is a self-contained directory on disk.

**Rust**
```rust
let mut db = DatabaseEngine::open(Path::new("./my-graph"), &DbOptions::default())?;
```

**Node.js**
```javascript
const db = OverGraph.open('./my-graph', { /* options */ });
```

**Python**
```python
db = OverGraph.open("./my-graph", **options)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| path | `&Path` | `string` | `str` | Yes | — | Directory path for the database. Created if it doesn't exist (when `create_if_missing` is true). Must be a valid filesystem path. |
| options | `&DbOptions` | `object` | `**kwargs` | No | See [DbOptions](#dboptions) | Database configuration. See the full options reference below. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<DatabaseEngine, EngineError>` | `OverGraph` | `OverGraph` |

A new database instance. On failure, raises/returns an error if the path is inaccessible, the manifest is corrupt, or WAL replay fails.

#### Behavior

- If the directory doesn't exist and `create_if_missing` is true (the default), the directory is created.
- If the directory contains an existing database, OverGraph loads the manifest, opens all segments, and replays WAL generations to recover in-flight state.
- Configuration values (`wal_sync_mode`, `dense_vector`, etc.) are persisted in the manifest on first open. Subsequent opens use the persisted configuration; the values you pass are only used for the initial creation.
- Opening the same directory from multiple processes simultaneously is **not supported** and may cause data corruption.

#### Example

```rust
// Rust - open with custom options
let opts = DbOptions {
    wal_sync_mode: WalSyncMode::GroupCommit {
        interval_ms: 50,
        soft_trigger_bytes: 2 * 1024 * 1024,
        hard_cap_bytes: 16 * 1024 * 1024,
    },
    edge_uniqueness: true,
    dense_vector: Some(DenseVectorConfig {
        dimension: 384,
        metric: DenseMetric::Cosine,
        hnsw: HnswConfig::default(),
    }),
    ..Default::default()
};
let mut db = DatabaseEngine::open(Path::new("./my-graph"), &opts)?;
```

```javascript
// Node.js - open with custom options
const db = OverGraph.open('./my-graph', {
  walSyncMode: 'group-commit',
  groupCommitIntervalMs: 50,
  edgeUniqueness: true,
  denseVector: { dimension: 384, metric: 'cosine' },
  compactAfterNFlushes: 4,
});
```

```python
# Python - open with custom options
db = OverGraph.open(
    "./my-graph",
    wal_sync_mode="group_commit",
    group_commit_interval_ms=50,
    edge_uniqueness=True,
    dense_vector_dimension=384,
    dense_vector_metric="cosine",
    compact_after_n_flushes=4,
)
```

---

### close

Shuts down the database cleanly.

**Rust**
```rust
db.close()?;
```

**Node.js**
```javascript
db.close();            // sync, waits for compaction
db.close({ force: true }); // sync, cancels compaction
await db.closeAsync(); // async
```

**Python**
```python
db.close()           # waits for compaction
db.close(force=True) # cancels compaction
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| force | Use `close_fast()` instead | `boolean` | `bool` | No | `false` | If `true`, cancels any in-progress background compaction instead of waiting for it to finish. Pending WAL data is still synced. |

#### Behavior

**Normal close** (`force=false`):
1. Freezes the active memtable.
2. Flushes all pending immutable memtables to segments.
3. Waits for any in-progress background compaction to finish.
4. Writes the final manifest.
5. After close, no immutable memtables or retained WAL generations remain.

**Fast close** (`force=true` / `close_fast()` in Rust):
1. Cancels in-progress background compaction (safe because no state is modified until the atomic swap).
2. Syncs the active WAL.
3. Persists the manifest with retained WAL generations (so WAL replay recovers state on next open).

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<(), EngineError>` | `void` / `Promise<void>` | `None` |

#### Context Manager / Destructor

**Python** supports context manager syntax:
```python
with OverGraph.open("./my-graph") as db:
    # Also accepts multiple labels: ["User", "Admin"]
    db.upsert_node("User", "alice")
# db.close() called automatically on exit
```

**Node.js** has no built-in equivalent; call `close()` or `closeAsync()` explicitly in a `finally` block.

---

### close_fast

Rust-only fast close. This is the same behavior exposed by `close({ force: true })` in Node.js and `close(force=True)` in Python.

```rust
db.close_fast()?;
```

It cancels any in-progress background compaction, syncs the active WAL, and persists a manifest that retains the WAL generations needed for replay on the next open.

---

### stats

Returns a read-only snapshot of current database statistics.

**Rust**
```rust
let s = db.stats()?;
println!("segments: {}, WAL bytes: {}", s.segment_count, s.pending_wal_bytes);
```

**Node.js**
```javascript
const s = db.stats();
console.log(`segments: ${s.segmentCount}, WAL bytes: ${s.pendingWalBytes}`);
```

**Python**
```python
s = db.stats()
print(f"segments: {s.segment_count}, WAL bytes: {s.pending_wal_bytes}")
```

#### Parameters

None.

#### Returns: DbStats

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| pending_wal_bytes | `usize` | `number` | `int` | Bytes buffered in the WAL not yet fsynced to disk. |
| segment_count | `usize` | `number` | `int` | Number of immutable segments on disk. |
| node_tombstone_count | `usize` | `number` | `int` | Soft-deleted nodes in the active memtable (reclaimed at compaction). |
| edge_tombstone_count | `usize` | `number` | `int` | Soft-deleted edges in the active memtable. |
| last_compaction_ms | `Option<i64>` | `number \| null` | `int \| None` | Unix timestamp (ms) of the last completed compaction, or null if none. |
| wal_sync_mode | `String` | `string` | `str` | `"immediate"` or `"group_commit"`. |
| active_memtable_bytes | `usize` | `number` | `int` | Estimated byte size of the active (writable) memtable. |
| immutable_memtable_bytes | `usize` | `number` | `int` | Estimated byte size of all sealed memtables waiting to flush. |
| immutable_memtable_count | `usize` | `number` | `int` | Count of sealed memtables waiting to flush. |
| pending_flush_count | `usize` | `number` | `int` | Flush operations currently in flight. |
| active_wal_generation_id | `u64` | `number` | `int` | Generation ID of the WAL file currently being written. |
| oldest_retained_wal_generation_id | `u64` | `number` | `int` | Oldest WAL generation kept on disk (needed for crash recovery). |

---

## Configuration

### DbOptions

Options passed to [`open()`](#open). All fields are optional with sensible defaults.

| Option | Rust type | Node.js key | Python kwarg | Default | Description |
|--------|-----------|-------------|--------------|---------|-------------|
| create_if_missing | `bool` | `createIfMissing` | `create_if_missing` | `true` | Create the database directory if it doesn't exist. If `false` and the directory is missing, `open()` returns an error. |
| wal_sync_mode | `WalSyncMode` | `walSyncMode` | `wal_sync_mode` | `GroupCommit` | Controls WAL durability. See [WalSyncMode](#walsyncmode). |
| group_commit_interval_ms | — (part of enum) | `groupCommitIntervalMs` | `group_commit_interval_ms` | `50` | Milliseconds between group-commit fsyncs. Only applies when `wal_sync_mode` is `group_commit`. |
| memtable_flush_threshold | `usize` | `memtableFlushThreshold` | `memtable_flush_threshold` | `134217728` (128 MB) | When the active memtable exceeds this size in bytes, it is sealed and queued for flush to a segment. |
| memtable_hard_cap_bytes | `usize` | `memtableHardCapBytes` | `memtable_hard_cap_bytes` | `536870912` (512 MB) | Writes block when the active memtable exceeds this size and the flush queue is full. Prevents unbounded memory growth under heavy write load. Set to `0` to disable. |
| max_immutable_memtables | `usize` | `maxImmutableMemtables` | `max_immutable_memtables` | `4` | Maximum number of sealed memtables allowed before the flush thread must drain one. Controls memory usage under write bursts. |
| edge_uniqueness | `bool` | `edgeUniqueness` | `edge_uniqueness` | `false` | When `true`, `upsert_edge` enforces at most one edge per `(from, to, label)` triple. An upsert with the same triple updates the existing edge. When `false`, every `upsert_edge` call creates a new edge. |
| compact_after_n_flushes | `u32` | `compactAfterNFlushes` | `compact_after_n_flushes` | `4` | Trigger background compaction after this many flushes. Set to `0` to disable auto-compaction. |
| dense_vector | `Option<DenseVectorConfig>` | `denseVector` | See below | `None` | Enable dense vector search. See [DenseVectorConfig](#densevectorconfig). In Python, use separate kwargs: `dense_vector_dimension` and `dense_vector_metric`. |

### WalSyncMode

Controls the trade-off between durability and write throughput.

| Mode | Rust | Node.js | Python | Behavior |
|------|------|---------|--------|----------|
| Immediate | `WalSyncMode::Immediate` | `"immediate"` | `"immediate"` | Every write triggers an `fsync`. Maximum crash safety. Data is durable before the write call returns. Lower throughput (~4ms per write on typical SSDs). |
| GroupCommit | `WalSyncMode::GroupCommit { .. }` | `"group-commit"` | `"group_commit"` | Writes are buffered and fsynced on a timer or when the buffer fills. Higher throughput (batched fsync amortizes the cost across many writes). A crash can lose at most one group-commit interval of writes. |

Current Node.js connector parsing treats unknown `walSyncMode` strings as group commit. Python validates `wal_sync_mode` and rejects unknown strings.

**GroupCommit parameters** (Node.js/Python expose these as top-level options):

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| interval_ms | `u32` | `50` | Maximum time between fsyncs. |
| soft_trigger_bytes | `usize` | `2097152` (2 MB) | Trigger an fsync when buffered bytes reach this threshold, even before the interval fires. |
| hard_cap_bytes | `usize` | `16777216` (16 MB) | Maximum WAL buffer size. Writes block if the buffer reaches this limit before the background syncer drains it. |

### DenseVectorConfig

Configures the HNSW index for dense vector search. Set once at database creation; cannot be changed later.

| Parameter | Rust | Node.js | Python | Default | Description |
|-----------|------|---------|--------|---------|-------------|
| dimension | `u32` | `dimension: number` | `dense_vector_dimension: int` | — (required if enabling vectors) | Dimensionality of dense vectors. Every node's `dense_vector` must have exactly this many elements. |
| metric | `DenseMetric` | `metric: string` | `dense_vector_metric: str` | `Cosine` | Distance metric for similarity. Rust uses enum variants. Node.js and Python use lower-case strings. |

**DenseMetric values:**

| Metric | Rust | Node.js / Python | Score semantics |
|--------|------|------------------|-----------------|
| Cosine | `DenseMetric::Cosine` | `"cosine"` | Higher = more similar (range: -1 to 1). |
| Euclidean | `DenseMetric::Euclidean` | `"euclidean"` | Lower distance is more similar. Results are returned as negative distance so higher scores remain "better." |
| Dot product | `DenseMetric::DotProduct` | `"dot_product"` | Higher = more similar. |

Current Node.js and Python connector parsers fall back to cosine for unknown metric strings.

**HNSW parameters** (Node.js/Python use defaults):

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| m | `usize` | `16` | Maximum number of bi-directional links per node per layer. Higher values improve recall at the cost of memory and build time. |
| ef_construction | `usize` | `200` | Size of the dynamic candidate list during index construction. Higher values improve recall at the cost of slower inserts. |

---

## Data Model

### Node Records

A public, hydrated node record returned by read operations.

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| id | `u64` | `number` | `int` | Unique, auto-assigned node ID. Monotonically increasing. |
| labels | `Vec<String>` | `string[]` | `list[str]` | Complete node label set. |
| key | `String` | `string` | `str` | Unique key within the node's label identity. Do not repeat the label in the key unless it is part of an external source ID. |
| props | `BTreeMap<String, PropValue>` | `Record<string, any>` | `dict[str, Any]` | User-defined properties. See [PropValue](#propvalue) for supported types. Lazily deserialized from MessagePack on first access. |
| weight | `f32` | `number` | `float` | Numeric weight. Default `1.0`. Used by pruning policies and scoring algorithms. |
| created_at | `i64` | `number` | `int` | Timestamp (ms) when the node was first created. |
| updated_at | `i64` | `number` | `int` | Timestamp (ms) of the most recent upsert. |
| dense_vector / denseVector | `Option<DenseVector>` | `number[] \| null` | `list[float] \| None` | Dense vector stored on the node. |
| sparse_vector / sparseVector | `Option<SparseVector>` | `SparseEntry[] \| null` | `list[tuple[int, float]] \| None` | Sparse vector stored on the node. |

Rust returns `NodeView`; Node.js returns `NodeView`; Python returns `NodeView`.

### Edge Records

A public, hydrated edge record returned by read operations.

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| id | `u64` | `number` | `int` | Unique, auto-assigned edge ID. |
| from / from_id | `u64` | `from: number` | `from_id: int` | Source node ID. |
| to / to_id | `u64` | `to: number` | `to_id: int` | Destination node ID. |
| label | `String` | `label: string` | `label: str` | Public edge label. |
| props | `BTreeMap<String, PropValue>` | `Record<string, any>` | `dict[str, Any]` | User-defined properties. |
| weight | `f32` | `number` | `float` | Edge weight. Default `1.0`. |
| valid_from | `i64` | `number` | `int` | Start of the edge's validity window (ms). If omitted when writing, OverGraph uses the edge's `created_at` timestamp. |
| valid_to | `i64` | `number` | `int` | End of the edge's validity window (ms). If omitted when writing, OverGraph uses `i64::MAX` / no expiration. |
| created_at | `i64` | `number` | `int` | Creation timestamp (ms). |
| updated_at | `i64` | `number` | `int` | Last update timestamp (ms). |

Rust returns `EdgeView`; Node.js returns `EdgeView`; Python returns `EdgeView`.

### PropValue

Property values are strongly typed in the Rust core. Connector inputs use their host-language conversion rules and do not expose every Rust variant as a distinct writable type.

| Type | Rust | Node.js | Python | Notes |
|------|------|---------|--------|-------|
| Null | `PropValue::Null` | `null` | `None` | |
| Boolean | `PropValue::Bool(bool)` | `boolean` | `bool` | |
| Integer | `PropValue::Int(i64)` | `number` | `int` | Node.js and normal Python integer inputs write signed integers. |
| Unsigned | `PropValue::UInt(u64)` | Readable as `number` | Readable as `int` | Rust can construct this directly. Connector property inputs do not provide a separate unsigned marker. |
| Float | `PropValue::Float(f64)` | `number` | `float` | 64-bit IEEE 754. |
| String | `PropValue::String(String)` | `string` | `str` | UTF-8. |
| Bytes | `PropValue::Bytes(Vec<u8>)` | Readable as JSON array | `bytes` | Python can write `bytes`. Node.js property input is JSON-like and does not currently convert `Buffer` to `PropValue::Bytes`. |
| Array | `PropValue::Array(Vec<PropValue>)` | `any[]` | `list` | Heterogeneous array. |
| Map | `PropValue::Map(BTreeMap<String, PropValue>)` | `object` | `dict` | Nested properties. |

Properties are encoded with [MessagePack](https://msgpack.org) internally and converted lazily when accessed from Node.js or Python.

Connector property conversion is intentionally host-language shaped. Node.js writes JSON-like values (`null`, booleans, numbers, strings, arrays, and objects); it does not currently use `Buffer` as a bytes marker or expose a separate unsigned-integer marker. Python writes the same common values plus `bytes`; normal Python `int` inputs write signed integers. Rust callers can construct every `PropValue` variant directly.

### IntoNodeLabels (Rust only)

Rust node-label APIs accept `impl IntoNodeLabels` for single-label and multi-label calls. Accepted input forms are `&str`, `String`, `&String`, `&[&str]`, `&[String]`, `Vec<String>`, `&[&str; N]`, and `&[String; N]`.

### Direction

Controls edge traversal direction. Used across traversal and graph analytics APIs.

| Value | Rust | Node.js | Python | Meaning |
|-------|------|---------|--------|---------|
| Outgoing | `Direction::Outgoing` | `"outgoing"` | `"outgoing"` | Follow edges in the `from → to` direction. |
| Incoming | `Direction::Incoming` | `"incoming"` | `"incoming"` | Follow edges in the `to → from` direction. |
| Both | `Direction::Both` | `"both"` | `"both"` | Follow edges in both directions (treat graph as undirected). |

### NodeLabelFilter / LabelMatchMode

Use `NodeLabelFilter` when callers need explicit `Any` or `All` semantics over node labels.

```rust
let any_user_or_admin = NodeLabelFilter {
    labels: vec!["User".into(), "Admin".into()],
    mode: LabelMatchMode::Any,
};

let both_user_and_admin = NodeLabelFilter {
    labels: vec!["User".into(), "Admin".into()],
    mode: LabelMatchMode::All,
};
```

```python
any_user_or_admin = {"labels": ["User", "Admin"], "mode": "any"}
both_user_and_admin = {"labels": ["User", "Admin"], "mode": "all"}
```

```javascript
const anyUserOrAdmin = { labels: ['User', 'Admin'], mode: 'any' };
const bothUserAndAdmin = { labels: ['User', 'Admin'], mode: 'all' };
```

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| labels | `Vec<String>` | `labels: string[]` | `"labels": list[str]` | Public node labels to match. Must be non-empty and contain no duplicates. |
| mode | `LabelMatchMode` | `mode: "any" \| "all"` | `"mode": "any" \| "all"` | `Any`/`"any"` matches nodes with at least one listed label. `All`/`"all"` matches nodes with every listed label. |

---

## Catalog APIs

Catalog APIs explicitly manage or inspect the node-label and edge-label token catalog. Ordinary graph APIs accept and return names; catalog diagnostics are the only public surface that exposes numeric token IDs.

### ensure_node_label / ensure_edge_label

Ensure a catalog token exists for a public node label or edge label and return its diagnostic token ID.

```rust
let user_label_id = db.ensure_node_label("User")?;
let created_label_id = db.ensure_edge_label("CREATED")?;
```

```javascript
const userLabelId = db.ensureNodeLabel('User');
const createdLabelId = db.ensureEdgeLabel('CREATED');
```

```python
user_label_id = db.ensure_node_label("User")
created_label_id = db.ensure_edge_label("CREATED")
```

These methods are optional for normal writes: `upsert_node`, `upsert_edge`, batch writes, graph patch, and write transactions auto-create missing names durably. Use explicit ensures when you want catalog IDs for diagnostics or want to prepare names before writes.

### get_node_label_id / get_edge_label_id

Read-only lookup from public name to diagnostic token ID.

```rust
let id = db.get_node_label_id("User")?;
let edge_id = db.get_edge_label_id("CREATED")?;
```

```javascript
const id = db.getNodeLabelId('User');
const edgeId = db.getEdgeLabelId('CREATED');
```

```python
id = db.get_node_label_id("User")
edge_id = db.get_edge_label_id("CREATED")
```

Returns `None`/`null` when the name is unknown.

### get_node_label / get_edge_label

Diagnostic reverse lookup from token ID to public name.

```rust
let label = db.get_node_label(label_id)?;
let edge_label = db.get_edge_label(label_id)?;
```

```javascript
const label = db.getNodeLabel(labelId);
const edgeLabel = db.getEdgeLabel(labelId);
```

```python
label = db.get_node_label(label_id)
edge_label = db.get_edge_label(label_id)
```

The node and edge `label_id` / `labelId` arguments are catalog token IDs, not normal graph API inputs.

### list_node_labels / list_edge_labels

List published catalog entries.

```rust
let labels = db.list_node_labels()?;
let edge_labels = db.list_edge_labels()?;
```

```javascript
const labels = db.listNodeLabels();
const edgeLabels = db.listEdgeLabels();
```

```python
labels = db.list_node_labels()
edge_labels = db.list_edge_labels()
```

| Entry | Rust fields | Node.js fields | Python fields |
|-------|-------------|----------------|---------------|
| Node label | `label`, `label_id` | `label`, `labelId` | `label`, `label_id` |
| Edge label | `label`, `label_id` | `label`, `labelId` | `label`, `label_id` |

`label_id` and `labelId` in these entries are diagnostic catalog metadata. Do not use them as input to ordinary node, edge, query, traversal, or vector APIs.

---

## Node Operations

### upsert_node

Creates a new node or updates an existing one. If the key already resolves to the same node through any supplied label, the node is updated in place; if the same key resolves to different nodes across supplied labels, the write is rejected as a conflict.

**Rust**
```rust
// Also accepts multiple labels: &["User", "Admin"]
let id = db.upsert_node("User", "alice", UpsertNodeOptions {
    props: BTreeMap::from([("role".into(), PropValue::String("admin".into()))]),
    weight: 1.0,
    ..Default::default()
})?;
```

**Node.js**
```javascript
// Also accepts multiple labels: ['User', 'Admin']
const id = db.upsertNode('User', 'alice', {
  props: { role: 'admin' },
  weight: 1.0,
});
```

**Python**
```python
# Also accepts multiple labels: ["User", "Admin"]
id = db.upsert_node("User", "alice", props={"role": "admin"}, weight=1.0)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| labels | `impl IntoNodeLabels` | `string \| string[]` | `str \| list[str]` | Yes | — | One or more public node labels. |
| key | `&str` | `string` | `str` | Yes | — | Unique key scoped by node labels. If the supplied label set and key resolve to an existing node, it is updated. |
| props | `BTreeMap<String, PropValue>` | `Record<string, any>` | `dict[str, Any]` | No | `{}` | Arbitrary key-value properties. On update, the entire props map is replaced (not merged). |
| weight | `f32` | `number` | `float` | No | `1.0` | Numeric weight. Used by pruning policies (`max_weight`) and scoring algorithms. |
| dense_vector | `Option<Vec<f32>>` | `number[]` | `list[float]` | No | `None` | Dense vector for similarity search. Length must match the `dimension` configured at `open()`. Requires `dense_vector` to be enabled in DbOptions. |
| sparse_vector | `Option<Vec<(u32, f32)>>` | `SparseEntry[]` | `list[tuple[int, float]]` | No | `None` | Sparse vector as `(dimension_index, value)` pairs. Dimension indices must be unique. No upfront dimension configuration required. |

**SparseEntry** (Node.js):
```typescript
{ dimension: number, value: number }
```

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<u64, EngineError>` | `number` | `int` |

The node's ID. If the node was newly created, this is a fresh ID. If the node already existed, this is the existing ID.

#### Behavior

- **Upsert semantics**: On insert, allocates a new ID, sets `created_at` and `updated_at` to the current time. On update, keeps the original `created_at`, refreshes `updated_at`, and replaces labels, props, weight, and vectors.
- **Atomicity**: The write is applied to the WAL and memtable in a single operation.
- **Performance**: ~4ms per call in `Immediate` sync mode (dominated by `fsync`). Use [`batch_upsert_nodes`](#batch_upsert_nodes) for bulk operations where a single fsync is shared across the batch.

---

### get_node

Retrieves a node by its ID.

**Rust**
```rust
if let Some(node) = db.get_node(id)? {
    println!("labels={:?}, key={}", node.labels, node.key);
}
```

**Node.js**
```javascript
const node = db.getNode(id);
if (node) console.log(node.labels, node.key);
```

**Python**
```python
node = db.get_node(id)
if node:
    print(node.labels, node.key)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| id | `u64` | `number` | `int` | Yes | Node ID to retrieve. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Option<NodeView>, EngineError>` | `NodeView \| null` | `NodeView \| None` |

Returns `None`/`null` if the node does not exist or has been deleted.

#### Performance

~38ns per lookup (memtable hot path). Segment reads require I/O but are mmap-accelerated.

---

### get_node_by_key

Looks up a node by its `(label, key)` pair. Uses the label-scoped key lookup/index for fast lookup.

**Rust**
```rust
let node = db.get_node_by_key("User", "alice")?;
```

**Node.js**
```javascript
const node = db.getNodeByKey('User', 'alice');
```

**Python**
```python
node = db.get_node_by_key("User", "alice")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Node label. |
| key | `&str` | `string` | `str` | Yes | Node key within the label. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Option<NodeView>, EngineError>` | `NodeView \| null` | `NodeView \| None` |

Returns `None`/`null` if no node with that `(label, key)` exists.

---

### add_node_label / remove_node_label

Node label-set mutation helpers. These update a node's label set without changing its ID, key, properties, weight, or vectors.

```rust
let added = db.add_node_label(node_id, "Admin")?;
let removed = db.remove_node_label(node_id, "Trial")?;
```

```javascript
const added = db.addNodeLabel(nodeId, 'Admin');
const removed = db.removeNodeLabel(nodeId, 'Trial');
```

```python
added = db.add_node_label(node_id, "Admin")
removed = db.remove_node_label(node_id, "Trial")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| id | `u64` | `number` | `int` | Yes | Node ID to mutate. |
| label | `&str` | `string` | `str` | Yes | Public node label to add or remove. |

#### Returns

| Rust | Node.js | Python | Description |
|------|---------|--------|-------------|
| `Result<bool, EngineError>` | `boolean` | `bool` | `true` when the node's label set changed, `false` when the requested label was already present for add or absent for remove. |

#### Behavior

- Adding a label auto-creates the label token when needed.
- Adding a label fails if another node already owns the same `(label, key)` identity.
- Removing an unknown or absent label returns `false`.
- Removing the last remaining node label returns an error.

---

### delete_node

Deletes a node by ID. **Cascade-deletes all incident edges** (both incoming and outgoing) in the same WAL batch.

**Rust**
```rust
db.delete_node(id)?;
```

**Node.js**
```javascript
db.deleteNode(id);
```

**Python**
```python
db.delete_node(id)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| id | `u64` | `number` | `int` | Yes | Node ID to delete. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<(), EngineError>` | `void` | `None` |

#### Behavior

- Writes tombstones for the node and all its incident edges (memtable + segments scanned) in a single WAL batch for atomicity.
- Tombstoned records are excluded from all subsequent reads.
- Tombstones are physically removed during [compaction](#compact).
- Deleting a nonexistent or already-deleted node is a no-op (idempotent).

---

### batch_upsert_nodes

Upserts multiple nodes in a single batch with one WAL fsync. Significantly faster than calling `upsert_node` in a loop.

**Rust**
```rust
let inputs = vec![
    NodeInput {
        labels: vec!["User".into()],
        key: "alice".into(),
        props: BTreeMap::new(),
        weight: 1.0,
        dense_vector: None,
        sparse_vector: None,
    },
    NodeInput {
        labels: vec!["User".into(), "Admin".into()],
        key: "bob".into(),
        props: BTreeMap::from([("role".into(), PropValue::String("viewer".into()))]),
        weight: 0.8,
        dense_vector: None,
        sparse_vector: None,
    },
];
let ids = db.batch_upsert_nodes(inputs)?;
```

**Node.js**
```javascript
const ids = db.batchUpsertNodes([
  { labels: ['User'], key: 'alice', weight: 1.0 },
  { labels: ['User', 'Admin'], key: 'bob', weight: 0.8, props: { role: 'viewer' } },
]);
// ids is a Float64Array
```

**Python**
```python
ids = db.batch_upsert_nodes([
    {"labels": ["User"], "key": "alice", "weight": 1.0},
    {"labels": ["User", "Admin"], "key": "bob", "weight": 0.8, "props": {"role": "viewer"}},
])
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| nodes | `Vec<NodeInput>` | `NodeInput[]` | `list[dict]` | Yes | Array of node inputs. Each element has the same fields as [`upsert_node`](#upsert_node) parameters. |

**NodeInput fields:**

| Field | Rust | Node.js | Python dict key | Required | Default | Description |
|-------|------|---------|-----------------|----------|---------|-------------|
| labels | `labels: Vec<String>` | `labels: string \| string[]` | `"labels"` | Yes | — | One or more node labels. Node.js accepts a single string or a non-empty string array for dict-based node inputs. |
| key | `String` | `key: string` | `"key"` | Yes | — | Node key. |
| props | `BTreeMap<String, PropValue>` | `props: object` | `"props"` | No | `{}` | Properties. |
| weight | `f32` | `weight: number` | `"weight"` | No | `1.0` | Weight. |
| dense_vector | `Option<Vec<f32>>` | `denseVector: number[]` | `"dense_vector"` | No | `None` | Dense vector. |
| sparse_vector | `Option<Vec<(u32, f32)>>` | `sparseVector: SparseEntry[]` | `"sparse_vector"` | No | `None` | Sparse vector. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `list[int]` |

An array of node IDs in the same order as the input array.

#### Performance

A single fsync is performed for the entire batch. At 100 nodes, this achieves ~46μs per node amortized (vs. ~4ms per node for individual calls). Use this for all bulk operations.

---

### get_nodes

Batch-retrieves multiple nodes by ID. Uses a sorted merge-walk across all data sources, **much faster than calling `get_node` in a loop**.

**Rust**
```rust
let nodes = db.get_nodes(&[1, 2, 3])?;
// nodes[0] is Option<NodeView> for ID 1, etc.
```

**Node.js**
```javascript
const nodes = db.getNodes([1, 2, 3]);
// nodes[0] is NodeView | null for ID 1, etc.
```

**Python**
```python
nodes = db.get_nodes([1, 2, 3])
# nodes[0] is NodeView | None for ID 1, etc.
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| ids | `&[u64]` | `number[]` | `list[int]` | Yes | Array of node IDs to fetch. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<Option<NodeView>>, EngineError>` | `(NodeView \| null)[]` | `list[NodeView \| None]` |

An array the same length as the input, where each element is the node record or `None`/`null` if that ID doesn't exist.

---

### get_nodes_by_keys

Batch-retrieves multiple nodes by `(label, key)` pairs.

**Rust**
```rust
let nodes = db.get_nodes_by_keys(&[
    NodeKeyQuery { label: "User".into(), key: "alice".into() },
    NodeKeyQuery { label: "User".into(), key: "bob".into() },
])?;
```

**Node.js**
```javascript
const nodes = db.getNodesByKeys([
  { label: 'User', key: 'alice' },
  { label: 'User', key: 'bob' },
]);
```

**Python**
```python
nodes = db.get_nodes_by_keys([
    {"labels": ["User"], "key": "alice"},
    {"labels": ["User"], "key": "bob"},
])
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| keys | `&[NodeKeyQuery]` | `KeyQuery[]` | `list[dict]` | Yes | Array of key lookups. Python uses `{"labels": "User" \| ["User"], "key": ...}` and requires exactly one label because keys are label-scoped. |

**KeyQuery** (Node.js):
```typescript
{ label: string, key: string }
```

#### Returns

Same shape as [`get_nodes`](#get_nodes): an array of node records or `None`/`null` in input order.

---

## Edge Operations

### upsert_edge

Creates a new edge or updates an existing one. When `edge_uniqueness` is enabled, edges are identified by the `(from, to, label)` triple.

**Rust**
```rust
let id = db.upsert_edge(alice_id, project_id, "WORKS_ON", UpsertEdgeOptions {
    props: BTreeMap::from([("since".into(), PropValue::String("2024".into()))]),
    weight: 1.0,
    ..Default::default()
})?;
```

**Node.js**
```javascript
const id = db.upsertEdge(aliceId, projectId, 'WORKS_ON', {
  props: { since: '2024' },
  weight: 1.0,
});
```

**Python**
```python
id = db.upsert_edge(alice_id, project_id, "WORKS_ON",
    props={"since": "2024"}, weight=1.0)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| from | `u64` | `number` | `int` | Yes | — | Source node ID. |
| to | `u64` | `number` | `int` | Yes | — | Destination node ID. |
| label | `&str` | `string` | `str` | Yes | — | Public edge label such as `"WORKS_ON"` or `"KNOWS"`. |
| props | `BTreeMap<String, PropValue>` | `Record<string, any>` | `dict[str, Any]` | No | `{}` | Edge properties. Replaced entirely on update. |
| weight | `f32` | `number` | `float` | No | `1.0` | Edge weight. Used by shortest path (as cost), top-k scoring, and pruning. |
| valid_from | `Option<i64>` | `number` | `int` | No | edge `created_at` | Start of the edge's temporal validity window (ms). Edges with `valid_from > at_epoch` are excluded from temporal queries. |
| valid_to | `Option<i64>` | `number` | `int` | No | `i64::MAX` (no expiration) | End of the validity window (ms). Edges with `valid_to <= at_epoch` are excluded from temporal queries. See [`invalidate_edge`](#invalidate_edge). |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<u64, EngineError>` | `number` | `int` |

The edge ID.

#### Behavior

- **With `edge_uniqueness` enabled**: If an edge with the same `(from, to, label)` exists, it is updated and the existing ID is returned. Otherwise a new edge is created.
- **With `edge_uniqueness` disabled** (default): Every call creates a new edge (parallel edges are allowed).

---

### get_edge

Retrieves an edge by ID.

**Rust**
```rust
let edge = db.get_edge(edge_id)?;
```

**Node.js**
```javascript
const edge = db.getEdge(edgeId);
```

**Python**
```python
edge = db.get_edge(edge_id)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| id | `u64` | `number` | `int` | Yes | Edge ID. |

#### Returns

`EdgeView` / `EdgeView` / `EdgeView`, or `None`/`null` if the edge doesn't exist or has been deleted.

---

### get_edge_by_triple

Looks up an edge by its `(from, to, label)` triple. Only meaningful when `edge_uniqueness` is enabled.

**Rust**
```rust
let edge = db.get_edge_by_triple(alice_id, project_id, "WORKS_ON")?;
```

**Node.js**
```javascript
const edge = db.getEdgeByTriple(aliceId, projectId, 'WORKS_ON');
```

**Python**
```python
edge = db.get_edge_by_triple(alice_id, project_id, "WORKS_ON")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| from | `u64` | `number` | `int` | Yes | Source node ID. |
| to | `u64` | `number` | `int` | Yes | Destination node ID. |
| label | `&str` | `string` | `str` | Yes | Edge label. |

#### Returns

`EdgeView` / `EdgeView` / `EdgeView`, or `None`/`null`.

---

### delete_edge

Deletes an edge by ID.

**Rust**
```rust
db.delete_edge(edge_id)?;
```

**Node.js**
```javascript
db.deleteEdge(edgeId);
```

**Python**
```python
db.delete_edge(edge_id)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| id | `u64` | `number` | `int` | Yes | Edge ID to delete. |

#### Behavior

- Writes a tombstone. Idempotent: deleting a nonexistent or already-deleted edge is a no-op.
- Tombstones are reclaimed during [compaction](#compact).

---

### invalidate_edge

Closes an edge's validity window by setting its `valid_to` timestamp. The edge remains in the database (not tombstoned) but is excluded from queries that use temporal filtering (`at_epoch`).

**Rust**
```rust
let updated = db.invalidate_edge(edge_id, now_ms)?;
```

**Node.js**
```javascript
const updated = db.invalidateEdge(edgeId, Date.now());
```

**Python**
```python
updated = db.invalidate_edge(edge_id, int(time.time() * 1000))
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| id | `u64` | `number` | `int` | Yes | Edge ID. |
| valid_to | `i64` | `number` | `int` | Yes | New end-of-validity timestamp (ms). The edge is considered expired for any `at_epoch >= valid_to`. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Option<EdgeView>, EngineError>` | `EdgeView \| null` | `EdgeView \| None` |

The updated edge record, or `None`/`null` if the edge doesn't exist.

#### Use Case

Temporal graphs: rather than hard-deleting edges, close their validity window. This preserves historical data while excluding expired edges from current queries:

```javascript
// Only returns edges valid at the given timestamp
const neighbors = db.neighbors(nodeId, { atEpoch: Date.now() });
```

---

### batch_upsert_edges

Upserts multiple edges in a single batch with one WAL fsync.

**Rust**
```rust
let inputs = vec![
    EdgeInput {
        from: 1,
        to: 2,
        label: "WORKS_ON".into(),
        props: BTreeMap::new(),
        weight: 1.0,
        valid_from: None,
        valid_to: None,
    },
    EdgeInput {
        from: 1,
        to: 3,
        label: "WORKS_ON".into(),
        props: BTreeMap::new(),
        weight: 0.5,
        valid_from: None,
        valid_to: None,
    },
];
let ids = db.batch_upsert_edges(inputs)?;
```

**Node.js**
```javascript
const ids = db.batchUpsertEdges([
  { from: 1, to: 2, label: 'WORKS_ON', weight: 1.0 },
  { from: 1, to: 3, label: 'WORKS_ON', weight: 0.5 },
]);
```

**Python**
```python
ids = db.batch_upsert_edges([
    {"from_id": 1, "to_id": 2, "label": "WORKS_ON", "weight": 1.0},
    {"from_id": 1, "to_id": 3, "label": "WORKS_ON", "weight": 0.5},
])
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| edges | `Vec<EdgeInput>` | `EdgeInput[]` | `list[dict]` | Yes | Array of edge inputs. |

**EdgeInput fields:**

| Field | Rust | Node.js | Python dict key | Required | Default | Description |
|-------|------|---------|-----------------|----------|---------|-------------|
| from | `u64` | `from: number` | `"from_id"` | Yes | — | Source node ID. |
| to | `u64` | `to: number` | `"to_id"` | Yes | — | Destination node ID. |
| label | `String` | `label: string` | `"label"` | Yes | — | Edge label. |
| props | `BTreeMap<String, PropValue>` | `props: object` | `"props"` | No | `{}` | Properties. |
| weight | `f32` | `weight: number` | `"weight"` | No | `1.0` | Weight. |
| valid_from | `Option<i64>` | `validFrom: number` | `"valid_from"` | No | edge `created_at` | Validity start. |
| valid_to | `Option<i64>` | `validTo: number` | `"valid_to"` | No | `i64::MAX` | Validity end. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `list[int]` |

Edge IDs in input order.

---

### get_edges

Batch-retrieves multiple edges by ID using a sorted merge-walk.

**Rust**
```rust
let edges = db.get_edges(&[10, 20, 30])?;
```

**Node.js**
```javascript
const edges = db.getEdges([10, 20, 30]);
```

**Python**
```python
edges = db.get_edges([10, 20, 30])
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| ids | `&[u64]` | `number[]` | `list[int]` | Yes | Edge IDs to fetch. |

#### Returns

Array of edge records or `None`/`null` in input order.

---

## Atomic Operations

### graph_patch

Applies multiple operations atomically in a single WAL batch: node upserts, edge upserts, edge invalidations, and deletes.

**Rust**
```rust
let result = db.graph_patch(GraphPatch {
    upsert_nodes: vec![NodeInput {
        labels: vec!["User".into(), "Admin".into()],
        key: "carol".into(),
        props: BTreeMap::new(),
        weight: 1.0,
        dense_vector: None,
        sparse_vector: None,
    }],
    upsert_edges: vec![EdgeInput {
        from: 1,
        to: 2,
        label: "WORKS_ON".into(),
        props: BTreeMap::new(),
        weight: 1.0,
        valid_from: None,
        valid_to: None,
    }],
    invalidate_edges: vec![(edge_id, now_ms)],
    delete_node_ids: vec![old_node_id],
    delete_edge_ids: vec![old_edge_id],
})?;
```

**Node.js**
```javascript
const result = db.graphPatch({
  upsertNodes: [{ labels: ['User'], key: 'carol' }],
  upsertEdges: [{ from: 1, to: 2, label: 'WORKS_ON' }],
  invalidateEdges: [{ edgeId: 5, validTo: Date.now() }],
  deleteNodeIds: [oldNodeId],
  deleteEdgeIds: [oldEdgeId],
});
```

**Python**
```python
result = db.graph_patch({
    "upsert_nodes": [{"labels": ["User"], "key": "carol"}],
    "upsert_edges": [{"from_id": 1, "to_id": 2, "label": "WORKS_ON"}],
    "invalidate_edges": [{"edge_id": 5, "valid_to": int(time.time() * 1000)}],
    "delete_node_ids": [old_node_id],
    "delete_edge_ids": [old_edge_id],
})
```

#### Parameters

All fields in the patch object are optional. Omit any you don't need.

| Field | Rust | Node.js | Python dict key | Description |
|-------|------|---------|-----------------|-------------|
| upsert_nodes | `Vec<NodeInput>` | `upsertNodes: NodeInput[]` | `"upsert_nodes"` | Nodes to create or update. Same format as [`batch_upsert_nodes`](#batch_upsert_nodes). |
| upsert_edges | `Vec<EdgeInput>` | `upsertEdges: EdgeInput[]` | `"upsert_edges"` | Edges to create or update. Same format as [`batch_upsert_edges`](#batch_upsert_edges). |
| invalidate_edges | `Vec<(u64, i64)>` | `invalidateEdges: {edgeId, validTo}[]` | `"invalidate_edges"` | Edges to invalidate. Each entry specifies an edge ID and a `valid_to` timestamp. |
| delete_node_ids | `Vec<u64>` | `deleteNodeIds: number[]` | `"delete_node_ids"` | Node IDs to delete. **Cascade**: incident edges are automatically deleted. |
| delete_edge_ids | `Vec<u64>` | `deleteEdgeIds: number[]` | `"delete_edge_ids"` | Edge IDs to delete. |

#### Execution Order

Operations within a patch are applied in a deterministic order:

1. **Node upserts** - create/update nodes (so new nodes can be referenced by edge upserts)
2. **Edge upserts** - create/update edges
3. **Edge invalidations** - set `valid_to` on edges
4. **Edge deletes** - tombstone edges
5. **Node deletes** - tombstone nodes and cascade-delete all incident edges

#### Returns: PatchResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| node_ids | `Vec<u64>` | `Float64Array` | `list[int]` | IDs of all upserted nodes, in input order. |
| edge_ids | `Vec<u64>` | `Float64Array` | `list[int]` | IDs of all upserted edges, in input order. |

---

### write transactions

Explicit write transactions stage ordered graph mutations locally, support bounded read-own-writes point lookups, and commit as one atomic WAL batch. Conflict detection is optimistic and write-target based: if a staged target changed after the transaction began, `commit` fails with a transaction conflict and no partial state is published.

Use transactions when later operations need local aliases from earlier staged upserts, or when a caller needs rollback before durability. Use `graph_patch` for simpler grouped atomic batches that do not need ordered local references.

Transaction reads are intentionally bounded. A transaction can read committed state from its begin snapshot plus its own staged writes for point/dedup lookups only: `get_node`, `get_edge`, `get_node_by_key`, and `get_edge_by_triple`. Traversal, vector search, property queries, pagination, export, analytics, prune-policy mutation, and maintenance APIs are not exposed on `WriteTxn`.

**Rust**
```rust
let mut txn = db.begin_write_txn()?;
let alice = txn.upsert_node_as("alice", &["User", "Admin"], "alice", UpsertNodeOptions::default())?;
let bob = txn.upsert_node_as("bob", "User", "bob", UpsertNodeOptions::default())?;
txn.upsert_edge_as("knows", alice.clone(), bob.clone(), "KNOWS", UpsertEdgeOptions::default())?;
assert!(txn.add_node_label(alice.clone(), "Manager")?);
assert!(txn.remove_node_label(alice.clone(), "Admin")?);
let staged = txn.get_node_by_key("User", "alice")?;
if let Some(view) = &staged {
    println!("staged labels: {:?}", view.labels);
}
let result = txn.commit()?;
```

**Node.js**
```javascript
const txn = db.beginWriteTxn();
txn.stage([
  { op: 'upsertNode', alias: 'alice', labels: ['User', 'Admin'], key: 'alice' },
  { op: 'upsertNode', alias: 'bob', labels: ['User'], key: 'bob' },
  { op: 'upsertEdge', alias: 'knows', from: { local: 'alice' }, to: { local: 'bob' }, label: 'KNOWS' },
]);
txn.addNodeLabel({ local: 'bob' }, 'Trial');
const staged = txn.getNode({ local: 'alice' });
const result = txn.commit();
```

**Python**
```python
txn = db.begin_write_txn()
txn.stage([
    {"op": "upsert_node", "alias": "alice", "labels": ["User", "Admin"], "key": "alice"},
    {"op": "upsert_node", "alias": "bob", "labels": ["User"], "key": "bob"},
    {"op": "upsert_edge", "alias": "knows", "from": {"local": "alice"}, "to": {"local": "bob"}, "label": "KNOWS"},
])
txn.add_node_label({"local": "bob"}, "Trial")
staged = txn.get_node({"local": "alice"})
result = txn.commit()
```

#### Transaction Surface

| Operation | Rust | Node.js | Python |
|-----------|------|---------|--------|
| Begin | `begin_write_txn()` | `beginWriteTxn()` | `begin_write_txn()` |
| Stage node | `upsert_node`, `upsert_node_as` | `upsertNode`, `upsertNodeAs` | `upsert_node`, `upsert_node_as` |
| Mutate node labels | `add_node_label`, `remove_node_label` | `addNodeLabel`, `removeNodeLabel` | `add_node_label`, `remove_node_label` |
| Stage edge | `upsert_edge`, `upsert_edge_as` | `upsertEdge`, `upsertEdgeAs` | `upsert_edge`, `upsert_edge_as` |
| Bulk ordered stage | `stage_intents(Vec<TxnIntent>)` | `stage(operations)` | `stage(operations)` |
| Reads | `get_node`, `get_edge`, `get_node_by_key`, `get_edge_by_triple` | same camelCase names | same snake_case names |
| Finish | `commit`, `rollback` | `commit`, `rollback` | `commit`, `rollback` |

#### Rust Transaction DTOs

Rust exposes the transaction reference and intent objects directly:

| Object | Variants / fields | Description |
|--------|-------------------|-------------|
| `TxnNodeRef` | `Id(u64)`, `Key { label, key }`, `Local(TxnLocalRef)` | Node target for transaction writes and bounded transaction reads. `Key` is single-label scoped. |
| `TxnEdgeRef` | `Id(u64)`, `Triple { from, to, label }`, `Local(TxnLocalRef)` | Edge target by ID, by endpoint refs plus edge label, or by local transaction ref. |
| `TxnIntent::UpsertNode` | `alias`, `labels`, `key`, `options` | Ordered staged node upsert. `labels` is the complete node-label set for the write. |
| `TxnIntent::UpsertEdge` | `alias`, `from`, `to`, `label`, `options` | Ordered staged edge upsert using transaction node refs. |
| `TxnIntent::DeleteNode` | `target` | Ordered staged node delete. |
| `TxnIntent::DeleteEdge` | `target` | Ordered staged edge delete. |
| `TxnIntent::InvalidateEdge` | `target`, `valid_to` | Ordered staged temporal edge invalidation. |

#### Builder Methods

| Method | Required inputs | Optional inputs | Returns |
|--------|-----------------|-----------------|---------|
| `upsert_node` / `upsertNode` | `labels`, `key` | node upsert options: `props`, `weight`, `dense_vector` / `denseVector`, `sparse_vector` / `sparseVector` | node ref addressable by key |
| `upsert_node_as` / `upsertNodeAs` | `alias`, `labels`, `key` | node upsert options | local node ref `{ local: alias }` |
| `add_node_label` / `remove_node_label` | node ref, `label` | — | `bool` changed flag |
| `upsert_edge` / `upsertEdge` | `from`, `to`, `label` | edge upsert options: `props`, `weight`, `valid_from` / `validFrom`, `valid_to` / `validTo` | edge ref addressable by triple |
| `upsert_edge_as` / `upsertEdgeAs` | `alias`, `from`, `to`, `label` | edge upsert options | local edge ref `{ local: alias }` |
| `delete_node` / `deleteNode` | node ref | — | `void` / `None` |
| `delete_edge` / `deleteEdge` | edge ref | — | `void` / `None` |
| `invalidate_edge` / `invalidateEdge` | edge ref, `valid_to` / `validTo` | — | `void` / `None` |
| `stage` / `stage_intents` | ordered operation payloads | — | `void` / `None` |

#### Ordered Operation Payloads

Node.js uses camelCase fields and op names: `upsertNode`, `upsertEdge`, `deleteNode`, `deleteEdge`, `invalidateEdge`.

Python uses snake_case fields and op names: `upsert_node`, `upsert_edge`, `delete_node`, `delete_edge`, `invalidate_edge`.

References are one of:

| Ref kind | Node.js | Python |
|----------|---------|--------|
| Node by ID | `{ id }` | `{"id": id}` |
| Node by key | `{ labels, key }` | `{"labels": label_or_single_label_list, "key": key}` |
| Node local alias | `{ local }` | `{"local": local}` |
| Edge by ID | `{ id }` | `{"id": id}` |
| Edge by triple | `{ from, to, label }` | `{"from": from, "to": to, "label": label}` |
| Edge local alias | `{ local }` | `{"local": local}` |

Node-by-key transaction refs use `labels` and `key` but are still single-label scoped:
`labels` may be a string or a one-item list/array.

Aliases are optional, process-local, and never persisted. When present, aliases must be unique within the transaction across node aliases and unique across edge aliases.

#### Transaction Read Views

`get_node` and `get_node_by_key` on a transaction return a transaction node view:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| id | `Option<u64>` | `id?: number` | `"id": int \| None` | Committed node ID when already known; `None`/omitted for staged creates that allocate an ID at commit. |
| local | `Option<TxnLocalRef>` | `local?: string` | `"local": str \| None` | Local alias for aliased staged records. Internal unaliased slots are not exposed as strings. |
| labels | `Vec<String>` | `labels: string[]` | `"labels": list[str]` | Complete node label set visible inside the transaction. |
| key | `String` | `key` | `"key"` | Node key. |
| props | `BTreeMap<String, PropValue>` | `props` | `"props"` | Node properties visible inside the transaction. |
| created_at / updated_at | `Option<i64>` | `createdAt?` / `updatedAt?` | `"created_at"` / `"updated_at"` | Present for committed records; absent/`None` for staged creates before commit. |
| weight | `f32` | `weight` | `"weight"` | Node weight. |
| dense_vector / sparse_vector | `Option<DenseVector>` / `Option<SparseVector>` | `denseVector?` / `sparseVector?` | `"dense_vector"` / `"sparse_vector"` | Staged or committed vectors when present. |

`get_edge` and `get_edge_by_triple` return a transaction edge view:

| Field | Node.js | Python | Description |
|-------|---------|--------|-------------|
| id | `id?: number` | `"id": int \| None` | Committed edge ID when already known; `None`/omitted for staged creates that allocate an ID at commit. |
| local | `local?: string` | `"local": str \| None` | Local alias for aliased staged records. |
| from / to | `from` / `to` | `"from"` / `"to"` | Endpoint refs visible inside the transaction. |
| label | `label` | `"label"` | Edge label. |
| props | `props` | `"props"` | Edge properties visible inside the transaction. |
| created_at / updated_at | `createdAt?` / `updatedAt?` | `"created_at"` / `"updated_at"` | Present for committed records; absent/`None` for staged creates before commit. |
| weight | `weight` | `"weight"` | Edge weight. |
| valid_from / valid_to | `validFrom?` / `validTo?` | `"valid_from"` / `"valid_to"` | Temporal validity bounds when present. |

#### Commit Result

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| node IDs | `node_ids: Vec<u64>` | `nodeIds: Float64Array` | `node_ids: list[int]` | IDs returned by node upsert intents in input order. |
| edge IDs | `edge_ids: Vec<u64>` | `edgeIds: Float64Array` | `edge_ids: list[int]` | IDs returned by edge upsert intents in input order. |
| node aliases | `local_node_ids` | `nodeAliases` | `node_aliases` | Alias-to-node-ID map for aliased staged node upserts. |
| edge aliases | `local_edge_ids` | `edgeAliases` | `edge_aliases` | Alias-to-edge-ID map for aliased staged edge upserts. |

After `commit()` or `rollback()`, the transaction handle is closed. Further use fails with `TxnClosed` / `transaction is closed`.

#### Conflict Handling

`TxnConflict` means the transaction definitely did not commit: no WAL entry was appended and no partial state was published. The caller can retry by starting a new transaction, restaging the desired operations, re-reading any needed point records, and committing again. OverGraph does not automatically retry because conflict-safe retry policy depends on caller intent.

---

## Label and Edge-Label Queries

### nodes_by_labels

Returns all node IDs containing every supplied node label.

**Rust**
```rust
let ids: Vec<u64> = db.nodes_by_labels("User")?;
let admin_ids: Vec<u64> = db.nodes_by_labels(vec!["User".into(), "Admin".into()])?;
```

**Node.js**
```javascript
const ids = db.nodesByLabels('User'); // Float64Array
const adminIds = db.nodesByLabels(['User', 'Admin']);
```

**Python**
```python
ids = db.nodes_by_labels("User")  # IdArray (lazy)
ids_list = ids.to_list()      # materialize to list[int]
admin_ids = db.nodes_by_labels(["User", "Admin"])
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| labels | `impl IntoNodeLabels` | `string \| string[]` | `str \| list[str]` | Yes | Label or labels to match. Nodes must contain every supplied node label. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `IdArray` |

All matching node IDs. Filtered (excludes deleted/pruned nodes).

**Python `IdArray`**: A lazy wrapper that avoids copying IDs to Python memory until accessed. Supports `len()`, indexing (`arr[i]`), iteration, `in` operator, and `to_list()`.

#### Performance

Single-label input uses the direct per-label fast path. Multi-label input uses `All` semantics, drives from the best label posting, and metadata-verifies current label membership. Use [`query_node_ids`](#query_node_ids) with `NodeLabelFilter` when `Any` semantics are needed.

---

### edges_by_label

Returns all edge IDs of a given edge label.

**Rust**
```rust
let ids: Vec<u64> = db.edges_by_label("WORKS_ON")?;
```

**Node.js**
```javascript
const ids = db.edgesByLabel('WORKS_ON'); // Float64Array
```

**Python**
```python
ids = db.edges_by_label("WORKS_ON")  # IdArray (lazy)
ids_list = ids.to_list()             # materialize to list[int]
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Public edge label to match, such as `"WORKS_ON"` or `"KNOWS"`. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `IdArray` |

All matching live edge IDs. Tombstoned edges are excluded. Unknown edge labels return an empty result.

**Python `IdArray`**: A lazy wrapper that avoids copying IDs to Python memory until accessed. Supports `len()`, indexing (`arr[i]`), iteration, `in` operator, and `to_list()`.

#### Performance

Uses the edge-label posting index and does not hydrate edge records. Edges have exactly one public label, so this API accepts a single label string. Use [`query_edge_ids`](#query_edge_ids) when you need additional edge predicates.

---

### get_nodes_by_labels

Returns full node records for nodes containing every supplied node label.

```rust
let nodes: Vec<NodeView> = db.get_nodes_by_labels("User")?;
let admin_nodes: Vec<NodeView> =
    db.get_nodes_by_labels(vec!["User".into(), "Admin".into()])?;
```

```javascript
const nodes = db.getNodesByLabels('User'); // NodeView[]
const admins = db.getNodesByLabels(['User', 'Admin']);
```

```python
nodes = db.get_nodes_by_labels("User")  # list[NodeView]
admins = db.get_nodes_by_labels(["User", "Admin"])
```

#### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| labels | `impl IntoNodeLabels` / `string \| string[]` / `str \| list[str]` | Yes | Label or labels to match. Nodes must contain every supplied node label. |

#### Returns

Array of full node records. Includes all public fields (id, labels, key, props, weight, timestamps, vectors).

Multi-label input always uses `All` semantics. Use [`query_nodes`](#query_nodes) with `NodeLabelFilter` when `Any` semantics are needed.

---

### get_edges_by_label

Returns full edge records for all edges of a given edge label.

**Rust**
```rust
let edges: Vec<EdgeView> = db.get_edges_by_label("WORKS_ON")?;
```

**Node.js**
```javascript
const edges = db.getEdgesByLabel('WORKS_ON'); // EdgeView[]
```

**Python**
```python
edges = db.get_edges_by_label("WORKS_ON")  # list[EdgeView]
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Public edge label to match. |

#### Returns

Array of full edge records. Includes all public edge fields: id, endpoints (`from`/`to` in Rust and Node.js, `from_id`/`to_id` in Python), label, props, weight, timestamps, and validity window.

Unknown edge labels return an empty array. Tombstoned edges are excluded.

#### Performance

Uses the edge-label posting index to collect matching IDs, then batch-hydrates the matching records. Use [`edges_by_label`](#edges_by_label) when IDs are enough.

---

### count_nodes_by_labels

Returns the count of nodes containing every supplied node label.

```rust
let count: u64 = db.count_nodes_by_labels("User")?;
let admin_count: u64 =
    db.count_nodes_by_labels(vec!["User".into(), "Admin".into()])?;
```

```javascript
const count = db.countNodesByLabels('User');
```

```python
count = db.count_nodes_by_labels("User")
admin_count = db.count_nodes_by_labels(["User", "Admin"])
```

Count uses metadata-only verification and does not hydrate node records or allocate the final ID result vector. Multi-label input always uses `All` semantics. Use [`query_node_ids`](#query_node_ids) with `NodeLabelFilter` when `Any` semantics are needed.

---

### count_edges_by_label

Returns the count of live edges of a given edge label.

**Rust**
```rust
let count: u64 = db.count_edges_by_label("WORKS_ON")?;
```

**Node.js**
```javascript
const count = db.countEdgesByLabel('WORKS_ON');
```

**Python**
```python
count = db.count_edges_by_label("WORKS_ON")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Public edge label to count. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<u64, EngineError>` | `number` | `int` |

Unknown edge labels return `0`. Tombstoned edges are excluded.

#### Performance

Counts through the edge-label posting path without hydrating edge records.

---

## Property Index Management

Property indexes are optional declarations on node or edge properties. Public query methods stay the same whether or not you declare an index.

Lifecycle rules:
- `ensure_node_property_index` registers an equality or numeric range declaration and starts background build work when needed.
- `ensure_edge_property_index` does the same for edge properties, scoped by edge label.
- `list_node_property_indexes` exposes declaration kind, range domain, lifecycle state, and any last error from the published read snapshot, so `Ready` means new public reads can use the same ready catalog.
- `list_edge_property_indexes` exposes the same state for edge declarations.
- `find_nodes`, `find_nodes_paged`, `find_nodes_range`, and `find_nodes_range_paged` use declaration-backed execution only when a matching declaration is `Ready`.
- `query_edge_ids`, `query_edges`, and `query_pattern` may use ready edge-property declarations as candidate sources while still verifying final edge filters.
- If a declaration is absent, `Building`, `Failed`, or cannot be used for a specific lookup, OverGraph falls back to the same public query API for that call.

### ensure_node_property_index

Ensures an optional secondary index declaration for a node property.

**Rust**
```rust
let eq = db.ensure_node_property_index(
    "User",
    "role",
    SecondaryIndexKind::Equality,
)?;

let range = db.ensure_node_property_index(
    "User",
    "score",
    SecondaryIndexKind::Range {
        domain: SecondaryIndexRangeDomain::Int,
    },
)?;
```

**Node.js**
```javascript
const eq = db.ensureNodePropertyIndex('User', 'role', { kind: 'equality' });

const range = db.ensureNodePropertyIndex('User', 'score', {
  kind: 'range',
  domain: 'int',
});
```

**Python**
```python
eq = db.ensure_node_property_index("User", "role", "equality")

range_info = db.ensure_node_property_index(
    "User",
    "score",
    "range",
    domain="int",
)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Restrict the declaration to this node label. |
| prop_key | `&str` | `string` | `str` | Yes | Property key to declare. |
| kind | `SecondaryIndexKind` | `{ kind: string, domain?: string }` | `str` plus optional `domain=` | Yes | Equality declaration or numeric range declaration. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<NodePropertyIndexInfo, EngineError>` | `NodePropertyIndexInfo` | `NodePropertyIndexInfo` |

The current declaration info.

#### Behavior

- Equality declarations use `SecondaryIndexKind::Equality`, `{ kind: 'equality' }`, or `"equality"`.
- Range declarations use `SecondaryIndexKind::Range { domain: ... }`, `{ kind: 'range', domain: 'int' | 'uint' | 'float' }`, or `"range"` plus `domain="int" | "uint" | "float"`.
- Re-ensuring an existing declaration returns the existing declaration info.
- Re-ensuring a `Failed` declaration retries it by moving it back to `Building`.
- A `(label, prop_key)` pair may have at most one range declaration domain. Trying to ensure the same property with a different range domain returns an error.
- A declaration becoming `Ready` is what enables declaration-backed routing. Callers do not switch to a different query method.

---

### drop_node_property_index

Drops an optional node-property secondary index declaration.

**Rust**
```rust
let removed = db.drop_node_property_index(
    "User",
    "role",
    SecondaryIndexKind::Equality,
)?;
```

**Node.js**
```javascript
const removed = db.dropNodePropertyIndex('User', 'role', { kind: 'equality' });
```

**Python**
```python
removed = db.drop_node_property_index("User", "role", "equality")
```

#### Parameters

Same parameters and kind values as [`ensure_node_property_index`](#ensure_node_property_index).

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<bool, EngineError>` | `boolean` | `bool` |

`true` if a declaration existed and was removed, `false` otherwise.

#### Behavior

- Dropping a declaration removes the optional declaration state and subsequent declaration-backed routing for that property.
- Property queries continue to work after a drop. They fall back to scan through the same public query APIs.

---

### list_node_property_indexes

Lists all optional node-property secondary index declarations.

**Rust**
```rust
let indexes = db.list_node_property_indexes()?;
```

**Node.js**
```javascript
const indexes = db.listNodePropertyIndexes();
```

**Python**
```python
indexes = db.list_node_property_indexes()
```

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Vec<NodePropertyIndexInfo>` | `Array<NodePropertyIndexInfo>` | `list[NodePropertyIndexInfo]` |

One entry per declaration.

---

### NodePropertyIndexInfo

User-facing declaration information returned by [`ensure_node_property_index`](#ensure_node_property_index) and [`list_node_property_indexes`](#list_node_property_indexes).

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| index_id | `u64` | `indexId: number` | `index_id: int` | Stable declaration ID. |
| label | `String` | `label: string` | `label: str` | Declared node label. |
| prop_key | `String` | `propKey: string` | `prop_key: str` | Declared property key. |
| kind | `SecondaryIndexKind` | `kind: string` | `kind: str` | `equality` or `range`. |
| domain | Encoded in `SecondaryIndexKind::Range` | `domain?: string` | `domain: str \| None` | Range domain for range declarations. Omitted / `None` for equality. |
| state | `SecondaryIndexState` | `state: string` | `state: str` | `building`, `ready`, or `failed`. |
| last_error | `Option<String>` | `lastError?: string` | `last_error: str \| None` | Most recent build or validation failure, if any. |

State meanings:
- `building`: the declaration exists, but the declaration-backed path is not live yet.
- `ready`: the declaration-backed path has full live coverage and may be used by matching queries.
- `failed`: the declaration could not be built or validated. Matching queries fall back to scan until the declaration is retried or dropped.

---

### ensure_edge_property_index

Ensures an optional secondary index declaration for an edge property, scoped to one edge label.

**Rust**
```rust
let eq = db.ensure_edge_property_index(
    "WORKS_AT",
    "role",
    SecondaryIndexKind::Equality,
)?;

let range = db.ensure_edge_property_index(
    "WORKS_AT",
    "score",
    SecondaryIndexKind::Range {
        domain: SecondaryIndexRangeDomain::Int,
    },
)?;
```

**Node.js**
```javascript
const eq = db.ensureEdgePropertyIndex('WORKS_AT', 'role', { kind: 'equality' });

const range = db.ensureEdgePropertyIndex('WORKS_AT', 'score', {
  kind: 'range',
  domain: 'int',
});
```

**Python**
```python
eq = db.ensure_edge_property_index("WORKS_AT", "role", "equality")

range_info = db.ensure_edge_property_index(
    "WORKS_AT",
    "score",
    "range",
    domain="int",
)
```

Parameters, kind values, lifecycle states, and domain validation match [`ensure_node_property_index`](#ensure_node_property_index), except `label` is the edge label.

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<EdgePropertyIndexInfo, EngineError>` | `EdgePropertyIndexInfo` | `EdgePropertyIndexInfo` |

#### Behavior

- Edge property declarations are edge-label-scoped. A property filter without an edge label cannot use an edge-label-scoped edge-property declaration as a direct-query anchor.
- Ready edge declarations are candidate sources only. `query_edge_ids`, `query_edges`, and graph pattern execution still verify edge metadata and edge property predicates before returning results.
- Direct `EdgeQuery` anchor legality is unchanged: edge property indexes improve planning inside legal direct edge queries, but do not make filter-only direct edge queries legal by themselves.
- Graph patterns may choose a ready edge-property equality or range source as an edge anchor when it is cheaper than node-anchor expansion.

---

### drop_edge_property_index

Drops an optional edge-property secondary index declaration.

**Rust**
```rust
let removed = db.drop_edge_property_index(
    "WORKS_AT",
    "role",
    SecondaryIndexKind::Equality,
)?;
```

**Node.js**
```javascript
const removed = db.dropEdgePropertyIndex('WORKS_AT', 'role', { kind: 'equality' });
```

**Python**
```python
removed = db.drop_edge_property_index("WORKS_AT", "role", "equality")
```

Same parameters and kind values as [`ensure_edge_property_index`](#ensure_edge_property_index). Returns `true` if a declaration existed and was removed, `false` otherwise.

---

### list_edge_property_indexes

Lists all optional edge-property secondary index declarations.

**Rust**
```rust
let indexes = db.list_edge_property_indexes()?;
```

**Node.js**
```javascript
const indexes = db.listEdgePropertyIndexes();
```

**Python**
```python
indexes = db.list_edge_property_indexes()
```

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<EdgePropertyIndexInfo>, EngineError>` | `Array<EdgePropertyIndexInfo>` | `list[EdgePropertyIndexInfo]` |

One entry per edge declaration.

---

### EdgePropertyIndexInfo

User-facing declaration information returned by [`ensure_edge_property_index`](#ensure_edge_property_index) and [`list_edge_property_indexes`](#list_edge_property_indexes).

Fields match [`NodePropertyIndexInfo`](#nodepropertyindexinfo), with the edge-label scope exposed as `label`: `index_id` / `indexId`, `label`, `prop_key` / `propKey`, `kind`, `domain`, `state`, and `last_error` / `lastError`.

---

### PropertyRangeBound

Bound object for [`find_nodes_range`](#find_nodes_range) and [`find_nodes_range_paged`](#find_nodes_range_paged).

**Rust**
```rust
let lower = PropertyRangeBound::Included(PropValue::Int(10));
let upper = PropertyRangeBound::Excluded(PropValue::Int(20));
```

**Node.js**
```javascript
const lower = { value: 10, inclusive: true, domain: 'int' };
const upper = { value: 20, inclusive: false, domain: 'int' };
```

**Python**
```python
lower = PropertyRangeBound(10, domain="int")
upper = PropertyRangeBound(20, inclusive=False, domain="int")
```

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| value | `PropValue` | `value: number` | `value: int \| float` | Numeric bound value. |
| inclusive | Encoded by enum variant | `inclusive?: boolean` | `inclusive: bool` | Inclusive when `true`, exclusive when `false`. |
| domain | Inferred from `PropValue` | `domain: string` | `domain: str` | Required in Node.js and Python. One of `int`, `uint`, or `float`. |

Notes:
- Range queries are domain-specific. There is no implicit coercion between `int`, `uint`, and `float`.
- Both bounds must agree on domain. Paged range cursors must use the same domain too.

---

### PropertyRangeCursor

Cursor object for [`find_nodes_range_paged`](#find_nodes_range_paged). The cursor key is `(value, node_id)`.

**Rust**
```rust
PropertyRangeCursor {
    value: PropValue::Int(20),
    node_id: 42,
}
```

**Node.js**
```javascript
{ value: 20, nodeId: 42, domain: 'int' }
```

**Python**
```python
PropertyRangeCursor(20, 42, domain="int")
```

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| value | `PropValue` | `value: number` | `value: int \| float` | Last value returned on the previous page. |
| node_id | `u64` | `nodeId: number` | `node_id: int` | Last node ID returned at that value. |
| domain | Inferred from `value` | `domain: string` | `domain: str` | Required in Node.js and Python so numeric domains stay explicit. |

---

### PropertyRangePageRequest (Rust only)

Rust request object for [`find_nodes_range_paged`](#find_nodes_range_paged).

```rust
PropertyRangePageRequest {
    limit: Some(100),
    after: None,
}
```

| Field | Rust | Description |
|-------|------|-------------|
| limit | `Option<usize>` | Maximum node IDs to return. `None` means no explicit page size. |
| after | `Option<PropertyRangeCursor>` | Cursor from the previous page. `None` starts at the lower bound. |

---

### PropertyRangePageResult

Result object returned by [`find_nodes_range_paged`](#find_nodes_range_paged).

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `Vec<u64>` | `Float64Array` | `IdArray` | Node IDs in range order for this page. |
| next_cursor | `Option<PropertyRangeCursor>` | `nextCursor?: PropertyRangeCursor` | `next_cursor: PropertyRangeCursor \| None` | Cursor for the next page. Omitted / `None` on the last page. |

---

## Property & Time Queries

Equality and numeric range queries are index-transparent. Callers do not choose indexed versus fallback execution. If a matching optional declaration is `Ready`, OverGraph uses it. Otherwise it scans through the same public query method.

### find_nodes

Finds all nodes with a given label where a specific property matches a given value (exact match).

**Rust**
```rust
let ids = db.find_nodes(
    "User",
    "role",
    &PropValue::String("admin".into()),
)?;
```

**Node.js**
```javascript
const ids = db.findNodes('User', 'role', 'admin'); // Float64Array
```

**Python**
```python
ids = db.find_nodes("User", "role", "admin")  # IdArray
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Restrict search to this node label. |
| prop_key | `&str` | `string` | `str` | Yes | Property key to match on. |
| prop_value | `PropValue` | `any` | `Any` | Yes | Exact value to match. Type must match (string "1" does not match integer 1). |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `IdArray` |

Matching node IDs. If a matching equality declaration is `Ready`, OverGraph uses the declaration-backed index path. Otherwise it scans nodes of the requested label.

---

### find_nodes_range

Finds all nodes with a given label where a numeric property falls within a range.

Results are ordered by `(property_value asc, node_id asc)`.

**Rust**
```rust
let ids = db.find_nodes_range(
    "User",
    "score",
    Some(&PropertyRangeBound::Included(PropValue::Int(10))),
    Some(&PropertyRangeBound::Excluded(PropValue::Int(20))),
)?;
```

**Node.js**
```javascript
const ids = db.findNodesRange(
  'User',
  'score',
  { value: 10, inclusive: true, domain: 'int' },
  { value: 20, inclusive: false, domain: 'int' },
);
```

**Python**
```python
ids = db.find_nodes_range(
    "User",
    "score",
    PropertyRangeBound(10, domain="int"),
    PropertyRangeBound(20, inclusive=False, domain="int"),
)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Restrict search to this node label. |
| prop_key | `&str` | `string` | `str` | Yes | Numeric property key to query. |
| lower | `Option<&PropertyRangeBound>` | `PropertyRangeBound \| null \| undefined` | `PropertyRangeBound \| None` | No | Lower bound. Omit for an unbounded start. |
| upper | `Option<&PropertyRangeBound>` | `PropertyRangeBound \| null \| undefined` | `PropertyRangeBound \| None` | No | Upper bound. Omit for an unbounded end. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `IdArray` |

Matching node IDs in range order.

#### Behavior

- At least one bound is required.
- Numeric domains are exact. `int`, `uint`, and `float` are separate query domains.
- If both bounds are present, they must use the same domain.
- If a matching range declaration is `Ready`, OverGraph uses the declaration-backed range path.
- If no matching `Ready` declaration exists, OverGraph falls back to a scan of nodes of the requested label.
- Invalid bound combinations return an error.

---

### find_nodes_by_time_range

Finds all nodes with a given label and `updated_at` within a time range.

```rust
let ids = db.find_nodes_by_time_range("User", start_ms, end_ms)?;
```

```javascript
const ids = db.findNodesByTimeRange('User', startMs, endMs);
```

```python
ids = db.find_nodes_by_time_range("User", start_ms, end_ms)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| label | `&str` | `string` | `str` | Yes | Node label. |
| from_ms | `i64` | `number` | `int` | Yes | Start of range (inclusive), ms since epoch. |
| to_ms | `i64` | `number` | `int` | Yes | End of range (inclusive), ms since epoch. |

#### Returns

Node IDs matching the time range. Uses the timestamp index.

---

## Queries

Query APIs combine explicit IDs, label-scoped keys, label/edge-label constraints, property filters, timestamp filters, and
bounded graph patterns through normal function-call and object APIs. OverGraph still has no query
string parser.

Query APIs return matching IDs, hydrated records, or bounded pattern ID bindings only.
Projection/query-row result APIs are not part of this surface.

Node queries use a recursive `filter` tree.

Top-level request fields such as node `label_filter`, edge `label`, `ids`, and `keys` are not part of the
filter tree. They are top-level constraints and are ANDed with the filter. Within `ids` and
`keys`, values are OR alternatives.

Use `filter` for all node and edge predicates.

Query APIs use the same published read snapshot and visibility rules as direct read APIs.
Internally, OverGraph may use explicit IDs, key lookup, the node-label index, ready property
equality/range indexes, the timestamp index, sorted intersection, sorted union, fallback scans, or
bounded adjacency expansion. Candidate indexes are verified after candidate planning; indexes are
never trusted as final truth.

OverGraph may also use private durable planner statistics when they are available. These stats can
improve cost estimates, adaptive caps, OR/IN costing, and graph-pattern fanout ordering, but they do
not change request shapes or result semantics. Missing, corrupt, or stale stats only degrade
planning quality; every returned result is still verified against the visible record.

### What Query APIs Are

Node queries are the API-first query surface for combining top-level constraints with a recursive
node `filter` tree. They are useful when a request needs more than one constraint, when an index may
help but should remain optional, or when the same filter should be explained.

Direct edge queries and graph pattern edge constraints use the canonical edge `filter` tree for
edge metadata and property predicates. Maintained edge-property indexes are used when available;
otherwise predicates are verified over the planned edge universe.

### Choosing the Right Query API

Use [`query_node_ids`](#query_node_ids) when you need matching IDs and want OverGraph to combine
top-level constraints with a node filter tree.

Use [`query_nodes`](#query_nodes) for the same query shape when you need hydrated node records. It
shares the same plan and verifier as `query_node_ids`; only the final payload differs.

Use [`explain_node_query`](#explain_node_query) to inspect the selected physical plan and warnings
without executing the page.

Use [`query_edge_ids`](#query_edge_ids) when you need matching edge IDs from explicit edge IDs, edge-label
constraints, endpoint constraints, or an explicit full-scan opt-in.

Use [`query_edges`](#query_edges) for the same edge query shape when you need hydrated edge records.
Metadata-only filters hydrate only the final page. Property filters hydrate bounded verifier
candidates.

Use [`explain_edge_query`](#explain_edge_query) to inspect direct edge query planning.

Use direct property and time queries such as [`find_nodes`](#find_nodes),
[`find_nodes_range`](#find_nodes_range), and
[`find_nodes_by_time_range`](#find_nodes_by_time_range) when you already know you need one direct
indexed lookup or range lookup. Those APIs keep their existing shapes.

Use [`query_pattern`](#query_pattern) when the result is a bounded graph pattern binding across
nodes and edges.

### Node Queries

#### query_node_ids

Runs a node query and returns matching node IDs.

**Rust**
```rust
let page = db.query_node_ids(&NodeQuery {
    label_filter: Some(NodeLabelFilter {
        labels: vec!["User".into()],
        mode: LabelMatchMode::All,
    }),
    filter: Some(NodeFilterExpr::And(vec![
        NodeFilterExpr::PropertyEquals {
            key: "status".into(),
            value: PropValue::String("active".into()),
        },
        NodeFilterExpr::PropertyRange {
            key: "score".into(),
            lower: Some(PropertyRangeBound::Included(PropValue::Int(50))),
            upper: None,
        },
    ])),
    page: PageRequest { limit: Some(100), after: None },
    ..Default::default()
})?;
```

**Node.js**
```javascript
const page = db.queryNodeIds({
  labelFilter: { labels: ['User'], mode: 'all' },
  filter: {
    and: [
      { property: 'status', eq: 'active' },
      { property: 'score', gte: 50 },
    ],
  },
  limit: 100,
});
```

**Python**
```python
page = db.query_node_ids({
    "label_filter": {"labels": ["User"], "mode": "all"},
    "filter": {
        "and": [
            {"property": "status", "eq": "active"},
            {"property": "score", "gte": 50},
        ],
    },
    "limit": 100,
})
```

##### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| request | `&NodeQuery` | `QueryNodeRequest` | `dict \| NodeQueryRequest` | Yes | Node query request. See [NodeQuery](#nodequery). |

##### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<QueryNodeIdsResult, EngineError>` | `IdPageResult` | `IdPageResult` |

Result fields:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `items: Vec<u64>` | `items: Float64Array` | `items: IdArray` | Matching node IDs in ascending node ID order. |
| cursor | `next_cursor: Option<u64>` | `nextCursor?: number` | `next_cursor: int \| None` | Cursor for the next page. Pass it as `after`. |

---

#### query_nodes

Runs the same node query as [`query_node_ids`](#query_node_ids), then hydrates the final page of
matching nodes.

**Rust**
```rust
let page = db.query_nodes(&NodeQuery {
    label_filter: Some(NodeLabelFilter {
        labels: vec!["Document".into(), "Published".into()],
        mode: LabelMatchMode::All,
    }),
    filter: Some(NodeFilterExpr::PropertyEquals {
        key: "status".into(),
        value: PropValue::String("active".into()),
    }),
    page: PageRequest { limit: Some(25), after: None },
    ..Default::default()
})?;
```

**Node.js**
```javascript
const page = db.queryNodes({
  labelFilter: { labels: ['Document', 'Published'], mode: 'all' },
  filter: {
    and: [
      { property: 'status', in: ['active', 'trial'] },
      { not: { property: 'archivedAt', exists: true } },
      {
        or: [
          { property: 'priority', gte: 8 },
          { property: 'source', eq: 'user' },
        ],
      },
    ],
  },
  limit: 25,
});
```

**Python**
```python
page = db.query_nodes({
    "label_filter": {"labels": ["Document", "Published"], "mode": "all"},
    "filter": {
        "and": [
            {"property": "status", "in": ["active", "trial"]},
            {"not": {"property": "archived_at", "exists": True}},
            {
                "or": [
                    {"property": "priority", "gte": 8},
                    {"property": "source", "eq": "user"},
                ],
            },
        ],
    },
    "limit": 25,
})
```

##### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| request | `&NodeQuery` | `QueryNodeRequest` | `dict \| NodeQueryRequest` | Yes | Node query request. See [NodeQuery](#nodequery). |

##### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<QueryNodesResult, EngineError>` | `NodePageResult` | `NodePageResult` |

Result fields:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `items: Vec<NodeView>` | `items: NodeView[]` | `items: list[NodeView]` | Hydrated final page of matching nodes. |
| cursor | `next_cursor: Option<u64>` | `nextCursor: number \| null` | `next_cursor: int \| None` | Cursor for the next page. Pass it as `after`. |

Connector node records expose top-level fields eagerly. Property maps are converted only when the
`.props` getter is accessed.

---

#### explain_node_query

Returns the deterministic planner tree, estimates, and warnings for a node query. It applies the
same validation rules as execution.

**Rust**
```rust
let plan = db.explain_node_query(&query)?;
```

**Node.js**
```javascript
const plan = db.explainNodeQuery({
  labelFilter: { labels: ['User'], mode: 'all' },
  filter: { property: 'status', eq: 'active' },
});
```

**Python**
```python
plan = db.explain_node_query({
    "label_filter": {"labels": ["User"], "mode": "all"},
    "filter": {"property": "status", "eq": "active"},
})
```

##### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<QueryPlan, EngineError>` | `object` | `dict` |

See [QueryPlan](#queryplan).

---

### Direct Edge Queries

#### query_edge_ids

Runs a direct edge query and returns matching edge IDs in ascending edge ID order.

**Rust**
```rust
let page = db.query_edge_ids(&EdgeQuery {
    label: Some("WORKS_AT".into()),
    from_ids: vec![person_id],
    filter: Some(EdgeFilterExpr::And(vec![
        EdgeFilterExpr::WeightRange { lower: Some(1.0), upper: None },
        EdgeFilterExpr::ValidAt { epoch_ms },
    ])),
    page: PageRequest { limit: Some(100), after: None },
    ..Default::default()
})?;
```

**Node.js**
```javascript
const page = db.queryEdgeIds({
  label: 'WORKS_AT',
  fromIds: [personId],
  filter: {
    and: [
      { weight: { gte: 1.0 } },
      { validAt: epochMs },
    ],
  },
  limit: 100,
});
```

**Python**
```python
page = db.query_edge_ids({
    "label": "WORKS_AT",
    "from_ids": [person_id],
    "filter": {
        "and": [
            {"weight": {"gte": 1.0}},
            {"valid_at": epoch_ms},
        ],
    },
    "limit": 100,
})
```

#### query_edges

Runs the same direct edge query as [`query_edge_ids`](#query_edge_ids), then hydrates the final page
of matching edge records.

**Node.js**
```javascript
const page = db.queryEdges({
  label: 'WORKS_AT',
  endpointIds: [personId],
  filter: { property: 'role', eq: 'lead' },
  limit: 25,
});
```

**Python**
```python
page = db.query_edges({
    "label": "WORKS_AT",
    "endpoint_ids": [person_id],
    "filter": {"property": "role", "eq": "lead"},
    "limit": 25,
})
```

#### explain_edge_query

Returns the deterministic planner tree, estimates, and warnings for a direct edge query.

**Rust**
```rust
let plan = db.explain_edge_query(&query)?;
```

**Node.js**
```javascript
const plan = db.explainEdgeQuery({ label: 'WORKS_AT', fromIds: [personId] });
```

**Python**
```python
plan = db.explain_edge_query({"label": "WORKS_AT", "from_ids": [person_id]})
```

##### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<QueryEdgeIdsResult, EngineError>` | `IdPageResult` | `IdPageResult` |
| `Result<QueryEdgesResult, EngineError>` | `EdgePageResult` | `EdgePageResult` |
| `Result<QueryPlan, EngineError>` | `object` | `dict` |

Rust `QueryEdgeIdsResult` contains `edge_ids: Vec<u64>` and `next_cursor: Option<u64>`. Rust `QueryEdgesResult` contains `edges: Vec<EdgeView>` and `next_cursor: Option<u64>`. Node.js and Python page result objects use `items` for the returned IDs or edges.

---

### Graph Pattern Queries

#### query_pattern

Runs a bounded, connected graph pattern query and returns ID bindings for node and named edge
aliases. Pattern v1 returns IDs only. Hydrate bound IDs with [`get_nodes`](#get_nodes) and
[`get_edges`](#get_edges) when needed.

Node patterns use the same recursive `filter` tree as node queries. Edge patterns use canonical
`filter` with the same shape as direct edge queries. Edge pattern `label_filter` is a simple
edge-label list, not a `NodeLabelFilter`.

**Rust**
```rust
let result = db.query_pattern(&GraphPatternQuery {
    nodes: vec![
        NodePattern {
            alias: "person".into(),
            label_filter: Some(NodeLabelFilter {
                labels: vec!["User".into(), "Admin".into()],
                mode: LabelMatchMode::All,
            }),
            ids: vec![],
            keys: vec![],
            filter: Some(NodeFilterExpr::Or(vec![
                NodeFilterExpr::PropertyEquals {
                    key: "status".into(),
                    value: PropValue::String("active".into()),
                },
                NodeFilterExpr::PropertyEquals {
                    key: "status".into(),
                    value: PropValue::String("trial".into()),
                },
            ])),
        },
        NodePattern {
            alias: "company".into(),
            label_filter: Some(NodeLabelFilter {
                labels: vec!["Company".into()],
                mode: LabelMatchMode::All,
            }),
            ids: vec![],
            keys: vec!["acme".into()],
            filter: None,
        },
    ],
    edges: vec![EdgePattern {
        alias: Some("employment".into()),
        from_alias: "person".into(),
        to_alias: "company".into(),
        direction: Direction::Outgoing,
        label_filter: vec!["WORKS_AT".into()],
        filter: Some(EdgeFilterExpr::PropertyEquals {
            key: "role".into(),
            value: PropValue::String("engineer".into()),
        }),
    }],
    at_epoch: None,
    limit: 100,
    order: PatternOrder::AnchorThenAliasesAsc,
})?;
```

**Node.js**
```javascript
const result = db.queryPattern({
  nodes: [
    {
      alias: 'person',
      labelFilter: { labels: ['User'], mode: 'all' },
      filter: {
        or: [
          { property: 'status', eq: 'active' },
          { property: 'status', eq: 'trial' },
        ],
      },
    },
    {
      alias: 'company',
      labelFilter: { labels: ['Company'], mode: 'all' },
      keys: ['acme'],
    },
  ],
  edges: [
    {
      alias: 'employment',
      fromAlias: 'person',
      toAlias: 'company',
      direction: 'outgoing',
      labelFilter: ['WORKS_AT'],
      filter: { property: 'role', eq: 'engineer' },
    },
  ],
  limit: 100,
});
```

**Python**
```python
result = db.query_pattern({
    "nodes": [
        {
            "alias": "person",
            "label_filter": {"labels": ["User"], "mode": "all"},
            "filter": {
                "or": [
                    {"property": "status", "eq": "active"},
                    {"property": "status", "eq": "trial"},
                ],
            },
        },
        {
            "alias": "company",
            "label_filter": {"labels": ["Company"], "mode": "all"},
            "keys": ["acme"],
        },
    ],
    "edges": [
        {
            "alias": "employment",
            "from_alias": "person",
            "to_alias": "company",
            "direction": "outgoing",
            "label_filter": ["WORKS_AT"],
            "filter": {"property": "role", "eq": "engineer"},
        },
    ],
    "limit": 100,
})
```

##### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| request | `&GraphPatternQuery` | `GraphPatternRequest` | `dict \| GraphPatternRequest` | Yes | Pattern request. See [GraphPatternQuery](#graphpatternquery). |

##### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<QueryPatternResult, EngineError>` | `object` | `dict` |

Result fields:

| Field | Description |
|-------|-------------|
| matches | List of bindings. Each binding has `nodes` and `edges` maps keyed by alias. |
| truncated | `true` when more matches existed than the requested `limit`. |

---

#### explain_pattern_query

Returns the plan for a graph pattern query without executing the match. Pattern explain reports
the selected anchor alias and the actual node-query physical plan used for that anchor.

**Rust**
```rust
let plan = db.explain_pattern_query(&pattern)?;
```

**Node.js**
```javascript
const plan = db.explainPatternQuery(pattern);
```

**Python**
```python
plan = db.explain_pattern_query(pattern)
```

##### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<QueryPlan, EngineError>` | `object` | `dict` |

See [QueryPlan](#queryplan).

Node.js and Python async APIs expose the same query and explain request shapes through
`queryNodeIdsAsync`, `queryNodesAsync`, `queryPatternAsync`, `explainNodeQueryAsync`,
`explainPatternQueryAsync`, and the Python `AsyncOverGraph` methods.

---

### Query Request Types and Plans

#### NodeQuery

Node query request fields:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| label_filter / labelFilter | `Option<NodeLabelFilter>` | `labelFilter?: { labels: string[], mode: "any" \| "all" }` | `label_filter?: {"labels": list[str], "mode": "any" \| "all"}` | Node-label constraint with explicit `Any` / `All` semantics. A one-label `All` filter uses the single-label fast path. |
| ids | `Vec<u64>` | `ids?: number[]` | `ids?: list[int]` | Explicit node ID candidates. OR within the list. |
| keys | `Vec<String>` | `keys?: string[]` | `keys?: list[str]` | Label-scoped key candidates. OR within the list. |
| filter | `Option<NodeFilterExpr>` | `filter?: QueryNodeFilter \| null` | `filter?: QueryNodeFilter \| None` | Recursive node filter tree. Omit or pass null/None for no filter. |
| limit | `page.limit` | `limit?: number` | `limit?: int` | Page size. Omit for unlimited. Connector `0` means unlimited. |
| after | `page.after` | `after?: number` | `after?: int` | Cursor from a previous page. Returns items with node IDs strictly greater than `after`. |
| allow_full_scan | `bool` | `allowFullScan?: boolean` | `allow_full_scan?: bool` | Required for unanchored full scan fallback. |

Top-level `label_filter` / `labelFilter`, `ids`, and `keys` are ANDed with `filter`.
A one-label `All` filter uses the direct node-label fast path. Key lookups require exactly one resolved node label.
Label-less verify-only filters require `allow_full_scan` / `allowFullScan` unless `ids` or `keys`
provide a legal bounded universe.

---

#### NodeFilter / QueryNodeFilter

Rust uses `NodeFilterExpr`. Node.js and Python use the canonical recursive `QueryNodeFilter`
object shape.

| Filter shape | Node.js | Python | Meaning |
|--------------|---------|--------|---------|
| Equality | `{ property: "status", eq: "active" }` | `{"property": "status", "eq": "active"}` | Property exactly equals value |
| IN | `{ property: "status", in: ["active", "trial"] }` | `{"property": "status", "in": ["active", "trial"]}` | Property equals any listed value |
| Range | `{ property: "score", gte: 50 }` | `{"property": "score", "gte": 50}` | Numeric/range comparison |
| Range with two bounds | `{ property: "score", gt: 50, lte: 100 }` | `{"property": "score", "gt": 50, "lte": 100}` | Bounded numeric/range comparison |
| Exists | `{ property: "embedding", exists: true }` | `{"property": "embedding", "exists": True}` | Property key is present |
| Missing | `{ property: "deletedAt", missing: true }` | `{"property": "deleted_at", "missing": True}` | Property key is absent |
| AND | `{ and: [filter, ...] }` | `{"and": [filter, ...]}` | All children must match |
| OR | `{ or: [filter, ...] }` | `{"or": [filter, ...]}` | Any child may match |
| NOT | `{ not: filter }` | `{"not": filter}` | Child must not match |
| Updated-at range | `{ updatedAt: { gte: ms } }` | `{"updated_at": {"gte": ms}}` | Built-in node `updated_at` timestamp range |

Property values use OverGraph's normal `PropValue` conversion rules. There is no query-only
coercion. For example, string `"1"` does not match integer `1`, and integer `1` does not
automatically match float `1.0`.

`in` is equivalent to equality OR for matching semantics. When a ready equality index exists, the
query engine may evaluate it as an indexed union, but final visible-record verification still decides
correctness.

`exists` and `missing` are key-presence predicates, not null checks. `exists` matches when the
property key is present even if its value is null. `missing` matches only when the key is absent.

`not` is verifier-first. A negative filter does not anchor a broad query by itself.

`or` can use an indexed union only when every branch is bounded. If any OR branch is verify-only or
requires fallback, the whole OR subtree is verified over the nearest legal universe rather than
planned as a partial union.

Results from node queries are ordered by node ID ascending. The `after` cursor means strictly
greater than that node ID.

##### Built-in timestamp versus same-named user property

The built-in timestamp filter is a structural field. User property names always live in the
`property` value field, so they do not collide with built-ins.

**Node.js**
```javascript
// Built-in node timestamp:
db.queryNodeIds({
  labelFilter: { labels: ['Document'], mode: 'all' },
  filter: { updatedAt: { gte: startMs, lt: endMs } },
});

// User property literally named "updatedAt":
db.queryNodeIds({
  labelFilter: { labels: ['Document'], mode: 'all' },
  filter: { property: 'updatedAt', eq: 'manual-value' },
});
```

**Python**
```python
# Built-in node timestamp:
db.query_node_ids({
    "label_filter": {"labels": ["Document"], "mode": "all"},
    "filter": {"updated_at": {"gte": start_ms, "lt": end_ms}},
})

# User property literally named "updated_at":
db.query_node_ids({
    "label_filter": {"labels": ["Document"], "mode": "all"},
    "filter": {"property": "updated_at", "eq": "manual-value"},
})
```

---

#### EdgeQuery

Direct edge query request fields:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| label | `Option<String>` | `label?: string` | `label?: str` | Optional edge-label constraint. |
| ids | `Vec<u64>` | `ids?: number[]` | `ids?: list[int]` | Explicit edge ID candidates. OR within the list. |
| from_ids | `Vec<u64>` | `fromIds?: number[]` | `from_ids?: list[int]` | Source endpoint candidates. OR within the list. |
| to_ids | `Vec<u64>` | `toIds?: number[]` | `to_ids?: list[int]` | Target endpoint candidates. OR within the list. |
| endpoint_ids | `Vec<u64>` | `endpointIds?: number[]` | `endpoint_ids?: list[int]` | Either-endpoint candidates. OR within the list. |
| filter | `Option<EdgeFilterExpr>` | `filter?: QueryEdgeFilter \| null` | `filter?: QueryEdgeFilter \| None` | Recursive edge filter tree. |
| limit | `page.limit` | `limit?: number` | `limit?: int` | Page size. Omit for unlimited. Connector `0` means unlimited. |
| after | `page.after` | `after?: number` | `after?: int` | Cursor from a previous page. Returns edge IDs strictly greater than `after`. |
| allow_full_scan | `bool` | `allowFullScan?: boolean` | `allow_full_scan?: bool` | Required for direct filter-only or unanchored full scans. |

Top-level edge anchors are ANDed with `filter`; values inside each list are ORed. A filter-only
direct edge query requires explicit full-scan opt-in even when metadata sidecars are available.

---

#### EdgeFilter / QueryEdgeFilter

Rust uses `EdgeFilterExpr`. Node.js and Python use the canonical recursive `QueryEdgeFilter`
object shape.

| Filter shape | Node.js | Python | Meaning |
|--------------|---------|--------|---------|
| Equality | `{ property: "role", eq: "lead" }` | `{"property": "role", "eq": "lead"}` | Edge property exactly equals value |
| IN | `{ property: "role", in: ["lead", "owner"] }` | `{"property": "role", "in": ["lead", "owner"]}` | Edge property equals any listed value |
| Range | `{ property: "score", gte: 50 }` | `{"property": "score", "gte": 50}` | Edge property range comparison |
| Exists | `{ property: "role", exists: true }` | `{"property": "role", "exists": True}` | Edge property key is present |
| Missing | `{ property: "role", missing: true }` | `{"property": "role", "missing": True}` | Edge property key is absent |
| Weight range | `{ weight: { gte: 1.0 } }` | `{"weight": {"gte": 1.0}}` | Built-in edge weight range |
| Updated-at range | `{ updatedAt: { gte: ms } }` | `{"updated_at": {"gte": ms}}` | Built-in edge update timestamp range |
| Valid-at | `{ validAt: ms }` | `{"valid_at": ms}` | Half-open validity check: `valid_from <= ms < valid_to` |
| Valid-from range | `{ validFrom: { gte: ms } }` | `{"valid_from": {"gte": ms}}` | Built-in `valid_from` range |
| Valid-to range | `{ validTo: { gt: ms } }` | `{"valid_to": {"gt": ms}}` | Built-in `valid_to` range |
| AND | `{ and: [filter, ...] }` | `{"and": [filter, ...]}` | All children must match |
| OR | `{ or: [filter, ...] }` | `{"or": [filter, ...]}` | Any child may match |
| NOT | `{ not: filter }` | `{"not": filter}` | Child must not match |

Weight ranges reject NaN. `-0.0` and `+0.0` compare as the same value. Ready edge-property
declarations may provide equality, `IN`, and range candidate sources for edge-label-scoped edge filters;
metadata filters may use private edge metadata sources when available. All edge filters still run
final verification for correctness.

---

#### GraphPatternQuery

Pattern request fields:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| nodes | `Vec<NodePattern>` | `nodes` | `nodes` | Node aliases and constraints. At least one required. |
| edges | `Vec<EdgePattern>` | `edges` | `edges` | Edge constraints between node aliases. At least one required for pattern v1. |
| at_epoch | `Option<i64>` | `atEpoch?: number` | `at_epoch?: int` | Optional temporal edge visibility timestamp. |
| limit | `usize` | `limit: number` | `limit: int` | Required positive match limit. |
| order | `PatternOrder` | implicit | implicit | `AnchorThenAliasesAsc` in v1. |

Node pattern fields:

| Field | Description |
|-------|-------------|
| alias | Non-empty unique node alias. |
| label_filter | `NodeLabelFilter` with explicit `Any` / `All` semantics. A one-label `All` filter uses the single-label fast path. |
| ids | Explicit node IDs. |
| keys | Label-scoped keys. Requires exactly one resolved node label from `label_filter`. |
| filter | Recursive node filter tree. Omit/null/None means no node filter. |

Edge pattern fields:

| Field | Description |
|-------|-------------|
| alias | Optional unique edge alias. Unnamed edges are constraints only. |
| from_alias / fromAlias | Source alias in the pattern direction. |
| to_alias / toAlias | Target alias in the pattern direction. |
| direction | `outgoing`, `incoming`, or `both`, relative to `from_alias`. |
| label_filter / labelFilter | Optional edge-label list. |
| filter | Canonical recursive edge filter tree. |

Pattern validation:

- Aliases must be unique and non-empty.
- Every edge endpoint must reference a declared node alias.
- Pattern v1 must be one connected component with at least one edge.
- Distinct node aliases bind distinct node IDs.
- Reusing the same alias in multiple edges means the same node binding.
- Unbounded initial nodes without a legal bounded universe are rejected. A label-less verify-only
  target filter is legal only after bounded edge expansion has produced target IDs.
- Edge `filter` is canonical.

---

#### QueryPlan

Explain APIs return:

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| kind | `kind` | `kind` | `kind` | `node_query`, `edge_query`, or `pattern_query`. |
| root | `root` | `root` | `root` | Recursive plan node. |
| estimated candidates | `estimated_candidates` | `estimatedCandidates` | `estimated_candidates` | Optional candidate count estimate. |
| warnings | `warnings` | `warnings` | `warnings` | Stable lower_snake warning strings. |
| notes | `notes` | `notes` | `notes` | Stable lower_snake informational planner notes. |
| public inputs | `public_inputs` | `publicInputs` | `public_inputs` | Normalized public node-label and edge-label names referenced during planning. |

Plan node kinds include:

| Plan node kind | Meaning |
|----------------|---------|
| `empty_result` | Impossible filter or empty candidate universe. |
| `explicit_ids` | Explicit ID candidate universe. |
| `key_lookup` | Label-scoped key lookup. |
| `node_label_index` | Label index candidate source. |
| `node_label_any_index` | Node-label `Any` candidate source. |
| `property_equality_index` | Ready equality property index candidate source. |
| `property_range_index` | Ready range property index candidate source. |
| `timestamp_index` | Built-in timestamp index candidate source. |
| `explicit_edge_ids` | Explicit edge ID candidate universe. |
| `edge_label_index` | Edge label index candidate source. |
| `edge_triple_index` | Exact `(from, to, label)` edge lookup source. |
| `edge_endpoint_adjacency` | Endpoint adjacency candidate source. |
| `edge_weight_index` | Optional edge weight sidecar candidate source. |
| `edge_updated_at_index` | Optional edge update-time sidecar candidate source. |
| `edge_validity_index` | Optional edge validity sidecar candidate source. |
| `edge_metadata_scan` | Edge metadata scan candidate source. |
| `edge_property_equality_index` | Ready edge-property equality declaration candidate source. |
| `edge_property_range_index` | Ready edge-property range declaration candidate source. |
| `intersect` | Sorted intersection of bounded candidate sources. |
| `union` | Sorted union of bounded OR/IN candidate sources. |
| `verify_node_filter` | Final visible-record verification of the full node filter. |
| `verify_edge_filter` | Final visible-edge metadata/property verification. |
| `adjacency_expansion` | Bounded graph-pattern edge expansion. |
| `pattern_expand` | Pattern execution expansion step. |
| `pattern_edge_anchor` | Pattern execution started from a planned edge source. |
| `verify_edge_predicates` | Edge post-filter verification. |
| `fallback_node_label_scan` | Label-scoped scan universe. |
| `fallback_full_node_scan` | Explicit full node scan universe. |
| `fallback_edge_label_scan` | Edge-label-scoped edge scan universe. |
| `fallback_full_edge_scan` | Explicit full edge scan universe. |

Warning strings include:

| Warning | Meaning |
|---------|---------|
| `missing_ready_index` | Needed index is absent, not ready, or unavailable. |
| `using_fallback_scan` | Query used a scan universe. |
| `full_scan_requires_opt_in` | Query would need a full scan but the caller did not opt in. |
| `full_scan_explicitly_allowed` | Full scan ran because caller opted in. |
| `unbounded_pattern_rejected` | Pattern was not safely bounded. |
| `edge_property_post_filter` | Edge properties were checked after bounded expansion. |
| `index_skipped_as_broad` | Ready index existed but was skipped as too broad. |
| `candidate_cap_exceeded` | Candidate cap prevented materializing a source. |
| `range_candidate_cap_exceeded` | Range candidate cap prevented bounded range materialization. |
| `timestamp_candidate_cap_exceeded` | Timestamp candidate cap prevented bounded timestamp materialization. |
| `verify_only_filter` | Some filter subtree ran only through verification. |
| `boolean_branch_fallback` | Boolean branch or OR was cheaper or safer as verifier fallback. |
| `planning_probe_budget_exceeded` | Planning probe/union budget forced fallback. |
| `unknown_node_label` | A requested node label is not present in the catalog. |
| `unknown_edge_label` | A requested edge label is not present in the catalog. |

Note strings include:

| Note | Meaning |
|------|---------|
| `node_label_any_dedupe_before_pagination` | `Any` node-label planning deduplicates candidates before pagination. |
| `node_label_any_final_verification` | `Any` node-label results are verified against final visible node records. |
| `node_label_all_superset_verification` | `All` node-label planning used a superset index source followed by final verification. |
| `stale_node_label_membership_verification` | Node-label index membership may include stale entries and is verified against visible records. |

---

#### Validation notes

Invalid filter shapes:

| Invalid shape | Why |
|---------------|-----|
| `{}` | Empty filter object is not a valid filter. |
| `{ and: [] }` | `and` must contain at least one child. |
| `{ or: [] }` | `or` must contain at least one child. |
| `{ not: null }` | `not` must contain exactly one filter object. |
| `{ AND: [...] }` | Uppercase boolean aliases are not supported. |
| `{ property: "", eq: "active" }` | Property key must be non-empty. |
| `{ eq: "active" }` | Property leaves require `property`. |
| `{ property: "status" }` | Property leaf must specify one operator family. |
| `{ property: "status", eq: "active", in: ["active"] }` | Mixed operator families are invalid. |
| `{ property: "status", in: [] }` | `in` list must be non-empty. |
| `{ property: "x", exists: false }` | `exists` only accepts true; use `missing: true` for the opposite. |
| `{ property: "x", missing: false }` | `missing` only accepts true; use `exists: true` for the opposite. |
| `{ property: "score", gt: 1, gte: 1 }` | Cannot specify both exclusive and inclusive lower bounds. |
| `{ updatedAt: { eq: 123 } }` | Updated-at filters support range bounds only. |

`filter` omitted/null/undefined/None means no node filter. `filter: {}` is invalid.

Boolean objects cannot contain sibling tags. For example, `{ and: [...], or: [...] }` and
`{ and: [...], property: "x", eq: 1 }` are invalid. No uppercase boolean or operator aliases are
accepted.

---

## Pagination

All paginated methods use **keyset (cursor-based) pagination**, not offset-based. This provides stable results even when data is inserted between pages.

The pattern is the same across all paginated methods:
- Pass `limit` for the page size and `after` as the cursor.
- Most paginated methods use an ID cursor.
- `find_nodes_range_paged` uses a structured range cursor keyed by `(value, node_id)`.
- The result includes `items` and `next_cursor` (`None`/`null` when there are no more pages).

### nodes_by_labels_paged

Paginated node-label scan. Returns IDs only.

```rust
let page = db.nodes_by_labels_paged("User", &PageRequest { limit: Some(100), after: None })?;
let admin_page = db.nodes_by_labels_paged(
    vec!["User".into(), "Admin".into()],
    &PageRequest { limit: Some(100), after: None },
)?;
// page.items: Vec<u64>, page.next_cursor: Option<u64>
```

```javascript
let page = db.nodesByLabelsPaged('User', 100); // limit=100, no cursor
let adminPage = db.nodesByLabelsPaged(['User', 'Admin'], 100);
// page = { items: Float64Array, nextCursor: number | null }

// Next page:
page = db.nodesByLabelsPaged('User', 100, page.nextCursor);
```

```python
page = db.nodes_by_labels_paged("User", limit=100)
admin_page = db.nodes_by_labels_paged(["User", "Admin"], limit=100)
# page.items: IdArray, page.next_cursor: int | None

# Next page:
page = db.nodes_by_labels_paged("User", limit=100, after=page.next_cursor)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| labels | `impl IntoNodeLabels` | `string \| string[]` | `str \| list[str]` | Yes | — | Label or labels to match. Nodes must contain every supplied node label. |
| limit | `Option<usize>` | `number` | `int` | No | Unlimited | Maximum items per page. |
| after | `Option<u64>` | `number` | `int` | No | `None` (start from beginning) | Cursor. Returns items with IDs strictly greater than this value. Use `next_cursor` from a previous result. |

#### Returns: PageResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `Vec<u64>` | `Float64Array` | `IdArray` | IDs in this page. |
| next_cursor | `Option<u64>` | `number \| null` | `int \| None` | Cursor for the next page. `None`/`null` means this is the last page. |

---

### edges_by_label_paged

Paginated edge-label scan. Returns edge IDs only.

```rust
let page = db.edges_by_label_paged(
    "WORKS_ON",
    &PageRequest { limit: Some(100), after: None },
)?;
// page.items: Vec<u64>, page.next_cursor: Option<u64>
```

```javascript
let page = db.edgesByLabelPaged('WORKS_ON', 100); // limit=100, no cursor
// page = { items: Float64Array, nextCursor: number | null }

// Next page:
page = db.edgesByLabelPaged('WORKS_ON', 100, page.nextCursor);
```

```python
page = db.edges_by_label_paged("WORKS_ON", limit=100)
# page.items: IdArray, page.next_cursor: int | None

# Next page:
page = db.edges_by_label_paged("WORKS_ON", limit=100, after=page.next_cursor)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| label | `&str` | `string` | `str` | Yes | - | Public edge label to match. |
| limit | `Option<usize>` | `number` | `int` | No | Unlimited | Maximum edge IDs per page. |
| after | `Option<u64>` | `number` | `int` | No | `None` (start from beginning) | Cursor. Returns edge IDs strictly greater than this value. Use `next_cursor` from a previous result. |

#### Returns: PageResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `Vec<u64>` | `Float64Array` | `IdArray` | Edge IDs in this page. |
| next_cursor | `Option<u64>` | `number \| null` | `int \| None` | Cursor for the next page. `None`/`null` means this is the last page. |

Unknown edge labels return an empty page. Tombstoned edges are excluded. Paged edge-label scans are ordered by edge ID.

---

### get_nodes_by_labels_paged

Paginated hydrated node-label scan. Returns full node records.

```rust
let page = db.get_nodes_by_labels_paged("User", &PageRequest { limit: Some(50), after: None })?;
let admin_page = db.get_nodes_by_labels_paged(
    vec!["User".into(), "Admin".into()],
    &PageRequest { limit: Some(50), after: None },
)?;
// page.items: Vec<NodeView>
```

```javascript
const page = db.getNodesByLabelsPaged('User', 50);
const adminPage = db.getNodesByLabelsPaged(['User', 'Admin'], 50);
// page.items: NodeView[]
```

```python
page = db.get_nodes_by_labels_paged("User", limit=50)
admin_page = db.get_nodes_by_labels_paged(["User", "Admin"], limit=50)
# page.items: list[NodeView]
```

---

### get_edges_by_label_paged

Paginated hydrated edge-label scan. Returns full edge records.

```rust
let page = db.get_edges_by_label_paged(
    "WORKS_ON",
    &PageRequest { limit: Some(50), after: None },
)?;
// page.items: Vec<EdgeView>
```

```javascript
const page = db.getEdgesByLabelPaged('WORKS_ON', 50);
// page.items: EdgeView[]
```

```python
page = db.get_edges_by_label_paged("WORKS_ON", limit=50)
# page.items: list[EdgeView]
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| label | `&str` | `string` | `str` | Yes | - | Public edge label to match. |
| limit | `Option<usize>` | `number` | `int` | No | Unlimited | Maximum edge records per page. |
| after | `Option<u64>` | `number` | `int` | No | `None` (start from beginning) | Cursor. Returns edge records with IDs strictly greater than this value. Use `next_cursor` from a previous result. |

#### Returns: PageResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `Vec<EdgeView>` | `EdgeView[]` | `list[EdgeView]` | Full edge records in this page. |
| next_cursor | `Option<u64>` | `number \| null` | `int \| None` | Cursor for the next page. `None`/`null` means this is the last page. |

Unknown edge labels return an empty page. Tombstoned edges are excluded. The implementation pages IDs first and hydrates only the requested page.

---

### find_nodes_paged

Paginated version of [`find_nodes`](#find_nodes).

```rust
let page = db.find_nodes_paged(
    "User",
    "role",
    &PropValue::String("admin".into()),
    &PageRequest { limit: Some(50), after: None },
)?;
```

```javascript
const page = db.findNodesPaged('User', 'role', 'admin', { limit: 50 });
```

```python
page = db.find_nodes_paged("User", "role", "admin", limit=50)
```

---

### find_nodes_range_paged

Paginated version of [`find_nodes_range`](#find_nodes_range).

**Rust**
```rust
let page = db.find_nodes_range_paged(
    "User",
    "score",
    Some(&PropertyRangeBound::Included(PropValue::Int(10))),
    Some(&PropertyRangeBound::Excluded(PropValue::Int(20))),
    &PropertyRangePageRequest {
        limit: Some(50),
        after: None,
    },
)?;
```

**Node.js**
```javascript
const page = db.findNodesRangePaged(
  'User',
  'score',
  { value: 10, inclusive: true, domain: 'int' },
  { value: 20, inclusive: false, domain: 'int' },
  { limit: 50 },
);
```

**Python**
```python
page = db.find_nodes_range_paged(
    "User",
    "score",
    PropertyRangeBound(10, domain="int"),
    PropertyRangeBound(20, inclusive=False, domain="int"),
    limit=50,
)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| label | `&str` | `string` | `str` | Yes | — | Restrict search to this node label. |
| prop_key | `&str` | `string` | `str` | Yes | — | Numeric property key to query. |
| lower | `Option<&PropertyRangeBound>` | `PropertyRangeBound \| null \| undefined` | `PropertyRangeBound \| None` | No | Unbounded | Lower bound. |
| upper | `Option<&PropertyRangeBound>` | `PropertyRangeBound \| null \| undefined` | `PropertyRangeBound \| None` | No | Unbounded | Upper bound. |
| limit | `Option<usize>` | `number` | `int` | No | Unlimited | Maximum items per page. |
| after | `Option<PropertyRangeCursor>` | `PropertyRangeCursor` | `PropertyRangeCursor` | No | `None` | Cursor from a previous range page. Reuse the same query arguments when resuming. |

#### Returns: PropertyRangePageResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| items | `Vec<u64>` | `Float64Array` | `IdArray` | Node IDs in range order for this page. |
| next_cursor | `Option<PropertyRangeCursor>` | `PropertyRangeCursor \| null \| undefined` | `PropertyRangeCursor \| None` | Cursor for the next page, or no cursor on the last page. |

#### Behavior

- At least one bound is required.
- Numeric domains are exact. `int`, `uint`, and `float` are separate query domains.
- If both bounds are present, they must use the same domain.
- When resuming with `after`, keep the same `label`, `prop_key`, bounds, and domain.
- Invalid bound or cursor combinations return an error.

---

### find_nodes_by_time_range_paged

Paginated version of [`find_nodes_by_time_range`](#find_nodes_by_time_range).

```javascript
const page = db.findNodesByTimeRangePaged('User', startMs, endMs, { limit: 50 });
```

```python
page = db.find_nodes_by_time_range_paged("User", start_ms, end_ms, limit=50)
```

---

## Traversal

### neighbors

Retrieves the immediate neighbors of a node (one hop). The most common graph traversal operation.

**Rust**
```rust
let entries = db.neighbors(node_id, &NeighborOptions {
    direction: Direction::Outgoing,
    edge_label_filter: Some(vec!["WORKS_ON".into()]),
    limit: Some(10),
    at_epoch: None,
    decay_lambda: None,
})?;

for entry in &entries {
    println!("neighbor={}, edge={}, weight={}", entry.node_id, entry.edge_id, entry.weight);
}
```

**Node.js**
```javascript
const list = db.neighbors(nodeId, {
  direction: 'outgoing',
  edgeLabelFilter: ['WORKS_ON'],
  limit: 10,
});

for (const n of list) {
  console.log(n.nodeId, n.edgeId, n.weight);
}
```

**Python**
```python
entries = db.neighbors(node_id, direction="outgoing", edge_label_filter=["WORKS_ON"], limit=10)
for entry in entries:
    print(entry.node_id, entry.edge_id, entry.weight)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| node_id | `u64` | `number` | `int` | Yes | — | Node to query neighbors for. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Traversal direction. `"outgoing"`, `"incoming"`, or `"both"`. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` (all labels) | Only return neighbors connected by edges with these labels. |
| limit | `Option<usize>` | `number` | `int` | No | `None` (unlimited) | Maximum number of neighbors to return. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` (current time) | Temporal filter. Only edges whose validity window contains this timestamp are included. `None` means the current wall-clock time. |
| decay_lambda | `Option<f32>` | `number` | `float` | No | `None` (no decay) | Exponential decay factor. When set, each neighbor's weight is multiplied by `exp(-λ × age_hours)` where `age_hours = max(at_epoch - valid_from, 0) / 3_600_000`. |

#### Returns: NeighborEntry

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| node_id | `u64` | `number` | `int` | ID of the neighboring node. |
| edge_id | `u64` | `number` | `int` | ID of the connecting edge. |
| label | `String` | `label: string` | `label: str` | Label of the connecting edge. |
| weight | `f32` | `number` | `float` | Edge weight (or decay-adjusted score if `decay_lambda` is set). |
| valid_from | `i64` | `number` | `int` | Edge validity start (ms). |
| valid_to | `i64` | `number` | `int` | Edge validity end (ms). |

**Node.js**: Returns `NeighborEntry[]` as plain objects, so you can use normal array access like `list[i].nodeId`.

#### Performance

~294ns for a node with 10 edges, ~2.1μs for 100 edges (memtable hot path).

---

### neighbors_paged

Paginated version of [`neighbors`](#neighbors).

```javascript
let page = db.neighborsPaged(nodeId, { direction: 'outgoing', limit: 20 });
// page.items: NeighborEntry[], page.nextCursor: number | null
console.log(page.items[0].nodeId);

// Next page:
page = db.neighborsPaged(nodeId, { direction: 'outgoing', limit: 20, after: page.nextCursor });
```

```python
page = db.neighbors_paged(node_id, direction="outgoing", limit=20)
# page.items: list[NeighborEntry], page.next_cursor: int | None

page = db.neighbors_paged(node_id, direction="outgoing", limit=20, after=page.next_cursor)
```

#### Additional Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| limit | `usize` / `number` / `int` | No | Unlimited | Page size. |
| after | `u64` / `number` / `int` | No | `None` | Cursor (edge ID) for the next page. |

---

### neighbors_batch

Batch-queries neighbors for multiple nodes in a single call. More efficient than calling `neighbors` in a loop.

**Rust**
```rust
let results = db.neighbors_batch(&[1, 2, 3], &NeighborOptions::default())?;
// results: NodeIdMap<Vec<NeighborEntry>> - map from node_id to its neighbors
```

**Node.js**
```javascript
const results = db.neighborsBatch([1, 2, 3], { direction: 'outgoing' });
// results: { queryNodeId: number, neighbors: NeighborEntry[] }[]
console.log(results[0].neighbors[0].nodeId);
```

**Python**
```python
results = db.neighbors_batch([1, 2, 3], direction="outgoing")
# results: dict[int, list[NeighborEntry]]
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| node_ids | `&[u64]` | `number[]` | `list[int]` | Yes | Node IDs to query neighbors for. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Traversal direction. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Edge label filter. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |
| decay_lambda | `Option<f32>` | `number` | `float` | No | `None` | Decay factor. Uses hours from `valid_from` when set. |

#### Returns

A map/array mapping each query node ID to its list of neighbors.

---

### top_k_neighbors

Returns the top K neighbors of a node ranked by a scoring criterion.

**Rust**
```rust
let top = db.top_k_neighbors(node_id, 5, &TopKOptions {
    direction: Direction::Outgoing,
    scoring: ScoringMode::DecayAdjusted { lambda: 0.01 },
    ..Default::default()
})?;
```

**Node.js**
```javascript
const top = db.topKNeighbors(nodeId, 5, {
  direction: 'outgoing',
  scoring: 'decay',
  decayLambda: 0.01,
});
console.log(top[0].nodeId, top[0].weight);
```

**Python**
```python
top = db.top_k_neighbors(
    node_id,
    5,
    direction="outgoing",
    scoring="decay",
    decay_lambda=0.01,
)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| node_id | `u64` | `number` | `int` | Yes | — | Source node. |
| k | `usize` | `number` | `int` | Yes | — | Number of top neighbors to return. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Traversal direction. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Edge label filter. |
| scoring | `ScoringMode` | `string` | `str` | No | `Weight` | Scoring criterion. Rust carries the decay lambda inside `ScoringMode::DecayAdjusted { lambda }`; connectors use `scoring: "decay"` plus `decayLambda` / `decay_lambda`. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |
| decay_lambda | — | `number` | `float` | No | `None` | Connector-only option required when `scoring = "decay"`. |

**Scoring modes:**

| Mode | Rust | Node.js / Python | Description |
|------|------|------------------|-------------|
| Weight | `ScoringMode::Weight` | `"weight"` | Rank by edge weight (descending). |
| Recency | `ScoringMode::Recency` | `"recency"` | Rank by recency. More recent edges score higher. |
| DecayAdjusted | `ScoringMode::DecayAdjusted { lambda }` | `"decay"` | Exponential decay: `weight × exp(-λ × age_hours)`, where `age_hours = max(at_epoch - valid_from, 0) / 3_600_000`. Connectors require `decay_lambda`. |

#### Returns

Array of `NeighborEntry` sorted by score descending. Length is `min(k, actual_neighbor_count)`.

---

### traverse

Breadth-first traversal from a starting node up to a maximum depth. Supports pagination, edge-label filtering, emission-only node-label filtering, temporal filtering, and decay scoring.

**Rust**
```rust
let result = db.traverse(start_id, &TraverseOptions {
    min_depth: 1,
    direction: Direction::Outgoing,
    edge_label_filter: Some(vec!["WORKS_ON".into()]),
    emit_node_label_filter: Some(NodeLabelFilter {
        labels: vec!["User".into(), "Admin".into()],
        mode: LabelMatchMode::Any,
    }),
    at_epoch: None,
    decay_lambda: None,
    limit: Some(100),
    cursor: None,
})?;

for hit in &result.items {
    println!("node={}, depth={}", hit.node_id, hit.depth);
}
```

**Node.js**
```javascript
const result = db.traverse(startId, 3, {
  minDepth: 1,
  direction: 'outgoing',
  edgeLabelFilter: ['WORKS_ON'],
  emitNodeLabelFilter: { labels: ['User', 'Admin'], mode: 'any' },
  limit: 100,
});

for (const hit of result.items) {
  console.log(hit.nodeId, hit.depth, hit.viaEdgeId);
}

// Paginate:
if (result.nextCursor) {
  const page2 = db.traverse(startId, 3, { cursor: result.nextCursor, limit: 100 });
}
```

**Python**
```python
result = db.traverse(start_id, max_depth=3,
    min_depth=1, direction="outgoing",
    edge_label_filter=["WORKS_ON"],
    emit_node_label_filter={"labels": ["User", "Admin"], "mode": "any"},
    limit=100)

for hit in result.items:
    print(hit.node_id, hit.depth, hit.via_edge_id)

# Paginate:
if result.next_cursor:
    page2 = db.traverse(start_id, max_depth=3, cursor=result.next_cursor, limit=100)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| start_node_id | `u64` | `number` | `int` | Yes | — | Starting node for the BFS traversal. |
| max_depth | (part of TraverseOptions in Rust) | `number` | `int` | Yes | — | Maximum number of hops from the start node. `1` = immediate neighbors, `2` = neighbors of neighbors, etc. |
| min_depth | `u32` | `number` | `int` | No | `1` | Minimum depth to include in results. Set to `0` to include the start node itself. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Edge traversal direction. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` (all labels) | Only follow edges with these labels. |
| emit_node_label_filter | `Option<NodeLabelFilter>` | `emitNodeLabelFilter: { labels: string[], mode: "any" \| "all" }` | `emit_node_label_filter: dict` | No | `None` (all labels) | Node-label filter for emitted nodes. Traversal may still pass through non-emitted labels. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter for edge validity. |
| decay_lambda | `Option<f64>` | `number` | `float` | No | `None` | Depth-based traversal score. When set, each hit receives `exp(-λ × depth)`. |
| limit | `Option<usize>` | `number` | `int` | No | `None` (unlimited) | Maximum results per page. Use with `cursor` for pagination. |
| cursor | `Option<TraversalCursor>` | `TraversalCursor` | `TraversalCursor` | No | `None` | Resume traversal from a previous page. |

#### Returns: TraversalHit

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| node_id | `u64` | `number` | `int` | Node reached by the traversal. |
| depth | `u32` | `number` | `int` | Distance (hops) from the start node. |
| via_edge_id | `Option<u64>` | `number \| null` | `int \| None` | Edge ID used to reach this node. `None` for the start node (depth 0). |
| score | `Option<f64>` | `number \| null` | `float \| None` | Decay-adjusted score (only present when `decay_lambda` is set). |

Results are ordered by `(depth ASC, node_id ASC)` with deterministic tie-breaking.

---

### extract_subgraph

Extracts a complete subgraph (all reachable nodes and edges) rooted at a given node.

**Rust**
```rust
let sg = db.extract_subgraph(root_id, 3, &SubgraphOptions {
    direction: Direction::Outgoing,
    edge_label_filter: None,
    node_label_filter: Some(NodeLabelFilter {
        labels: vec!["User".into()],
        mode: LabelMatchMode::Any,
    }),
    at_epoch: None,
})?;
println!("{} nodes, {} edges", sg.nodes.len(), sg.edges.len());
```

**Node.js**
```javascript
const sg = db.extractSubgraph(rootId, 3, {
  direction: 'outgoing',
  nodeLabelFilter: { labels: ['User'], mode: 'any' },
});
console.log(sg.nodes.length, 'nodes,', sg.edges.length, 'edges');
```

**Python**
```python
sg = db.extract_subgraph(
    root_id,
    max_depth=3,
    direction="outgoing",
    node_label_filter={"labels": ["User"], "mode": "any"},
)
print(len(sg.nodes), "nodes,", len(sg.edges), "edges")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| start_node_id | `u64` | `number` | `int` | Yes | — | Root node. |
| max_depth | `u32` | `number` | `int` | Yes | — | Maximum hops from root. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Direction. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Edge label filter. |
| node_label_filter | `Option<NodeLabelFilter>` | `nodeLabelFilter: { labels: string[], mode: "any" \| "all" }` | `node_label_filter: dict` | No | `None` | Node-label filter for nodes to include and expand through. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |

#### Returns: Subgraph

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| nodes | `Vec<NodeView>` | `NodeView[]` | `list[NodeView]` | All nodes in the subgraph (full records). |
| edges | `Vec<EdgeView>` | `EdgeView[]` | `list[EdgeView]` | All edges in the subgraph (full records). |

### shortest_path

Finds the shortest (lowest-cost) path between two nodes.

**Rust**
```rust
let path = db.shortest_path(from_id, to_id, &ShortestPathOptions {
    direction: Direction::Outgoing,
    weight_field: None, // uses edge.weight; set to Some("cost".into()) for property-based cost
    max_depth: Some(10),
    max_cost: Some(100.0),
    ..Default::default()
})?;

if let Some(p) = path {
    println!("path: {:?}, cost: {}", p.nodes, p.total_cost);
}
```

**Node.js**
```javascript
const path = db.shortestPath(fromId, toId, {
  direction: 'outgoing',
  maxDepth: 10,
  maxCost: 100.0,
});

if (path) {
  console.log('nodes:', path.nodes, 'cost:', path.totalCost);
}
```

**Python**
```python
path = db.shortest_path(from_id, to_id, direction="outgoing", max_depth=10, max_cost=100.0)
if path:
    print("nodes:", path.nodes, "cost:", path.total_cost)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| from | `u64` | `number` | `int` | Yes | — | Source node ID. |
| to | `u64` | `number` | `int` | Yes | — | Destination node ID. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Direction to follow edges. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Only traverse these edge labels. |
| weight_field | `Option<String>` | `string` | `str` | No | `None` | Property key on edges to use as cost. When `None`, uses `edge.weight`. When set, reads the named property as the edge cost (must be numeric). |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |
| max_depth | `Option<u32>` | `number` | `int` | No | `None` (unlimited) | Stop searching after this many hops. Prevents runaway searches on deep graphs. |
| max_cost | `Option<f64>` | `number` | `float` | No | `None` (unlimited) | Stop searching when accumulated cost exceeds this threshold. |

#### Algorithm

- When `weight_field` is `None` **and all edge weights are 1.0**: BFS (unweighted shortest path).
- Otherwise: Dijkstra's algorithm (weighted shortest path).

#### Returns: ShortestPath

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| nodes | `Vec<u64>` | `number[]` | `list[int]` | Ordered list of node IDs from source to destination (inclusive). |
| edges | `Vec<u64>` | `number[]` | `list[int]` | Edge IDs along the path. Length = `nodes.length - 1`. |
| cost / total_cost | `f64` | `number` | `float` | Sum of edge costs along the path. |

Returns `None`/`null` if no path exists within the given constraints.

---

### all_shortest_paths

Finds **all** shortest paths (when multiple paths have the same minimum cost).

```rust
let paths = db.all_shortest_paths(from_id, to_id, &AllShortestPathsOptions {
    max_paths: Some(10),
    ..Default::default()
})?;
```

```javascript
const paths = db.allShortestPaths(fromId, toId, { maxPaths: 10 });
```

```python
paths = db.all_shortest_paths(from_id, to_id, max_paths=10)
```

#### Additional Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| max_paths | `Option<usize>` | `number` | `int` | No | `None` (unlimited) | Stop after finding this many paths. Use to prevent combinatorial explosion on highly connected graphs. |

All other parameters are the same as [`shortest_path`](#shortest_path).

#### Returns

Array of `ShortestPath` objects. All paths have the same cost (the minimum). Can be empty if no path exists.

---

### is_connected

Fast reachability check: does any path exist between two nodes? Uses BFS with early termination.

```rust
let connected = db.is_connected(from_id, to_id, &IsConnectedOptions::default())?;
```

```javascript
const connected = db.isConnected(fromId, toId, { direction: 'both', maxDepth: 5 });
```

```python
connected = db.is_connected(from_id, to_id, direction="both", max_depth=5)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| from | `u64` | `number` | `int` | Yes | — | Source node. |
| to | `u64` | `number` | `int` | Yes | — | Destination node. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Direction. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Edge label filter. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |
| max_depth | `Option<u32>` | `number` | `int` | No | `None` | Maximum search depth. |

#### Returns

`bool`. Returns `true` if a path exists, `false` otherwise.

---

## Degree & Weight Aggregation

### degree

Counts the number of edges connected to a node.

```rust
let d = db.degree(node_id, &DegreeOptions::default())?;
```

```javascript
const d = db.degree(nodeId, { direction: 'both' });
```

```python
d = db.degree(node_id, direction="both")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| node_id | `u64` | `number` | `int` | Yes | — | Node to count edges for. |
| direction | `Direction` | `string` | `str` | No | `Outgoing` | Which edges to count. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Only count edges with these labels. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<u32, EngineError>` | `number` | `int` |

The edge count.

#### Performance

Metadata-only fast path for unfiltered, non-temporal queries when all visible segments have valid degree sidecars. O(edges) walk fallback when filtering by edge label, using a temporal epoch, running with active prune policies, reading a node with temporal incident edges, or reading through a segment whose degree sidecar is missing/corrupt.

---

### degrees

Batch degree query for multiple nodes.

```rust
let map = db.degrees(&[1, 2, 3], &DegreeOptions::default())?;
// map: NodeIdMap<u32>
```

```javascript
const entries = db.degrees([1, 2, 3], { direction: 'outgoing' });
// entries: { nodeId: number, degree: number }[]
```

```python
result = db.degrees([1, 2, 3], direction="outgoing")
# result: dict[int, int]
```

---

### sum_edge_weights

Sums the weights of all edges connected to a node.

```rust
let total = db.sum_edge_weights(node_id, &DegreeOptions::default())?;
```

```javascript
const total = db.sumEdgeWeights(nodeId, { direction: 'outgoing' });
```

```python
total = db.sum_edge_weights(node_id, direction="outgoing")
```

Same parameters as [`degree`](#degree). Returns `f64` / `number` / `float`.

---

### avg_edge_weight

Average weight of edges connected to a node.

```rust
let avg = db.avg_edge_weight(node_id, &DegreeOptions::default())?;
```

```javascript
const avg = db.avgEdgeWeight(nodeId); // number | null
```

```python
avg = db.avg_edge_weight(node_id)  # float | None
```

Same parameters as [`degree`](#degree). Returns `None`/`null` if the node has no edges.

---

## Graph Analytics

### connected_components

Computes all [weakly connected components](https://en.wikipedia.org/wiki/Connected_component_(graph_theory)) in the graph. Treats edges as undirected regardless of their actual direction.

**Rust**
```rust
let components = db.connected_components(&ComponentOptions {
    node_label_filter: Some(NodeLabelFilter {
        labels: vec!["User".into()],
        mode: LabelMatchMode::Any,
    }),
    ..Default::default()
})?;
// components: NodeIdMap<u64> - node_id to component_id
```

**Node.js**
```javascript
const entries = db.connectedComponents({
  nodeLabelFilter: { labels: ['User'], mode: 'any' },
});
// entries: { nodeId: number, componentId: number }[]
```

**Python**
```python
components = db.connected_components(node_label_filter={"labels": ["User"], "mode": "any"})
# components: dict[int, int] - node_id to component_id
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Only consider these edge labels when determining connectivity. |
| node_label_filter | `Option<NodeLabelFilter>` | `nodeLabelFilter: { labels: string[], mode: "any" \| "all" }` | `node_label_filter: dict` | No | `None` | Node-label filter for nodes included in components. |
| at_epoch | `Option<i64>` | `number` | `int` | No | `None` | Temporal filter. |

#### Returns

A mapping from every node ID to its component ID. The component ID is the smallest node ID within each component (a canonical representative).

---

### component_of

Returns all nodes in the same connected component as a given node.

```rust
let node_ids = db.component_of(node_id, &ComponentOptions {
    node_label_filter: Some(NodeLabelFilter {
        labels: vec!["User".into()],
        mode: LabelMatchMode::Any,
    }),
    ..Default::default()
})?;
```

```javascript
const nodeIds = db.componentOf(nodeId); // Float64Array
```

```python
node_ids = db.component_of(node_id, node_label_filter={"labels": ["User"], "mode": "any"})  # list[int]
```

#### Parameters

Same as [`connected_components`](#connected_components), plus:

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| node_id | `u64` | `number` | `int` | Yes | Node to find the component for. |

#### Returns

| Rust | Node.js | Python |
|------|---------|--------|
| `Result<Vec<u64>, EngineError>` | `Float64Array` | `list[int]` |

All three surfaces return the sorted node IDs in the same connected component as the requested node.

---

### personalized_pagerank

Computes [Personalized PageRank](https://en.wikipedia.org/wiki/PageRank#Personalized_PageRank) from one or more seed nodes. Useful for recommendation, influence scoring, and relevance ranking.

OverGraph exposes two PPR algorithms:
- `exact` / `ExactPowerIteration` (default): reference implementation using power iteration.
- `approx` / `ApproxForwardPush`: local forward-push approximation, usually much faster for seed-centric retrieval workloads.

**Rust**
```rust
let result = db.personalized_pagerank(&[seed_id], &PprOptions {
    algorithm: PprAlgorithm::ApproxForwardPush,
    approx_residual_tolerance: 1e-5,
    max_results: Some(50),
    ..Default::default()
})?;
```

**Node.js**
```javascript
const result = db.personalizedPagerank([seedId], {
  algorithm: 'approx',
  approxResidualTolerance: 1e-5,
  maxResults: 50,
});

console.log('algorithm:', result.algorithm);
for (let i = 0; i < result.nodeIds.length; i++) {
  console.log(result.nodeIds[i], result.scores[i]);
}
```

**Python**
```python
result = db.personalized_pagerank([seed_id],
    algorithm="approx",
    approx_residual_tolerance=1e-5,
    max_results=50)

print("algorithm:", result.algorithm)
for nid, score in zip(result.node_ids, result.scores):
    print(nid, score)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| seed_node_ids | `Vec<u64>` | `number[]` | `list[int]` | Yes | — | Seed nodes. The random walk teleports back to these nodes with probability `1 - damping_factor`. Multiple seeds distribute the teleport probability evenly. |
| algorithm | `PprAlgorithm` | `string` | `str` | No | `ExactPowerIteration` / `"exact"` | PPR algorithm. Rust accepts `ExactPowerIteration` or `ApproxForwardPush`. Node/Python accept `"exact"` or `"approx"`. |
| damping_factor | `f64` | `number` | `float` | No | `0.85` | Probability of following an edge (vs. teleporting back to a seed). Standard PageRank uses 0.85. Higher values explore further from seeds; lower values stay closer. |
| max_iterations | `u32` | `number` | `int` | No | `20` | Maximum power iterations for exact mode. The algorithm stops when it converges or reaches this limit. |
| epsilon | `f64` | `number` | `float` | No | `1e-6` | Convergence threshold. Iteration stops when the L1 norm of the score change vector drops below this value. |
| approx_residual_tolerance | `f64` | `number` | `float` | No | `1e-5` | Approximate-mode stopping tolerance for forward push. Smaller values improve fidelity and increase work. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Only follow these edge labels during the walk. |
| max_results | `Option<usize>` | `number` | `int` | No | `None` (all) | Return only the top N nodes by score. |

#### Returns: PprResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| scores | `Vec<(u64, f64)>` | — | — | Rust scored node pairs sorted by score descending. |
| node IDs | — | `nodeIds: Float64Array` | `node_ids: list[int]` | Connector node IDs sorted by score descending. |
| scores | — | `scores: Float64Array` | `scores: list[float]` | Connector scores corresponding to node IDs. Exact PPR sums to 1.0 (or very close); approximate PPR is optimized for ranking quality rather than strict normalization. |
| iterations | `u32` | `number` | `int` | Number of exact power iterations performed. Approximate mode returns `0`. |
| converged | `bool` | `boolean` | `bool` | Exact mode: whether the algorithm converged within `max_iterations`. Approximate mode: `true` when no node remains above the residual tolerance. |
| algorithm | `PprAlgorithm` | `string` | `str` | Which algorithm produced the result. |
| approx | `Option<PprApproxMeta>` | `PprApproxMeta \| null` | `PprApproxMeta \| None` | Approximate-mode metadata. `None`/`null` in exact mode. |

---

### export_adjacency

Exports the graph's adjacency structure as flat arrays. Useful for bulk analysis, NetworkX integration, or external graph processing.

**Rust**
```rust
let export = db.export_adjacency(&ExportOptions {
    node_label_filter: Some(NodeLabelFilter {
        labels: vec!["User".into(), "Admin".into()],
        mode: LabelMatchMode::Any,
    }),
    include_weights: true,
    ..Default::default()
})?;
println!("node label side table: {:?}", export.node_labels);
println!("per-node label indexes: {:?}", export.node_label_indexes);
```

**Node.js**
```javascript
const adj = db.exportAdjacency({
  nodeLabelFilter: { labels: ['User', 'Admin'], mode: 'any' },
  includeWeights: true,
});
// adj.nodeIds: Float64Array
// adj.edgeLabels: string[]
// adj.edgeFrom: Float64Array
// adj.edgeTo: Float64Array
// adj.edgeLabelIndexes: Uint32Array
// adj.edgeWeights: Float64Array | undefined
```

**Python**
```python
adj = db.export_adjacency(
    node_label_filter={"labels": ["User", "Admin"], "mode": "any"},
    include_weights=True,
)
# adj.node_ids: list[int]
# adj.node_labels: list[str]
# adj.node_label_indexes: list[list[int]]
# adj.edge_labels: list[str]
# adj.edges: list[ExportEdge] - each has from_id, to_id, edge_label_index, weight
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| node_label_filter | `Option<NodeLabelFilter>` | `nodeLabelFilter: { labels: string[], mode: "any" \| "all" }` | `node_label_filter: dict` | No | `None` | Node-label filter for exported nodes. |
| edge_label_filter | `Option<Vec<String>>` | `edgeLabelFilter: string[]` | `edge_label_filter: list[str]` | No | `None` | Only export edges with these labels. |
| include_weights | `bool` | `boolean` | `bool` | No | `true` | Include edge weights in the export. Set to `false` to save memory/bandwidth when weights aren't needed. |

#### Returns: AdjacencyExport

Rust:

| Field | Type | Description |
|-------|------|-------------|
| node_ids | `Vec<u64>` | Live node IDs in the exported graph. |
| node_labels | `Vec<String>` | Export-local node-label side table. |
| node_label_indexes | `Vec<Vec<u32>>` | Per-node label side-table indexes, aligned with `node_ids`. |
| edge_labels | `Vec<String>` | Export-local edge-label side table. |
| edges | `Vec<ExportEdge>` | Exported edges. Each `ExportEdge.edge_label_index` references `edge_labels`. |

Node.js:

| Field | Type | Description |
|-------|------|-------------|
| nodeIds | `Float64Array` | Live node IDs in the exported graph. |
| edgeLabels | `string[]` | Export-local edge-label side table. |
| edgeFrom | `Float64Array` | Source node IDs, aligned with `edgeTo` and `edgeLabelIndexes`. |
| edgeTo | `Float64Array` | Destination node IDs. |
| edgeLabelIndexes | `Uint32Array` | Edge-label side-table indexes, aligned with `edgeFrom` / `edgeTo`. |
| edgeWeights | `Float64Array \| undefined` | Edge weights when `includeWeights` is true. |

Python:

| Field | Type | Description |
|-------|------|-------------|
| node_ids | `list[int]` | Live node IDs in the exported graph. |
| node_labels | `list[str]` | Export-local node-label side table. |
| node_label_indexes | `list[list[int]]` | Per-node label side-table indexes, aligned with `node_ids`. |
| edge_labels | `list[str]` | Export-local edge-label side table. |
| edges | `list[ExportEdge]` | Exported edges. Each edge has `from_id`, `to_id`, `edge_label_index`, and optional `weight`. |

---

## Vector Search

### vector_search

Performs similarity search using dense vectors (HNSW approximate nearest neighbors), sparse vectors (inverted index dot product), or hybrid mode (fusion of both).

**Rust**
```rust
// Dense search
let hits = db.vector_search(&VectorSearchRequest {
    mode: VectorSearchMode::Dense,
    dense_query: Some(vec![0.1, 0.2, 0.3, /* ... 384 dims */]),
    sparse_query: None,
    k: 10,
    label_filter: None,
    ef_search: Some(100),
    scope: None,
    dense_weight: None,
    sparse_weight: None,
    fusion_mode: None,
})?;

// Sparse search
let hits = db.vector_search(&VectorSearchRequest {
    mode: VectorSearchMode::Sparse,
    dense_query: None,
    sparse_query: Some(vec![(42, 0.9), (128, 0.5)]),
    k: 10,
    label_filter: None,
    ef_search: None,
    scope: None,
    dense_weight: None,
    sparse_weight: None,
    fusion_mode: None,
})?;

// Hybrid search
let hits = db.vector_search(&VectorSearchRequest {
    mode: VectorSearchMode::Hybrid,
    dense_query: Some(embedding),
    sparse_query: Some(sparse_terms),
    k: 10,
    label_filter: Some(NodeLabelFilter {
        labels: vec!["Document".into(), "Published".into()],
        mode: LabelMatchMode::All,
    }),
    ef_search: None,
    scope: None,
    dense_weight: Some(0.7),
    sparse_weight: Some(0.3),
    fusion_mode: Some(FusionMode::WeightedScoreFusion),
})?;
```

**Node.js**
```javascript
// Dense search
const hits = db.vectorSearch('dense', {
  k: 10,
  denseQuery: [0.1, 0.2, 0.3, /* ... */],
  efSearch: 100,
});

// Sparse search
const hits = db.vectorSearch('sparse', {
  k: 10,
  sparseQuery: [{ dimension: 42, value: 0.9 }, { dimension: 128, value: 0.5 }],
});

// Hybrid search with graph scope
const hits = db.vectorSearch('hybrid', {
  k: 10,
  labelFilter: { labels: ['User', 'Project'], mode: 'any' },
  denseQuery: embedding,
  sparseQuery: sparseTerms,
  denseWeight: 0.7,
  sparseWeight: 0.3,
  fusionMode: 'weighted_score',
  scope: {
    startNodeId: rootId,
    maxDepth: 2,
    direction: 'outgoing',
  },
});
```

**Python**
```python
# Dense search
hits = db.vector_search("dense", k=10, dense_query=[0.1, 0.2, ...], ef_search=100)

# Sparse search
hits = db.vector_search("sparse", k=10, sparse_query=[(42, 0.9), (128, 0.5)])

# Hybrid with graph scope
hits = db.vector_search("hybrid", k=10,
    dense_query=embedding,
    sparse_query=sparse_terms,
    label_filter={"labels": ["Document", "Published"], "mode": "all"},
    dense_weight=0.7, sparse_weight=0.3,
    fusion_mode="weighted_score",
    scope_start_node_id=root_id,
    scope_max_depth=2,
    scope_direction="outgoing")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| mode | `VectorSearchMode` | `string` | `str` | Yes | — | `"dense"`, `"sparse"`, or `"hybrid"`. Determines which query vector(s) and index to use. |
| k | `usize` | `number` | `int` | Yes | — | Number of top results to return. |
| dense_query | `Option<Vec<f32>>` | `number[]` | `list[float]` | Required for `dense`/`hybrid` | `None` | Query vector for dense search. Must have the same dimension as configured at `open()`. |
| sparse_query | `Option<Vec<(u32, f32)>>` | `SparseEntry[]` | `list[tuple[int, float]]` | Required for `sparse`/`hybrid` | `None` | Query vector for sparse search. List of `(dimension_index, value)` pairs. |
| label_filter | `Option<NodeLabelFilter>` | `labelFilter: { labels: string[], mode: "any" \| "all" }` | `label_filter: dict` | No | `None` | Node-label filter. |
| ef_search | `Option<usize>` | `number` | `int` | No | `128` | HNSW search expansion factor. The effective dense fetch limit is at least `k` and at least `8`. Higher values improve recall at the cost of latency. Only applies to dense/hybrid modes. |

**Hybrid fusion parameters** (only used when `mode = "hybrid"`):

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| dense_weight | `Option<f32>` | `number` | `float` | No | `1.0` | Weight for dense scores in fusion. |
| sparse_weight | `Option<f32>` | `number` | `float` | No | `1.0` | Weight for sparse scores in fusion. |
| fusion_mode | `Option<FusionMode>` | `string` | `str` | No | `WeightedRankFusion` | How to combine dense and sparse results. See fusion modes below. |

**Fusion modes:**

| Mode | Rust | Node.js / Python | Description |
|------|------|------------------|-------------|
| WeightedRankFusion | `FusionMode::WeightedRankFusion` | `"weighted_rank"` | Weighted reciprocal rank fusion. Default. Combines rank positions with weights. Robust when score distributions differ. |
| ReciprocalRankFusion | `FusionMode::ReciprocalRankFusion` | `"reciprocal_rank"` | Standard RRF (unweighted). Equal contribution from both signals. |
| WeightedScoreFusion | `FusionMode::WeightedScoreFusion` | `"weighted_score"` | Min-max normalized score fusion. Directly combines normalized scores. Best when score magnitudes are meaningful. |

**Graph-scoped search** (restrict vector search to a subgraph):

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| scope.start_node_id | `u64` | `scope.startNodeId: number` | `scope_start_node_id: int` | No | `None` | Root node for scope traversal. When set, only nodes reachable from this node within `max_depth` are candidates. |
| scope.max_depth | `u32` | `scope.maxDepth: number` | `scope_max_depth: int` | Required if scope set | — | Maximum hops from the scope root. |
| scope.direction | `Direction` | `scope.direction: string` | `scope_direction: str` | No | `Outgoing` | Direction for scope traversal. |
| scope.edge_label_filter | `Option<Vec<String>>` | `scope.edgeLabelFilter: string[]` | `scope_edge_label_filter: list[str]` | No | `None` | Edge labels for scope traversal. |
| scope.at_epoch | `Option<i64>` | `scope.atEpoch: number` | `scope_at_epoch: int` | No | `None` | Temporal filter for scope. |

#### Returns: VectorHit

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| node_id | `u64` | `number` | `int` | Matching node ID. |
| score | `f32` | `number` | `float` | Similarity score. Higher is better. |

Results are sorted by score descending.

---

## Retention & Pruning

### prune

Immediately deletes nodes matching the specified criteria. Cascade-deletes all incident edges. Applied atomically in a single WAL batch.

```rust
let result = db.prune(&PrunePolicy {
    max_age_ms: Some(7 * 24 * 60 * 60 * 1000), // 7 days
    max_weight: Some(0.1),                       // weight <= 0.1
    label: Some("Conversation".into()),           // only conversations
})?;
println!("pruned {} nodes, {} edges", result.nodes_pruned, result.edges_pruned);
```

```javascript
const result = db.prune({
  maxAgeMs: 7 * 24 * 60 * 60 * 1000,
  maxWeight: 0.1,
  label: 'Conversation',
});
```

```python
result = db.prune(
    max_age_ms=7 * 24 * 60 * 60 * 1000,
    max_weight=0.1,
    label="Conversation",
)
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Default | Description |
|-----------|------|---------|--------|----------|---------|-------------|
| max_age_ms | `Option<i64>` | `number` | `int` | No* | `None` | Delete nodes older than `now - max_age_ms` milliseconds. Age is computed from `updated_at`. |
| max_weight | `Option<f32>` | `number` | `float` | No* | `None` | Delete nodes with `weight <= max_weight`. |
| label | `Option<String>` | `string` | `str` | No | `None` (all labels) | Restrict pruning to a single node label. |

\* At least one of `max_age_ms` or `max_weight` must be provided. This guards against accidental mass deletion (calling `prune({})` with no criteria is an error).

**Criteria are combined with AND logic.** A node is pruned only if it matches *all* specified criteria.

#### Returns: PruneResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| nodes_pruned | `u64` | `number` | `int` | Number of nodes deleted. |
| edges_pruned | `u64` | `number` | `int` | Number of edges cascade-deleted. |

---

### set_prune_policy

Registers a named prune policy that is automatically applied during [compaction](#compact). Multiple policies can coexist.

```rust
db.set_prune_policy("stale-conversations", PrunePolicy {
    max_age_ms: Some(30 * 24 * 60 * 60 * 1000), // 30 days
    max_weight: None,
    label: Some("Conversation".into()),
})?;
```

```javascript
db.setPrunePolicy('stale-conversations', {
  maxAgeMs: 30 * 24 * 60 * 60 * 1000,
  label: 'Conversation',
});
```

```python
db.set_prune_policy("stale-conversations",
    max_age_ms=30 * 24 * 60 * 60 * 1000,
    label="Conversation")
```

#### Parameters

| Parameter | Rust | Node.js | Python | Required | Description |
|-----------|------|---------|--------|----------|-------------|
| name | `&str` | `string` | `str` | Yes | Policy name. Used to remove or list the policy later. |
| policy | `PrunePolicy` | `object` | `**kwargs` | Yes | Pruning criteria (same fields as [`prune`](#prune)). |

#### Behavior

- Persisted in the manifest. Survives database close/reopen.
- Applied automatically during compaction: matching nodes are pruned and their edges cascade-deleted.
- Multiple policies combine with **OR logic across policies**: a node matching *any* policy is pruned. Within a single policy, criteria combine with AND logic.
- Setting a policy with the same name replaces the previous one.

---

### remove_prune_policy

Removes a named prune policy.

```rust
let existed = db.remove_prune_policy("stale-conversations")?;
```

```javascript
const existed = db.removePrunePolicy('stale-conversations');
```

```python
existed = db.remove_prune_policy("stale-conversations")
```

#### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| name | `&str` / `string` / `str` | Yes | Name of the policy to remove. |

#### Returns

`bool`. Returns `true` if the policy existed and was removed, `false` if no policy with that name was found.

---

### list_prune_policies

Lists all registered prune policies.

```rust
let policies = db.list_prune_policies()?;
for info in &policies {
    println!("{}: max_age_ms={:?}", info.name, info.policy.max_age_ms);
}
```

```javascript
const policies = db.listPrunePolicies();
// [{ name: string, policy: { maxAgeMs?, maxWeight?, label? } }]
```

```python
policies = db.list_prune_policies()
for p in policies:
    print(p.name, p.max_age_ms, p.max_weight, p.label)
```

#### Returns

Array of named policies. Rust and Node.js entries contain a nested policy object; Python flattens
policy fields onto each entry.

| Field path | Rust | Node.js | Python | Description |
|------------|------|---------|--------|-------------|
| name | `info.name: String` | `entry.name: string` | `p.name: str` | Policy name. |
| policy | `info.policy: PrunePolicy` | `entry.policy: PrunePolicy` | — | Nested policy object in Rust and Node.js. |
| max age | `info.policy.max_age_ms: Option<i64>` | `entry.policy.maxAgeMs?: number` | `p.max_age_ms: int \| None` | Age threshold. |
| max weight | `info.policy.max_weight: Option<f32>` | `entry.policy.maxWeight?: number` | `p.max_weight: float \| None` | Weight threshold. |
| label | `info.policy.label: Option<String>` | `entry.policy.label?: string` | `p.label: str \| None` | Node-label scope. |

---

## Maintenance

### sync

Forces an immediate WAL fsync, ensuring all buffered writes are durable on disk.

```rust
db.sync()?;
```

```javascript
db.sync();
```

```python
db.sync()
```

#### Behavior

- In **Immediate** mode: no-op (every write already triggers fsync).
- In **GroupCommit** mode: blocks until all currently buffered data is fsynced.

---

### flush

Flushes the active memtable to a new on-disk segment. Blocks until all pending immutable memtables are written.

```rust
let info = db.flush()?;
```

```javascript
db.flush();
```

```python
info = db.flush()  # SegmentInfo | None
```

#### Returns

| Rust | Node.js | Python | Description |
|------|---------|--------|-------------|
| `Result<Option<SegmentInfo>, EngineError>` | `void` | `SegmentInfo \| None` | Info about the written segment, or `None` if the memtable was empty. |

**SegmentInfo** (Rust/Python):

| Field | Rust | Python | Description |
|-------|------|--------|-------------|
| id | `u64` | `int` | Segment ID on disk. |
| node_count | `u64` | `int` | Nodes in the segment. |
| edge_count | `u64` | `int` | Edges in the segment. |
| segment_format_version | `u32` | — | Rust segment format version. |
| segment_data_id | `[u8; 32]` | — | Rust segment data identifier. |

---

### compact

Merges all segments into a single segment. Applies prune policies during the merge. Reclaims space from tombstones.

```rust
let stats = db.compact()?;
```

```javascript
const stats = db.compact();
```

```python
stats = db.compact()
```

#### Returns: CompactionStats

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| segments_merged | `usize` | `number` | `int` | Number of input segments. |
| nodes_kept | `u64` | `number` | `int` | Live nodes in the output segment. |
| nodes_removed | `u64` | `number` | `int` | Tombstoned nodes reclaimed. |
| edges_kept | `u64` | `number` | `int` | Live edges in the output. |
| edges_removed | `u64` | `number` | `int` | Tombstoned edges reclaimed. |
| duration_ms | `u64` | `number` | `int` | Wall-clock time of compaction. |
| output_segment_id | `u64` | `number` | `int` | ID of the output segment. |
| nodes_auto_pruned | `u64` | `number` | `int` | Nodes removed by prune policies. |
| edges_auto_pruned | `u64` | `number` | `int` | Edges cascade-deleted by auto-prune. |

Returns `None`/`null` if there are fewer than 2 segments (nothing to compact).

---

### compact_with_progress

Compaction with a progress callback. The callback is invoked at key phases and can cancel the compaction.

```rust
let stats = db.compact_with_progress(|progress| {
    println!("phase: {:?}, {}/{} records",
        progress.phase, progress.records_processed, progress.total_records);
    true // return false to cancel
})?;
```

```javascript
// Sync (blocks event loop):
const stats = db.compactWithProgress((progress) => {
  console.log(progress.phase, progress.recordsProcessed, '/', progress.totalRecords);
  return true; // return false to cancel
});

// Async (preferred for UIs):
const stats = await db.compactWithProgressAsync((progress) => {
  console.log(progress.phase);
  // async version cannot cancel, returns void
});
```

```python
def on_progress(progress):
    print(progress.phase, progress.records_processed, "/", progress.total_records)
    return True  # return False to cancel

stats = db.compact_with_progress(on_progress)
```

#### Progress Object

| Field | Type | Description |
|-------|------|-------------|
| phase | `string` | Current phase: `"collecting_tombstones"`, `"merging_nodes"`, `"merging_edges"`, `"writing_output"`. |
| segments_processed | `u32` / `number` / `int` | Segments completed so far. |
| total_segments | `u32` / `number` / `int` | Total segments to process. |
| records_processed | `u64` / `number` / `int` | Individual records processed. |
| total_records | `u64` / `number` / `int` | Total records to process. |

**Cancellation**: Return `false` from the callback to safely cancel compaction. No state is modified because cancellation happens before the atomic segment swap.

---

### ingest_mode

Enters bulk ingest mode. Disables auto-compaction so that rapid writes don't trigger background merges. Call [`end_ingest`](#end_ingest) when done.

```rust
db.ingest_mode();
// ... bulk writes ...
let stats = db.end_ingest()?;
```

```javascript
db.ingestMode();
// ... bulk writes ...
const stats = db.endIngest();
```

```python
db.ingest_mode()
# ... bulk writes ...
stats = db.end_ingest()
```

#### Behavior

- No compaction is triggered while in ingest mode, regardless of `compact_after_n_flushes`.
- The memtable still flushes to segments when the threshold is reached.
- Ideal for initial data loading: write millions of records, then compact once.

---

### end_ingest

Exits ingest mode and immediately compacts all segments.

```rust
let stats = db.end_ingest()?;
```

```javascript
const stats = db.endIngest(); // CompactionStats | null
```

```python
stats = db.end_ingest()  # CompactionStats | None
```

#### Returns

`CompactionStats` (same as [`compact`](#compact)), or `None`/`null` if there was nothing to compact.

---

### scrub

Runs an offline integrity check across all segments. Recomputes SHA-256 payload digests for every component and compares them to the digests recorded at write time. Reports mismatches without modifying any data.

**Rust**
```rust
let report = db.scrub()?;
println!("checked: {}, failed: {}", report.total_components_checked, report.total_components_failed);
for seg in &report.segments {
    for f in &seg.findings {
        eprintln!("segment {}: {} — {}", seg.segment_id, f.finding_type, f.detail);
    }
}
```

**Node.js**
```javascript
const report = db.scrub();
console.log(`checked: ${report.totalComponentsChecked}, failed: ${report.totalComponentsFailed}`);

// async
const report = await db.scrubAsync();
```

**Python**
```python
report = db.scrub()
print(f"checked: {report.total_components_checked}, failed: {report.total_components_failed}")

# async
report = await db.scrub()
```

#### Parameters

None.

#### Returns: ScrubReport

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| segments | `Vec<SegmentScrubResult>` | `Array<SegmentScrubResult>` | `list[SegmentScrubResult]` | Per-segment results. |
| total_components_checked | `u64` | `number` | `int` | Total components examined. |
| total_components_ok | `u64` | `number` | `int` | Components that passed all checks. |
| total_components_failed | `u64` | `number` | `int` | Components with at least one finding. |
| total_bytes_digested | `u64` | `number` | `int` | Total payload bytes hashed during the scrub. |
| duration_ms | `u64` | `number` | `int` | Wall-clock time of the scrub in milliseconds. |

#### SegmentScrubResult

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| segment_id | `u64` | `number` | `int` | Segment that was checked. |
| findings | `Vec<ComponentScrubFinding>` | `Array<ComponentScrubFinding>` | `list[ComponentScrubFinding]` | Problems found (empty if healthy). |
| components_ok | `u64` | `number` | `int` | Components that passed in this segment. |
| bytes_digested | `u64` | `number` | `int` | Payload bytes hashed in this segment. |

#### ComponentScrubFinding

| Field | Rust | Node.js | Python | Description |
|-------|------|---------|--------|-------------|
| component_kind | `String` | `string` | `str` | Which component type had the problem (e.g. `"NodeRecords"`, `"PlannerStats"`). |
| finding_type | `ScrubFindingType` | `string` | `str` | Classification: `PayloadDigestMismatch`, `ComponentIdMismatch`, `DependencyDigestMismatch`, `IdentityHeaderMismatch`, `ContainerIdMismatch`, `SegmentIdentityMismatch`, `RangeOverflow`, `RangeOverlap`, `FileMissing`, or `IoError`. |
| detail | `String` | `string` | `str` | Human-readable description of the finding. |

#### Behavior

- Scrub is **read-only** — it never modifies data on disk.
- Scrub is **offline** — it is never called automatically during open, query, flush, or compaction. You must call it explicitly.
- Segments are checked in parallel using a shared thread pool. The work is I/O-bound (streaming 64KB-buffered reads + SHA-256), not CPU-bound.
- A healthy database returns `total_components_failed == 0` and an empty `findings` array for every segment.
- If a segment directory is missing (e.g. deleted concurrently), the scrub reports a `FileMissing` finding rather than panicking.

---

## Introspection

These methods provide quick diagnostic information. They are **approximate** and counts may slightly overcount when the same ID appears in multiple memtables or segments.

### node_count

```rust
let count = db.node_count()?; // usize
```

Approximate count of live nodes across all data sources.

### edge_count

```rust
let count = db.edge_count()?; // usize
```

Approximate count of live edges.

### next_node_id

```rust
let next = db.next_node_id()?; // u64
```

Rust-only diagnostic: the next auto-assigned node ID that would be used by a new node write.

### next_edge_id

```rust
let next = db.next_edge_id()?; // u64
```

Rust-only diagnostic: the next auto-assigned edge ID that would be used by a new edge write.

### segment_count

```rust
let count = db.segment_count()?; // usize
```

Number of on-disk segments. After compaction, this is typically 0 or 1.

### segment_tombstone_node_count

```rust
let count = db.segment_tombstone_node_count()?; // usize
```

Rust-only diagnostic: deleted node records currently retained in immutable segments.

### segment_tombstone_edge_count

```rust
let count = db.segment_tombstone_edge_count()?; // usize
```

Rust-only diagnostic: deleted edge records currently retained in immutable segments.

### path

```rust
let path = db.path();
```

Returns the database directory path as `&Path`.

### manifest

Rust diagnostic API for reading the current raw manifest state.

```rust
let manifest = db.manifest()?;
println!("label token schema: {}", manifest.label_token_schema_version);
```

#### Returns: ManifestState

`ManifestState` is a raw diagnostic object. Ordinary graph APIs accept public label names, not these internal numeric IDs.

| Field | Rust | Description |
|-------|------|-------------|
| label_token_schema_version | `u32` | Node-label / edge-label catalog schema marker. |
| node_label_tokens | `BTreeMap<String, u32>` | Public node label to internal `label_id`. |
| edge_label_tokens | `BTreeMap<String, u32>` | Public edge label to internal `label_id`. |
| secondary_indexes | `Vec<SecondaryIndexManifestEntry>` | Raw optional secondary-index declarations. Node targets use `SecondaryIndexTarget::NodeProperty { label_id, prop_key }`; edge targets use `SecondaryIndexTarget::EdgeProperty { label_id, prop_key }`. |
| segments | `Vec<SegmentInfo>` | Published segment metadata. |

### manifest::load_manifest_readonly (Rust only)

Diagnostic read-only manifest loader that inspects the manifest priority chain without writing to disk.

```rust
let manifest = overgraph::manifest::load_manifest_readonly(Path::new("./my-graph"))?;
```

Returns `Result<Option<ManifestState>, EngineError>`. The returned manifest is a raw diagnostic view and may contain internal numeric token IDs.

---

## Binary Batch Ingestion

High-performance connector-only binary format for batch upserts. Avoids JSON parsing overhead. Useful when ingesting data from a custom pipeline. Rust callers use the structured `batch_upsert_nodes` and `batch_upsert_edges` APIs directly.

### batch_upsert_nodes_binary

```javascript
const buf = Buffer.alloc(/* ... */);
// Format: "OGNB", version 2, count, then per-node labels/key/props payloads.
const ids = db.batchUpsertNodesBinary(buf);
```

```python
buf = b'...'  # same binary format
ids = db.batch_upsert_nodes_binary(buf)
```

#### Binary Format (little-endian)

```
┌──────────────────────────────────────┐
│ magic: "OGNB"                        │
│ version: u16 = 2                     │
│ count: u32                           │  ← number of nodes in this batch
├──────────────────────────────────────┤
│ For each node:                       │
│   label_count: u8                    │
│   repeated label_count times:        │
│     label_len: u16                   │
│     label: [u8; label_len] (UTF-8)   │
│   weight:    f32                     │
│   key_len:   u16                     │
│   key:       [u8; key_len]  (UTF-8)  │
│   props_len: u32                     │
│   props:     [u8; props_len] (JSON)  │
└──────────────────────────────────────┘
```

#### Returns

Array of node IDs (same order as packed nodes).

Version 1 node buffers are rejected. Use version 2 for every connector so each packed node carries its full label set.

---

### batch_upsert_edges_binary

```javascript
const ids = db.batchUpsertEdgesBinary(buf);
```

```python
ids = db.batch_upsert_edges_binary(buf)
```

#### Binary Format (little-endian)

```
┌──────────────────────────────────────────┐
│ magic: "OGEB"                            │
│ version: u16 = 1                         │
│ count: u32                               │
├──────────────────────────────────────────┤
│ For each edge:                           │
│   from:       u64                        │
│   to:         u64                        │
│   label_len:  u16                       │
│   label:      [u8; label_len] (UTF-8)   │
│   weight:     f32                        │
│   valid_from: i64                        │
│   valid_to:   i64                        │
│   props_len:  u32                        │
│   props:      [u8; props_len]  (JSON)    │
└──────────────────────────────────────────┘
```

In the packed binary edge format only, `valid_from = 0` and `valid_to = 0` are sentinels for the engine defaults. `valid_from = 0` means "use the edge's `created_at` timestamp"; `valid_to = 0` means "use `i64::MAX` / no expiration." Because of these sentinels, epoch `0` cannot be represented as an explicit edge validity bound in this packed format.

---

## Error Handling

All methods can fail. Errors are returned differently across languages:

| Language | Error mechanism | Error type |
|----------|----------------|------------|
| Rust | `Result<T, EngineError>` | `EngineError` enum |
| Node.js | Thrown `Error` | Standard `Error` with message |
| Python | Raised exception | `OverGraphError(Exception)` |

### EngineError Variants (Rust)

| Variant | Description |
|---------|-------------|
| `IoError(io::Error)` | Filesystem I/O failure (disk full, permission denied, etc.). |
| `CorruptRecord(String)` | A record failed deserialization. Indicates data corruption. |
| `CorruptWal(String)` | WAL file is corrupt (truncated, bad checksum). |
| `SerializationError(String)` | Property encoding/decoding failed. |
| `ManifestError(String)` | Manifest file is corrupt or incompatible. |
| `DatabaseNotFound(String)` | Directory doesn't exist and `create_if_missing` is false. |
| `DatabaseClosed` | Operation attempted after the engine was closed. |
| `InvalidOperation(String)` | Invalid API usage (e.g., writing to a closed database). |
| `TxnConflict(String)` | Explicit write transaction conflict. No WAL entry was appended and the transaction did not commit. |
| `TxnClosed` | Explicit write transaction was already committed or rolled back. |
| `CompactionCancelled` | Compaction was cancelled via the progress callback. |
| `WalSyncFailed(String)` | WAL fsync failed. |

### Error Handling Examples

**Rust**
```rust
match db.get_node(42) {
    Ok(Some(node)) => println!("found: {}", node.key),
    Ok(None) => println!("not found"),
    Err(e) => eprintln!("error: {}", e),
}
```

**Node.js**
```javascript
try {
  const node = db.getNode(42);
} catch (e) {
  console.error('OverGraph error:', e.message);
}
```

**Python**
```python
from overgraph import OverGraph, OverGraphError

try:
    node = db.get_node(42)
except OverGraphError as e:
    print(f"OverGraph error: {e}")
```

---

## Async API

Both Node.js and Python provide async variants of all methods.

### Node.js

Every synchronous method has an async counterpart with an `Async` suffix that returns a `Promise`:

```javascript
// Sync
const node = db.getNode(42);

// Async
const node = await db.getNodeAsync(42);
```

Async methods run on the libuv thread pool. Write operations acquire an exclusive lock; read operations acquire a shared lock (allowing concurrent reads).

**Available async methods:** `closeAsync`, `ensureNodeLabelAsync`, `ensureEdgeLabelAsync`, `getNodeLabelIdAsync`, `getEdgeLabelIdAsync`, `getNodeLabelAsync`, `getEdgeLabelAsync`, `listNodeLabelsAsync`, `listEdgeLabelsAsync`, `upsertNodeAsync`, `upsertEdgeAsync`, `addNodeLabelAsync`, `removeNodeLabelAsync`, `batchUpsertNodesAsync`, `batchUpsertEdgesAsync`, `batchUpsertNodesBinaryAsync`, `batchUpsertEdgesBinaryAsync`, `getNodeAsync`, `getEdgeAsync`, `getNodeByKeyAsync`, `getEdgeByTripleAsync`, `getNodesAsync`, `getNodesByKeysAsync`, `getEdgesAsync`, `deleteNodeAsync`, `deleteEdgeAsync`, `invalidateEdgeAsync`, `graphPatchAsync`, `beginWriteTxnAsync`, `neighborsAsync`, `neighborsPagedAsync`, `neighborsBatchAsync`, `traverseAsync`, `topKNeighborsAsync`, `extractSubgraphAsync`, `shortestPathAsync`, `allShortestPathsAsync`, `isConnectedAsync`, `degreeAsync`, `degreesAsync`, `sumEdgeWeightsAsync`, `avgEdgeWeightAsync`, `findNodesAsync`, `findNodesPagedAsync`, `ensureNodePropertyIndexAsync`, `dropNodePropertyIndexAsync`, `listNodePropertyIndexesAsync`, `ensureEdgePropertyIndexAsync`, `dropEdgePropertyIndexAsync`, `listEdgePropertyIndexesAsync`, `findNodesRangeAsync`, `findNodesRangePagedAsync`, `findNodesByTimeRangeAsync`, `findNodesByTimeRangePagedAsync`, `nodesByLabelsAsync`, `edgesByLabelAsync`, `getNodesByLabelsAsync`, `getEdgesByLabelAsync`, `countNodesByLabelsAsync`, `countEdgesByLabelAsync`, `nodesByLabelsPagedAsync`, `edgesByLabelPagedAsync`, `getNodesByLabelsPagedAsync`, `getEdgesByLabelPagedAsync`, `queryNodeIdsAsync`, `queryNodesAsync`, `queryEdgeIdsAsync`, `queryEdgesAsync`, `queryPatternAsync`, `explainNodeQueryAsync`, `explainEdgeQueryAsync`, `explainPatternQueryAsync`, `personalizedPagerankAsync`, `connectedComponentsAsync`, `componentOfAsync`, `vectorSearchAsync`, `exportAdjacencyAsync`, `pruneAsync`, `setPrunePolicyAsync`, `removePrunePolicyAsync`, `listPrunePoliciesAsync`, `syncAsync`, `flushAsync`, `compactAsync`, `compactWithProgressAsync`, `ingestModeAsync`, `endIngestAsync`.

`WriteTxn` handles expose async counterparts for the full transaction surface: `upsertNodeAsync`, `upsertNodeAsAsync`, `upsertEdgeAsync`, `upsertEdgeAsAsync`, `deleteNodeAsync`, `deleteEdgeAsync`, `invalidateEdgeAsync`, `stageAsync`, `getNodeAsync`, `getEdgeAsync`, `getNodeByKeyAsync`, `getEdgeByTripleAsync`, `commitAsync`, and `rollbackAsync`. Async transaction operations on one handle execute in call order.

### Python

The `AsyncOverGraph` class wraps every `OverGraph` method with `asyncio.to_thread()`. `begin_write_txn()` returns an `AsyncWriteTxn` whose methods mirror `WriteTxn`:

```python
from overgraph import AsyncOverGraph

async def main():
    async with await AsyncOverGraph.open("./my-graph") as db:
        # Also accepts multiple labels: ["User", "Admin"]
        node_id = await db.upsert_node("User", "alice")
        node = await db.get_node(node_id)
        neighbors = await db.neighbors(node_id)

asyncio.run(main())
```

**All methods have identical signatures and semantics** to the sync `OverGraph` class but return coroutines.
`AsyncWriteTxn` also serializes operations on each transaction handle so staged writes, reads, `commit()`, and `rollback()` run in await/call order.

**GIL behavior**: The sync `OverGraph` releases the Python GIL during all Rust operations, enabling true parallelism in multi-threaded Python. The `AsyncOverGraph` uses `asyncio.to_thread()` to run sync operations in the default thread pool executor.

---

## Appendix: Quick Reference

### All Methods at a Glance

| Category | Method | Description |
|----------|--------|-------------|
| **Lifecycle** | `open` | Open or create database |
| | `close` | Shut down database |
| | `stats` | Runtime statistics |
| **Nodes** | `upsert_node` | Create or update node |
| | `get_node` | Get node by ID |
| | `get_node_by_key` | Get node by label + key |
| | `add_node_label` | Add a node label to an existing node |
| | `remove_node_label` | Remove a node label from an existing node |
| | `delete_node` | Delete node (cascade edges) |
| | `batch_upsert_nodes` | Batch create/update nodes |
| | `get_nodes` | Batch get nodes by ID |
| | `get_nodes_by_keys` | Batch get nodes by label + key |
| **Edges** | `upsert_edge` | Create or update edge |
| | `get_edge` | Get edge by ID |
| | `get_edge_by_triple` | Get edge by from + to + edge label |
| | `delete_edge` | Delete edge |
| | `invalidate_edge` | Close validity window |
| | `batch_upsert_edges` | Batch create/update edges |
| | `get_edges` | Batch get edges by ID |
| **Atomic** | `graph_patch` | Multi-op atomic batch |
| | `begin_write_txn` / `beginWriteTxn` | Explicit ordered write transaction |
| **Catalog** | `ensure_node_label` / `ensureNodeLabel` | Ensure node label token |
| | `ensure_edge_label` / `ensureEdgeLabel` | Ensure edge label token |
| | `get_node_label_id` / `getNodeLabelId` | Diagnostic name-to-ID lookup |
| | `get_edge_label_id` / `getEdgeLabelId` | Diagnostic name-to-ID lookup |
| | `get_node_label` / `getNodeLabel` | Diagnostic ID-to-name lookup |
| | `get_edge_label` / `getEdgeLabel` | Diagnostic ID-to-name lookup |
| | `list_node_labels` / `listNodeLabels` | List node-label catalog entries |
| | `list_edge_labels` / `listEdgeLabels` | List edge-label catalog entries |
| **Label and Edge-Label Queries** | `nodes_by_labels` | Node ID convenience query |
| | `edges_by_label` | All edge IDs of an edge label |
| | `get_nodes_by_labels` | Hydrated node convenience query |
| | `get_edges_by_label` | All edge records of an edge label |
| | `count_nodes_by_labels` | Node count convenience query |
| | `count_edges_by_label` | Count edges of an edge label |
| **Property Indexes** | `ensure_node_property_index` | Declare optional node equality or range index |
| | `drop_node_property_index` | Remove optional node property index declaration |
| | `list_node_property_indexes` | Inspect node declaration state |
| | `ensure_edge_property_index` | Declare optional edge equality or range index |
| | `drop_edge_property_index` | Remove optional edge property index declaration |
| | `list_edge_property_indexes` | Inspect edge declaration state |
| **Property & Time Queries** | `find_nodes` | Property search |
| | `find_nodes_range` | Numeric property range search |
| | `find_nodes_by_time_range` | Time range search |
| **Queries** | `query_node_ids` | Node query returning IDs |
| | `query_nodes` | Node query returning hydrated nodes |
| | `explain_node_query` | Explain a node query plan |
| | `query_edge_ids` | Edge query returning IDs |
| | `query_edges` | Edge query returning hydrated edges |
| | `explain_edge_query` | Explain an edge query plan |
| | `query_pattern` | Bounded graph pattern query |
| | `explain_pattern_query` | Explain a graph pattern plan |
| **Pagination** | `*_paged` | Paginated variants |
| **Traversal** | `neighbors` | Immediate neighbors |
| | `neighbors_paged` | Paginated neighbors |
| | `neighbors_batch` | Multi-node neighbors |
| | `top_k_neighbors` | Top K by score |
| | `traverse` | BFS traversal |
| | `extract_subgraph` | Subgraph extraction |
| | `shortest_path` | Shortest path |
| | `all_shortest_paths` | All shortest paths |
| | `is_connected` | Reachability check |
| **Degree & Weight** | `degree` | Edge count |
| | `degrees` | Batch edge counts |
| | `sum_edge_weights` | Sum of edge weights |
| | `avg_edge_weight` | Average edge weight |
| **Analytics** | `connected_components` | WCC decomposition |
| | `component_of` | Component membership |
| | `personalized_pagerank` | PPR scoring |
| | `export_adjacency` | Adjacency export |
| **Vectors** | `vector_search` | Dense/sparse/hybrid search |
| **Retention** | `prune` | Immediate pruning |
| | `set_prune_policy` | Register auto-prune |
| | `remove_prune_policy` | Remove auto-prune |
| | `list_prune_policies` | List policies |
| **Maintenance** | `sync` | Force WAL fsync |
| | `flush` | Memtable → segment |
| | `compact` | Merge segments |
| | `compact_with_progress` | Merge with progress |
| | `ingest_mode` | Enter bulk mode |
| | `end_ingest` | Exit bulk mode + compact |
| | `scrub` | Validate database integrity |
| **Introspection** | `path` | Database directory path |
| | `manifest` | Rust raw manifest diagnostics |
| | `next_node_id` | Rust next node ID diagnostic |
| | `next_edge_id` | Rust next edge ID diagnostic |
| | `segment_tombstone_node_count` | Rust segment node tombstone diagnostic |
| | `segment_tombstone_edge_count` | Rust segment edge tombstone diagnostic |
| | `manifest::load_manifest_readonly` | Rust read-only manifest diagnostic |
| **Binary** | `batch_upsert_nodes_binary` | Connector-only binary batch nodes |
| | `batch_upsert_edges_binary` | Connector-only binary batch edges |