meshdb-storage 0.2.0

RocksDB-backed storage engine for Mesh
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
//! RocksDB-backed implementation of [`StorageEngine`].
//!
//! Holds the on-disk state for a single local peer: nodes, edges,
//! adjacency lists, label/type/property indexes, and the index metadata
//! needed to rehydrate at `open` time. Column families carve the backend
//! into purpose-keyed namespaces so each access pattern walks a tight
//! prefix.
//!
//! External callers should hold this as `Arc<dyn StorageEngine>` and
//! route through the trait — the concrete type is only visible at the
//! construction site (`RocksDbStorageEngine::open`) and at the Raft
//! snapshot restore path, which is backend-bound by design.

use crate::{
    engine::{
        ConstraintScope, EdgePointIndexSpec, EdgePropertyIndexSpec, GraphMutation, PointIndexSpec,
        PropertyConstraintKind, PropertyConstraintSpec, PropertyIndexSpec, PropertyType,
        StorageEngine,
    },
    error::{Error, Result},
    keys::{
        adj_key, cell_from_point_index_key, constraint_meta_decode, constraint_meta_encode,
        decode_point_index_value, edge_from_adj_key, edge_id_from_property_index_key,
        edge_property_index_composite_key, edge_property_index_composite_value_prefix,
        encode_index_tuple, encode_index_value, id_from_str_index_key, label_index_key,
        label_index_prefix, node_from_adj_value, node_id_from_point_index_key,
        node_id_from_property_index_key, parse_property_index_entry_props, point_cell,
        point_cell_range, point_index_key, point_index_label_prop_prefix, point_index_srid_prefix,
        point_index_value, property_index_composite_key, property_index_composite_value_prefix,
        property_index_label_prefix, type_index_key, type_index_prefix, ID_LEN,
    },
};
use meshdb_core::{Edge, EdgeId, Node, NodeId, Property};
use rocksdb::{
    checkpoint::Checkpoint, ColumnFamilyDescriptor, Direction, IteratorMode, Options, WriteBatch,
    DB,
};
use std::path::Path;
use std::sync::RwLock;

const CF_NODES: &str = "nodes";
const CF_EDGES: &str = "edges";
const CF_ADJ_OUT: &str = "adj_out";
const CF_ADJ_IN: &str = "adj_in";
const CF_LABEL_INDEX: &str = "label_index";
const CF_TYPE_INDEX: &str = "type_index";
const CF_PROPERTY_INDEX: &str = "property_index";
const CF_INDEX_META: &str = "index_meta";
const CF_EDGE_PROPERTY_INDEX: &str = "edge_property_index";
const CF_EDGE_INDEX_META: &str = "edge_index_meta";
const CF_CONSTRAINT_META: &str = "constraint_meta";
const CF_POINT_INDEX: &str = "point_index";
const CF_POINT_INDEX_META: &str = "point_index_meta";
const CF_EDGE_POINT_INDEX: &str = "edge_point_index";
const CF_EDGE_POINT_INDEX_META: &str = "edge_point_index_meta";
/// Persisted `apoc.trigger.*` registry. Keyed by trigger name
/// (UTF-8 bytes), valued by the JSON-encoded trigger spec
/// (cypher / selector / config / installed_at). Local-only in
/// this release — the trigger registry doesn't replicate
/// across cluster peers, so each node holds its own set.
const CF_TRIGGER_META: &str = "trigger_meta";
/// Persisted multi-raft pending-tx staging. Keyed by partition-
/// namespaced txid (4-byte LE partition + txid bytes), valued by
/// the serde-encoded `Vec<GraphMutation>` to apply on `CommitTx`.
/// Lets the partition applier reconstruct `pending_txs` after a
/// restart instead of relying on openraft to re-replay entries
/// past `last_applied` (which it doesn't).
const CF_PENDING_TX_META: &str = "pending_tx_meta";

const ALL_CFS: &[&str] = &[
    CF_NODES,
    CF_EDGES,
    CF_ADJ_OUT,
    CF_ADJ_IN,
    CF_LABEL_INDEX,
    CF_TYPE_INDEX,
    CF_PROPERTY_INDEX,
    CF_INDEX_META,
    CF_EDGE_PROPERTY_INDEX,
    CF_EDGE_INDEX_META,
    CF_CONSTRAINT_META,
    CF_POINT_INDEX,
    CF_POINT_INDEX_META,
    CF_EDGE_POINT_INDEX,
    CF_EDGE_POINT_INDEX_META,
    CF_TRIGGER_META,
    CF_PENDING_TX_META,
];

const EMPTY: &[u8] = &[];

/// Encode a [`PropertyIndexSpec`] as a stable `CF_INDEX_META` key:
/// `<label>\0<prop1>\0<prop2>\0...\0<propN>`. No component can contain
/// a NUL (identifier-only grammar), so splitting on NUL decodes
/// unambiguously. Length-1 specs encode byte-identically to the
/// pre-composite-refactor format (`<label>\0<prop>`), so existing
/// on-disk data survives the upgrade.
fn index_meta_key(spec: &PropertyIndexSpec) -> Vec<u8> {
    let cap = spec.label.len()
        + spec.properties.iter().map(|p| p.len()).sum::<usize>()
        + spec.properties.len();
    let mut k = Vec::with_capacity(cap);
    k.extend_from_slice(spec.label.as_bytes());
    for p in &spec.properties {
        k.push(0);
        k.extend_from_slice(p.as_bytes());
    }
    k
}

fn index_meta_key_decode(key: &[u8]) -> Result<PropertyIndexSpec> {
    let mut parts = key.split(|b| *b == 0);
    let label_bytes = parts.next().ok_or(Error::CorruptBytes {
        cf: CF_INDEX_META,
        expected: 1,
        actual: 0,
    })?;
    let label = std::str::from_utf8(label_bytes)
        .map_err(|_| Error::CorruptBytes {
            cf: CF_INDEX_META,
            expected: label_bytes.len(),
            actual: label_bytes.len(),
        })?
        .to_string();
    let mut properties: Vec<String> = Vec::new();
    for part in parts {
        let s = std::str::from_utf8(part)
            .map_err(|_| Error::CorruptBytes {
                cf: CF_INDEX_META,
                expected: part.len(),
                actual: part.len(),
            })?
            .to_string();
        properties.push(s);
    }
    if properties.is_empty() {
        return Err(Error::CorruptBytes {
            cf: CF_INDEX_META,
            expected: 1,
            actual: 0,
        });
    }
    Ok(PropertyIndexSpec { label, properties })
}

/// Encode an [`EdgePropertyIndexSpec`] as a stable `CF_EDGE_INDEX_META`
/// key: `<edge_type>\0<prop1>\0<prop2>\0...\0<propN>`. Same NUL-split
/// shape as the node form, same backward-compat guarantee for
/// length-1 specs.
fn edge_index_meta_key(spec: &EdgePropertyIndexSpec) -> Vec<u8> {
    let cap = spec.edge_type.len()
        + spec.properties.iter().map(|p| p.len()).sum::<usize>()
        + spec.properties.len();
    let mut k = Vec::with_capacity(cap);
    k.extend_from_slice(spec.edge_type.as_bytes());
    for p in &spec.properties {
        k.push(0);
        k.extend_from_slice(p.as_bytes());
    }
    k
}

fn edge_index_meta_key_decode(key: &[u8]) -> Result<EdgePropertyIndexSpec> {
    let mut parts = key.split(|b| *b == 0);
    let type_bytes = parts.next().ok_or(Error::CorruptBytes {
        cf: CF_EDGE_INDEX_META,
        expected: 1,
        actual: 0,
    })?;
    let edge_type = std::str::from_utf8(type_bytes)
        .map_err(|_| Error::CorruptBytes {
            cf: CF_EDGE_INDEX_META,
            expected: type_bytes.len(),
            actual: type_bytes.len(),
        })?
        .to_string();
    let mut properties: Vec<String> = Vec::new();
    for part in parts {
        let s = std::str::from_utf8(part)
            .map_err(|_| Error::CorruptBytes {
                cf: CF_EDGE_INDEX_META,
                expected: part.len(),
                actual: part.len(),
            })?
            .to_string();
        properties.push(s);
    }
    if properties.is_empty() {
        return Err(Error::CorruptBytes {
            cf: CF_EDGE_INDEX_META,
            expected: 1,
            actual: 0,
        });
    }
    Ok(EdgePropertyIndexSpec {
        edge_type,
        properties,
    })
}

/// Encode a [`PointIndexSpec`] as a stable `CF_POINT_INDEX_META`
/// key: `<label>\0<property>`. Single-property on purpose — the
/// spec only carries one property. NUL-split, same shape as the
/// non-spatial index meta format so tooling that inspects CFs by
/// hand stays predictable.
fn point_index_meta_key(spec: &PointIndexSpec) -> Vec<u8> {
    let mut k = Vec::with_capacity(spec.label.len() + spec.property.len() + 1);
    k.extend_from_slice(spec.label.as_bytes());
    k.push(0);
    k.extend_from_slice(spec.property.as_bytes());
    k
}

fn point_index_meta_key_decode(key: &[u8]) -> Result<PointIndexSpec> {
    let mut parts = key.splitn(2, |b| *b == 0);
    let label_bytes = parts.next().ok_or(Error::CorruptBytes {
        cf: CF_POINT_INDEX_META,
        expected: 1,
        actual: 0,
    })?;
    let property_bytes = parts.next().ok_or(Error::CorruptBytes {
        cf: CF_POINT_INDEX_META,
        expected: label_bytes.len() + 2,
        actual: key.len(),
    })?;
    let label = std::str::from_utf8(label_bytes)
        .map_err(|_| Error::CorruptBytes {
            cf: CF_POINT_INDEX_META,
            expected: label_bytes.len(),
            actual: label_bytes.len(),
        })?
        .to_string();
    let property = std::str::from_utf8(property_bytes)
        .map_err(|_| Error::CorruptBytes {
            cf: CF_POINT_INDEX_META,
            expected: property_bytes.len(),
            actual: property_bytes.len(),
        })?
        .to_string();
    if property.is_empty() {
        return Err(Error::CorruptBytes {
            cf: CF_POINT_INDEX_META,
            expected: 1,
            actual: 0,
        });
    }
    Ok(PointIndexSpec { label, property })
}

/// Relationship-scope analogue of [`point_index_meta_key`]. Same
/// `<edge_type>\0<property>` shape.
fn edge_point_index_meta_key(spec: &EdgePointIndexSpec) -> Vec<u8> {
    let mut k = Vec::with_capacity(spec.edge_type.len() + spec.property.len() + 1);
    k.extend_from_slice(spec.edge_type.as_bytes());
    k.push(0);
    k.extend_from_slice(spec.property.as_bytes());
    k
}

fn edge_point_index_meta_key_decode(key: &[u8]) -> Result<EdgePointIndexSpec> {
    let mut parts = key.splitn(2, |b| *b == 0);
    let type_bytes = parts.next().ok_or(Error::CorruptBytes {
        cf: CF_EDGE_POINT_INDEX_META,
        expected: 1,
        actual: 0,
    })?;
    let property_bytes = parts.next().ok_or(Error::CorruptBytes {
        cf: CF_EDGE_POINT_INDEX_META,
        expected: type_bytes.len() + 2,
        actual: key.len(),
    })?;
    let edge_type = std::str::from_utf8(type_bytes)
        .map_err(|_| Error::CorruptBytes {
            cf: CF_EDGE_POINT_INDEX_META,
            expected: type_bytes.len(),
            actual: type_bytes.len(),
        })?
        .to_string();
    let property = std::str::from_utf8(property_bytes)
        .map_err(|_| Error::CorruptBytes {
            cf: CF_EDGE_POINT_INDEX_META,
            expected: property_bytes.len(),
            actual: property_bytes.len(),
        })?
        .to_string();
    if property.is_empty() {
        return Err(Error::CorruptBytes {
            cf: CF_EDGE_POINT_INDEX_META,
            expected: 1,
            actual: 0,
        });
    }
    Ok(EdgePointIndexSpec {
        edge_type,
        property,
    })
}

pub struct RocksDbStorageEngine {
    db: DB,
    /// In-memory view of the registered property indexes, populated
    /// from [`CF_INDEX_META`] at open time and kept in sync by
    /// [`RocksDbStorageEngine::create_property_index`] and
    /// [`RocksDbStorageEngine::drop_property_index`].
    ///
    /// The write-path consults this on every `append_put_node` /
    /// `append_detach_delete_node` call to decide which index entries
    /// to emit, so it absolutely must not hit the DB on the hot path.
    /// `RwLock` rather than `Mutex` because the common access pattern
    /// is many concurrent reads with only DDL-time writes.
    indexes: RwLock<Vec<PropertyIndexSpec>>,
    /// Relationship-scope analogue of `indexes`. Populated from
    /// [`CF_EDGE_INDEX_META`] at open time and kept in sync by
    /// [`RocksDbStorageEngine::create_edge_property_index`] /
    /// [`RocksDbStorageEngine::drop_edge_property_index`]. Consulted on
    /// every edge write path (`append_put_edge`, `append_delete_edge`,
    /// `append_detach_delete_node`) and by UNIQUE edge-constraint
    /// enforcement, so the same "must not hit the DB on the hot path"
    /// contract applies.
    edge_indexes: RwLock<Vec<EdgePropertyIndexSpec>>,
    /// In-memory view of the registered property constraints,
    /// populated from [`CF_CONSTRAINT_META`] at open time and kept in
    /// sync by [`RocksDbStorageEngine::create_property_constraint`] and
    /// [`RocksDbStorageEngine::drop_property_constraint`].
    ///
    /// Every `put_node` consults this to validate UNIQUE / NOT NULL
    /// invariants, so — as with `indexes` — it must not hit the DB on
    /// the hot path. Enforcement reads the catalog under a read lock
    /// and runs `nodes_by_property` against the backing index only
    /// when a UNIQUE check actually needs it.
    constraints: RwLock<Vec<PropertyConstraintSpec>>,
    /// In-memory view of the registered point indexes. Loaded from
    /// [`CF_POINT_INDEX_META`] at open and kept in sync by
    /// [`RocksDbStorageEngine::create_point_index`] /
    /// [`RocksDbStorageEngine::drop_point_index`]. `append_put_node`
    /// and `append_detach_delete_node` walk this list to maintain
    /// entries, so — as with the other in-memory index catalogs — it
    /// must not hit the DB on the hot path.
    point_indexes: RwLock<Vec<PointIndexSpec>>,
    /// Relationship-scope analogue of `point_indexes`. Consulted by
    /// every edge write (`append_put_edge`, `append_delete_edge`,
    /// `append_detach_delete_node`) to maintain
    /// [`CF_EDGE_POINT_INDEX`] entries.
    edge_point_indexes: RwLock<Vec<EdgePointIndexSpec>>,
}

/// Operator-tunable rocksdb options. Defaults match what
/// [`RocksDbStorageEngine::open`] applied historically (modest
/// `max_open_files`, capped LOG retention) — production
/// deployments override via the [`storage]` config section.
#[derive(Debug, Clone)]
pub struct StorageOptions {
    /// Cap on open SST files. RocksDB's default of -1 keeps
    /// every SST in the table cache forever, which blows past
    /// typical FD soft limits in CI / test setups. 64 is plenty
    /// for the hot set in the foundational test suites; bump
    /// for production read-heavy workloads.
    pub max_open_files: i32,
    /// Maximum number of historical INFO log files to keep on
    /// disk. RocksDB's default is 1000 which produces a long
    /// tail of LOG.old.* files that compounds disk pressure
    /// when many databases run in parallel.
    pub keep_log_file_num: usize,
    /// Per-column-family memtable size (write buffer). Bigger
    /// = fewer L0 files + more memory per CF. RocksDB's default
    /// is 64MB; tuning below that helps small / many-tenant
    /// deployments, above for write-heavy single-tenant ones.
    /// `None` keeps the upstream default.
    pub write_buffer_size_bytes: Option<usize>,
    /// Maximum number of memtables before writes stall. Bigger
    /// = more headroom for write bursts at the cost of memory.
    /// RocksDB's default is 2; 4-8 is common for write-heavy
    /// loads. `None` keeps the upstream default.
    pub max_write_buffer_number: Option<i32>,
    /// Bloom filter bits per key on the block-based table
    /// format. Bigger = lower false-positive rate on point
    /// reads at the cost of memory. RocksDB's default builds
    /// no bloom filter unless explicitly configured; 10 bits
    /// gives ~1% FP rate and is the typical recommendation.
    /// `None` keeps the upstream default (no bloom filter).
    pub bloom_filter_bits_per_key: Option<i32>,
}

impl Default for StorageOptions {
    fn default() -> Self {
        Self {
            max_open_files: 64,
            keep_log_file_num: 4,
            write_buffer_size_bytes: None,
            max_write_buffer_number: None,
            bloom_filter_bits_per_key: None,
        }
    }
}

impl RocksDbStorageEngine {
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        Self::open_with_options(path, StorageOptions::default())
    }

    /// Open with operator-tunable rocksdb knobs. Applied to both
    /// the database-level options (FD cap, LOG retention) and
    /// every column family's table options (bloom filter, write
    /// buffer). Defaults match [`RocksDbStorageEngine::open`].
    pub fn open_with_options(path: impl AsRef<Path>, opts: StorageOptions) -> Result<Self> {
        let mut db_opts = Options::default();
        db_opts.create_if_missing(true);
        db_opts.create_missing_column_families(true);
        db_opts.set_max_open_files(opts.max_open_files);
        db_opts.set_keep_log_file_num(opts.keep_log_file_num);

        // Per-CF options. Same options applied to every column
        // family — none of them have wildly different access
        // patterns, and the cost of tuning each independently
        // exceeds the win for v1.
        let mut cf_opts = Options::default();
        if let Some(sz) = opts.write_buffer_size_bytes {
            cf_opts.set_write_buffer_size(sz);
        }
        if let Some(n) = opts.max_write_buffer_number {
            cf_opts.set_max_write_buffer_number(n);
        }
        if let Some(bits) = opts.bloom_filter_bits_per_key {
            let mut block_opts = rocksdb::BlockBasedOptions::default();
            block_opts.set_bloom_filter(bits as f64, false);
            cf_opts.set_block_based_table_factory(&block_opts);
        }

        let cfs: Vec<ColumnFamilyDescriptor> = ALL_CFS
            .iter()
            .map(|name| ColumnFamilyDescriptor::new(*name, cf_opts.clone()))
            .collect();

        let db = DB::open_cf_descriptors(&db_opts, path, cfs)?;
        let indexes = load_index_meta(&db)?;
        let edge_indexes = load_edge_index_meta(&db)?;
        let constraints = load_constraint_meta(&db)?;
        let point_indexes = load_point_index_meta(&db)?;
        let edge_point_indexes = load_edge_point_index_meta(&db)?;
        Ok(Self {
            db,
            indexes: RwLock::new(indexes),
            edge_indexes: RwLock::new(edge_indexes),
            constraints: RwLock::new(constraints),
            point_indexes: RwLock::new(point_indexes),
            edge_point_indexes: RwLock::new(edge_point_indexes),
        })
    }

    fn cf(&self, name: &'static str) -> Result<&rocksdb::ColumnFamily> {
        self.db
            .cf_handle(name)
            .ok_or(Error::MissingColumnFamily(name))
    }

    pub fn put_node(&self, node: &Node) -> Result<()> {
        let mut batch = WriteBatch::default();
        self.append_put_node(&mut batch, node)?;
        self.db.write(batch)?;
        Ok(())
    }

    fn append_put_node(&self, batch: &mut WriteBatch, node: &Node) -> Result<()> {
        let nodes_cf = self.cf(CF_NODES)?;
        let label_cf = self.cf(CF_LABEL_INDEX)?;
        let prop_cf = self.cf(CF_PROPERTY_INDEX)?;

        let existing: Option<Node> = match self.db.get_cf(nodes_cf, node.id.as_bytes())? {
            Some(bytes) => Some(serde_json::from_slice(&bytes)?),
            None => None,
        };
        let existing_labels: &[String] = existing.as_ref().map(|n| &n.labels[..]).unwrap_or(&[]);

        // Constraint enforcement: walk every registered constraint and
        // confirm the post-write state satisfies it. UNIQUE queries
        // the backing property index (guaranteed to exist — see
        // `create_property_constraint`) for rival holders of the same
        // value. NOT NULL checks the incoming property map directly.
        // Runs before we touch the batch, so a violation short-circuits
        // without leaving partial writes behind.
        self.enforce_constraints(node, existing.as_ref())?;

        let bytes = serde_json::to_vec(node)?;
        batch.put_cf(nodes_cf, node.id.as_bytes(), bytes);

        for old in existing_labels {
            if !node.labels.contains(old) {
                batch.delete_cf(label_cf, label_index_key(old, node.id));
            }
        }
        for new in &node.labels {
            if !existing_labels.contains(new) {
                batch.put_cf(label_cf, label_index_key(new, node.id), EMPTY);
            }
        }

        // Property-index maintenance: for each registered (label, prop)
        // index, compute the delta between the previous entry (if any)
        // and the new one, and emit the minimal set of put/delete
        // operations. Skipping an update when the entry is unchanged
        // keeps steady-state writes free of index churn.
        let indexes = self.indexes.read().expect("indexes lock poisoned");
        for spec in indexes.iter() {
            let was_indexed = existing_labels.iter().any(|l| l == &spec.label);
            let now_indexed = node.labels.iter().any(|l| l == &spec.label);
            let old_encoded = if was_indexed {
                existing
                    .as_ref()
                    .and_then(|n| encode_index_tuple(&n.properties, &spec.properties))
            } else {
                None
            };
            let new_encoded = if now_indexed {
                encode_index_tuple(&node.properties, &spec.properties)
            } else {
                None
            };
            if old_encoded == new_encoded {
                continue;
            }
            if let Some(values) = &old_encoded {
                batch.delete_cf(
                    prop_cf,
                    property_index_composite_key(&spec.label, &spec.properties, values, node.id),
                );
            }
            if let Some(values) = &new_encoded {
                batch.put_cf(
                    prop_cf,
                    property_index_composite_key(&spec.label, &spec.properties, values, node.id),
                    EMPTY,
                );
            }
        }

        // Point-index maintenance. Same delta shape as the
        // property-index loop: compare old vs new indexed point and
        // emit the minimum entry set. Cheap-bail when neither the
        // label membership nor the point value has changed.
        let point_indexes = self
            .point_indexes
            .read()
            .expect("point_indexes lock poisoned");
        if !point_indexes.is_empty() {
            let point_cf = self.cf(CF_POINT_INDEX)?;
            for spec in point_indexes.iter() {
                let was_indexed = existing_labels.iter().any(|l| l == &spec.label);
                let now_indexed = node.labels.iter().any(|l| l == &spec.label);
                let old_point = if was_indexed {
                    existing
                        .as_ref()
                        .and_then(|n| extract_indexable_point(&n.properties, &spec.property))
                } else {
                    None
                };
                let new_point = if now_indexed {
                    extract_indexable_point(&node.properties, &spec.property)
                } else {
                    None
                };
                if old_point == new_point {
                    continue;
                }
                if let Some(p) = &old_point {
                    let cell = point_cell(p.srid, p.x, p.y);
                    batch.delete_cf(
                        point_cf,
                        point_index_key(
                            &spec.label,
                            &spec.property,
                            p.srid,
                            cell,
                            node.id.as_bytes(),
                        ),
                    );
                }
                if let Some(p) = &new_point {
                    let cell = point_cell(p.srid, p.x, p.y);
                    batch.put_cf(
                        point_cf,
                        point_index_key(
                            &spec.label,
                            &spec.property,
                            p.srid,
                            cell,
                            node.id.as_bytes(),
                        ),
                        point_index_value(p.x, p.y, p.z),
                    );
                }
            }
        }

        Ok(())
    }

    pub fn get_node(&self, id: NodeId) -> Result<Option<Node>> {
        let cf = self.cf(CF_NODES)?;
        match self.db.get_cf(cf, id.as_bytes())? {
            Some(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
            None => Ok(None),
        }
    }

    pub fn put_edge(&self, edge: &Edge) -> Result<()> {
        let mut batch = WriteBatch::default();
        self.append_put_edge(&mut batch, edge)?;
        self.db.write(batch)?;
        Ok(())
    }

    fn append_put_edge(&self, batch: &mut WriteBatch, edge: &Edge) -> Result<()> {
        let edges_cf = self.cf(CF_EDGES)?;
        let out_cf = self.cf(CF_ADJ_OUT)?;
        let in_cf = self.cf(CF_ADJ_IN)?;
        let type_cf = self.cf(CF_TYPE_INDEX)?;
        let edge_prop_cf = self.cf(CF_EDGE_PROPERTY_INDEX)?;

        // Relationship-scope constraint enforcement. Same short-
        // circuit pattern as `append_put_node` — if a constraint
        // would be violated, abort before touching the batch so the
        // write never lands.
        let existing_edge = self.get_edge(edge.id)?;
        self.enforce_edge_constraints(edge, existing_edge.as_ref())?;

        let bytes = serde_json::to_vec(edge)?;
        batch.put_cf(edges_cf, edge.id.as_bytes(), bytes);
        batch.put_cf(
            out_cf,
            adj_key(edge.source, edge.id),
            edge.target.as_bytes(),
        );
        batch.put_cf(in_cf, adj_key(edge.target, edge.id), edge.source.as_bytes());
        batch.put_cf(type_cf, type_index_key(&edge.edge_type, edge.id), EMPTY);

        // Edge-property-index maintenance: for each registered
        // (edge_type, prop) index, delta the previous entry against
        // the new one and emit the minimal set of put/delete
        // operations. Mirrors the node path in `append_put_node`.
        // An existing edge whose type doesn't match the registered
        // index contributes no work — edges never change their type,
        // so a type-mismatched entry can't exist to clean up.
        let edge_indexes = self
            .edge_indexes
            .read()
            .expect("edge_indexes lock poisoned");
        for spec in edge_indexes.iter() {
            if spec.edge_type != edge.edge_type {
                continue;
            }
            let old_encoded = existing_edge
                .as_ref()
                .and_then(|e| encode_index_tuple(&e.properties, &spec.properties));
            let new_encoded = encode_index_tuple(&edge.properties, &spec.properties);
            if old_encoded == new_encoded {
                continue;
            }
            if let Some(values) = &old_encoded {
                batch.delete_cf(
                    edge_prop_cf,
                    edge_property_index_composite_key(
                        &spec.edge_type,
                        &spec.properties,
                        values,
                        edge.id,
                    ),
                );
            }
            if let Some(values) = &new_encoded {
                batch.put_cf(
                    edge_prop_cf,
                    edge_property_index_composite_key(
                        &spec.edge_type,
                        &spec.properties,
                        values,
                        edge.id,
                    ),
                    EMPTY,
                );
            }
        }

        // Edge-point-index maintenance — relationship-scope mirror
        // of the node-point-index loop in `append_put_node`. Same
        // delta shape: diff the indexed point across the previous
        // and new edge state and emit the minimum put/delete set.
        let edge_point_indexes = self
            .edge_point_indexes
            .read()
            .expect("edge_point_indexes lock poisoned");
        if !edge_point_indexes.is_empty() {
            let point_cf = self.cf(CF_EDGE_POINT_INDEX)?;
            for spec in edge_point_indexes.iter() {
                if spec.edge_type != edge.edge_type {
                    continue;
                }
                let old_point = existing_edge
                    .as_ref()
                    .and_then(|e| extract_indexable_point(&e.properties, &spec.property));
                let new_point = extract_indexable_point(&edge.properties, &spec.property);
                if old_point == new_point {
                    continue;
                }
                if let Some(p) = &old_point {
                    let cell = point_cell(p.srid, p.x, p.y);
                    batch.delete_cf(
                        point_cf,
                        point_index_key(
                            &spec.edge_type,
                            &spec.property,
                            p.srid,
                            cell,
                            edge.id.as_bytes(),
                        ),
                    );
                }
                if let Some(p) = &new_point {
                    let cell = point_cell(p.srid, p.x, p.y);
                    batch.put_cf(
                        point_cf,
                        point_index_key(
                            &spec.edge_type,
                            &spec.property,
                            p.srid,
                            cell,
                            edge.id.as_bytes(),
                        ),
                        point_index_value(p.x, p.y, p.z),
                    );
                }
            }
        }
        Ok(())
    }

    pub fn get_edge(&self, id: EdgeId) -> Result<Option<Edge>> {
        let cf = self.cf(CF_EDGES)?;
        match self.db.get_cf(cf, id.as_bytes())? {
            Some(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
            None => Ok(None),
        }
    }

    pub fn delete_edge(&self, id: EdgeId) -> Result<()> {
        let edge = self.get_edge(id)?.ok_or(Error::EdgeNotFound(id))?;
        let mut batch = WriteBatch::default();
        self.append_delete_edge(&mut batch, id, &edge)?;
        self.db.write(batch)?;
        Ok(())
    }

    fn append_delete_edge(&self, batch: &mut WriteBatch, id: EdgeId, edge: &Edge) -> Result<()> {
        let edges_cf = self.cf(CF_EDGES)?;
        let out_cf = self.cf(CF_ADJ_OUT)?;
        let in_cf = self.cf(CF_ADJ_IN)?;
        let type_cf = self.cf(CF_TYPE_INDEX)?;
        let edge_prop_cf = self.cf(CF_EDGE_PROPERTY_INDEX)?;

        batch.delete_cf(edges_cf, id.as_bytes());
        batch.delete_cf(out_cf, adj_key(edge.source, id));
        batch.delete_cf(in_cf, adj_key(edge.target, id));
        batch.delete_cf(type_cf, type_index_key(&edge.edge_type, id));

        // Remove any edge-property-index entries this edge owned.
        // Mirrors the put path: for each registered index whose type
        // matches, the encoded value (if any) pinned an index key we
        // now need to delete.
        let edge_indexes = self
            .edge_indexes
            .read()
            .expect("edge_indexes lock poisoned");
        for spec in edge_indexes.iter() {
            if spec.edge_type != edge.edge_type {
                continue;
            }
            if let Some(values) = encode_index_tuple(&edge.properties, &spec.properties) {
                batch.delete_cf(
                    edge_prop_cf,
                    edge_property_index_composite_key(
                        &spec.edge_type,
                        &spec.properties,
                        &values,
                        id,
                    ),
                );
            }
        }

        // Edge-point-index sweep for the deleted edge. Mirrors the
        // node-point-index sweep in `append_detach_delete_node`.
        let edge_point_indexes = self
            .edge_point_indexes
            .read()
            .expect("edge_point_indexes lock poisoned");
        if !edge_point_indexes.is_empty() {
            let point_cf = self.cf(CF_EDGE_POINT_INDEX)?;
            for spec in edge_point_indexes.iter() {
                if spec.edge_type != edge.edge_type {
                    continue;
                }
                if let Some(p) = extract_indexable_point(&edge.properties, &spec.property) {
                    let cell = point_cell(p.srid, p.x, p.y);
                    batch.delete_cf(
                        point_cf,
                        point_index_key(
                            &spec.edge_type,
                            &spec.property,
                            p.srid,
                            cell,
                            id.as_bytes(),
                        ),
                    );
                }
            }
        }
        Ok(())
    }

    pub fn detach_delete_node(&self, id: NodeId) -> Result<()> {
        let mut batch = WriteBatch::default();
        self.append_detach_delete_node(&mut batch, id)?;
        self.db.write(batch)?;
        Ok(())
    }

    fn append_detach_delete_node(&self, batch: &mut WriteBatch, id: NodeId) -> Result<()> {
        let node = self.get_node(id)?;
        let outgoing = self.outgoing(id)?;
        let incoming = self.incoming(id)?;

        let nodes_cf = self.cf(CF_NODES)?;
        let edges_cf = self.cf(CF_EDGES)?;
        let out_cf = self.cf(CF_ADJ_OUT)?;
        let in_cf = self.cf(CF_ADJ_IN)?;
        let label_cf = self.cf(CF_LABEL_INDEX)?;
        let type_cf = self.cf(CF_TYPE_INDEX)?;
        let prop_cf = self.cf(CF_PROPERTY_INDEX)?;
        let edge_prop_cf = self.cf(CF_EDGE_PROPERTY_INDEX)?;

        if let Some(n) = &node {
            for label in &n.labels {
                batch.delete_cf(label_cf, label_index_key(label, id));
            }
            // Remove every property-index entry this node was holding
            // open. Mirrors the put path: for each registered index
            // whose label matches, if the node carries an indexable
            // value for the property, delete the corresponding entry.
            let indexes = self.indexes.read().expect("indexes lock poisoned");
            for spec in indexes.iter() {
                if !n.labels.iter().any(|l| l == &spec.label) {
                    continue;
                }
                if let Some(values) = encode_index_tuple(&n.properties, &spec.properties) {
                    batch.delete_cf(
                        prop_cf,
                        property_index_composite_key(&spec.label, &spec.properties, &values, id),
                    );
                }
            }
            // Point-index entries held by this node, mirror of the
            // property-index sweep above.
            let point_indexes = self
                .point_indexes
                .read()
                .expect("point_indexes lock poisoned");
            if !point_indexes.is_empty() {
                let point_cf = self.cf(CF_POINT_INDEX)?;
                for spec in point_indexes.iter() {
                    if !n.labels.iter().any(|l| l == &spec.label) {
                        continue;
                    }
                    if let Some(p) = extract_indexable_point(&n.properties, &spec.property) {
                        let cell = point_cell(p.srid, p.x, p.y);
                        batch.delete_cf(
                            point_cf,
                            point_index_key(
                                &spec.label,
                                &spec.property,
                                p.srid,
                                cell,
                                id.as_bytes(),
                            ),
                        );
                    }
                }
            }
        }

        // Edges detached by this delete also need their
        // edge-property-index entries swept. Read the catalog once so
        // the inner loop doesn't reacquire the lock per edge.
        let edge_indexes_snapshot = self
            .edge_indexes
            .read()
            .expect("edge_indexes lock poisoned")
            .clone();
        let edge_point_indexes_snapshot = self
            .edge_point_indexes
            .read()
            .expect("edge_point_indexes lock poisoned")
            .clone();
        let edge_point_cf_opt = if edge_point_indexes_snapshot.is_empty() {
            None
        } else {
            Some(self.cf(CF_EDGE_POINT_INDEX)?)
        };

        for (edge_id, target) in &outgoing {
            if let Some(e) = self.get_edge(*edge_id)? {
                batch.delete_cf(type_cf, type_index_key(&e.edge_type, *edge_id));
                for spec in &edge_indexes_snapshot {
                    if spec.edge_type != e.edge_type {
                        continue;
                    }
                    if let Some(values) = encode_index_tuple(&e.properties, &spec.properties) {
                        batch.delete_cf(
                            edge_prop_cf,
                            edge_property_index_composite_key(
                                &spec.edge_type,
                                &spec.properties,
                                &values,
                                *edge_id,
                            ),
                        );
                    }
                }
                if let Some(point_cf) = edge_point_cf_opt {
                    for spec in &edge_point_indexes_snapshot {
                        if spec.edge_type != e.edge_type {
                            continue;
                        }
                        if let Some(p) = extract_indexable_point(&e.properties, &spec.property) {
                            let cell = point_cell(p.srid, p.x, p.y);
                            batch.delete_cf(
                                point_cf,
                                point_index_key(
                                    &spec.edge_type,
                                    &spec.property,
                                    p.srid,
                                    cell,
                                    edge_id.as_bytes(),
                                ),
                            );
                        }
                    }
                }
            }
            batch.delete_cf(edges_cf, edge_id.as_bytes());
            batch.delete_cf(out_cf, adj_key(id, *edge_id));
            batch.delete_cf(in_cf, adj_key(*target, *edge_id));
        }
        for (edge_id, source) in &incoming {
            if let Some(e) = self.get_edge(*edge_id)? {
                batch.delete_cf(type_cf, type_index_key(&e.edge_type, *edge_id));
                for spec in &edge_indexes_snapshot {
                    if spec.edge_type != e.edge_type {
                        continue;
                    }
                    if let Some(values) = encode_index_tuple(&e.properties, &spec.properties) {
                        batch.delete_cf(
                            edge_prop_cf,
                            edge_property_index_composite_key(
                                &spec.edge_type,
                                &spec.properties,
                                &values,
                                *edge_id,
                            ),
                        );
                    }
                }
                if let Some(point_cf) = edge_point_cf_opt {
                    for spec in &edge_point_indexes_snapshot {
                        if spec.edge_type != e.edge_type {
                            continue;
                        }
                        if let Some(p) = extract_indexable_point(&e.properties, &spec.property) {
                            let cell = point_cell(p.srid, p.x, p.y);
                            batch.delete_cf(
                                point_cf,
                                point_index_key(
                                    &spec.edge_type,
                                    &spec.property,
                                    p.srid,
                                    cell,
                                    edge_id.as_bytes(),
                                ),
                            );
                        }
                    }
                }
            }
            batch.delete_cf(edges_cf, edge_id.as_bytes());
            batch.delete_cf(out_cf, adj_key(*source, *edge_id));
            batch.delete_cf(in_cf, adj_key(id, *edge_id));
        }
        batch.delete_cf(nodes_cf, id.as_bytes());
        Ok(())
    }

    /// Apply a sequence of mutations as one atomic rocksdb write. Either
    /// every mutation lands or none does — no replica can observe a
    /// partial result, even across a process crash.
    ///
    /// Reads performed during batch construction (existing labels for
    /// PutNode, edge metadata for DeleteEdge / DetachDeleteNode) hit the
    /// live store, not the in-flight batch. Read-your-writes across
    /// mutations in the same batch is *not* supported. The executor never
    /// generates such patterns: it produces fresh ids per row and
    /// dedupes mutated entities before flushing.
    pub fn apply_batch(&self, mutations: &[GraphMutation]) -> Result<()> {
        let mut batch = WriteBatch::default();
        for m in mutations {
            match m {
                GraphMutation::PutNode(n) => self.append_put_node(&mut batch, n)?,
                GraphMutation::PutEdge(e) => self.append_put_edge(&mut batch, e)?,
                GraphMutation::DeleteEdge(id) => {
                    if let Some(edge) = self.get_edge(*id)? {
                        self.append_delete_edge(&mut batch, *id, &edge)?;
                    }
                }
                GraphMutation::DetachDeleteNode(id) => {
                    self.append_detach_delete_node(&mut batch, *id)?;
                }
            }
        }
        self.db.write(batch)?;
        Ok(())
    }

    /// Walk every node in the store. Used for snapshot construction; not
    /// suitable as a query primitive since it materializes the full set.
    pub fn all_nodes(&self) -> Result<Vec<Node>> {
        let cf = self.cf(CF_NODES)?;
        let mut nodes = Vec::new();
        for item in self.db.iterator_cf(cf, IteratorMode::Start) {
            let (_, value) = item?;
            nodes.push(serde_json::from_slice(&value)?);
        }
        Ok(nodes)
    }

    /// Walk every edge in the store. Used for snapshot construction.
    pub fn all_edges(&self) -> Result<Vec<Edge>> {
        let cf = self.cf(CF_EDGES)?;
        let mut edges = Vec::new();
        for item in self.db.iterator_cf(cf, IteratorMode::Start) {
            let (_, value) = item?;
            edges.push(serde_json::from_slice(&value)?);
        }
        Ok(edges)
    }

    /// Produce a consistent point-in-time checkpoint of the store at
    /// `path`. Wraps rocksdb's [`Checkpoint`] API — on the same
    /// filesystem the checkpoint is effectively free (hard links over
    /// the underlying SST files); cross-filesystem it falls back to a
    /// full copy. `path` must NOT already exist; rocksdb creates it.
    ///
    /// Used by the Raft state machine's streaming snapshot path: a
    /// snapshot is built by checkpointing into a temp dir, packing
    /// the checkpoint's files into a length-prefixed archive, and
    /// shipping the bytes. Skips the "Vec<Node> in memory" materialization
    /// path that the previous JSON-over-everything snapshot used.
    pub fn create_checkpoint(&self, path: impl AsRef<Path>) -> Result<()> {
        let checkpoint = Checkpoint::new(&self.db)?;
        checkpoint.create_checkpoint(path)?;
        Ok(())
    }

    /// Drop every key from every column family. Used by snapshot install
    /// to wipe local state before applying the leader's snapshot. Cheap
    /// for empty / small stores; for large stores this is O(n).
    pub fn clear_all(&self) -> Result<()> {
        let mut batch = WriteBatch::default();
        for cf_name in ALL_CFS {
            let cf = self.cf(cf_name)?;
            for item in self.db.iterator_cf(cf, IteratorMode::Start) {
                let (key, _) = item?;
                batch.delete_cf(cf, key);
            }
        }
        self.db.write(batch)?;
        Ok(())
    }

    pub fn all_node_ids(&self) -> Result<Vec<NodeId>> {
        let cf = self.cf(CF_NODES)?;
        let mut results = Vec::new();
        for item in self.db.iterator_cf(cf, IteratorMode::Start) {
            let (key, _) = item?;
            if key.len() != ID_LEN {
                return Err(Error::CorruptBytes {
                    cf: CF_NODES,
                    expected: ID_LEN,
                    actual: key.len(),
                });
            }
            let mut bytes = [0u8; ID_LEN];
            bytes.copy_from_slice(&key);
            results.push(NodeId::from_bytes(bytes));
        }
        Ok(results)
    }

    pub fn outgoing(&self, source: NodeId) -> Result<Vec<(EdgeId, NodeId)>> {
        self.scan_adj(CF_ADJ_OUT, source)
    }

    pub fn incoming(&self, target: NodeId) -> Result<Vec<(EdgeId, NodeId)>> {
        self.scan_adj(CF_ADJ_IN, target)
    }

    /// Snapshot the currently-registered property indexes. Cheap clone
    /// — specs are tiny (a label + a property key).
    pub fn list_property_indexes(&self) -> Vec<PropertyIndexSpec> {
        self.indexes.read().expect("indexes lock poisoned").clone()
    }

    /// Declare a new `(label, property)` single-property equality
    /// index and backfill it by scanning every node that currently
    /// carries `label`. Idempotent: re-creating an already-registered
    /// index is a no-op, matching how Neo4j's `CREATE INDEX IF NOT
    /// EXISTS` behaves.
    ///
    /// Backfill is done in the same [`WriteBatch`] as the meta insert,
    /// so a crash mid-backfill leaves the store with either zero
    /// entries (batch not yet written) or a fully-populated index
    /// (batch committed). No partial-build state is ever visible.
    pub fn create_property_index(&self, label: &str, property: &str) -> Result<()> {
        self.create_property_index_composite(label, &[property.to_string()])
    }

    /// Composite form of [`create_property_index`]. Declares a
    /// `(label, properties)` tuple index and backfills it by scanning
    /// every node currently carrying `label`. A node that's missing
    /// any of the properties, or carries an unindexable value for
    /// any of them, contributes no entry — composite indexes are
    /// all-or-nothing on the tuple.
    ///
    /// Single-property calls delegate here with a length-1 slice;
    /// the on-disk key format is byte-identical to the pre-composite
    /// layout in that case.
    pub fn create_property_index_composite(
        &self,
        label: &str,
        properties: &[String],
    ) -> Result<()> {
        assert!(
            !properties.is_empty(),
            "create_property_index_composite requires at least one property"
        );
        let spec = PropertyIndexSpec {
            label: label.to_string(),
            properties: properties.to_vec(),
        };
        let mut guard = self.indexes.write().expect("indexes lock poisoned");
        if guard.contains(&spec) {
            return Ok(());
        }

        let meta_cf = self.cf(CF_INDEX_META)?;
        let prop_cf = self.cf(CF_PROPERTY_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.put_cf(meta_cf, index_meta_key(&spec), EMPTY);

        for node_id in self.nodes_by_label(label)? {
            let node = match self.get_node(node_id)? {
                Some(n) => n,
                None => continue,
            };
            if let Some(values) = encode_index_tuple(&node.properties, &spec.properties) {
                batch.put_cf(
                    prop_cf,
                    property_index_composite_key(label, properties, &values, node_id),
                    EMPTY,
                );
            }
        }

        self.db.write(batch)?;
        guard.push(spec);
        Ok(())
    }

    /// Declare a new property constraint. Behavior summary:
    ///
    /// * The name is the user-facing identifier. When `name` is
    ///   `None`, a deterministic default (`constraint_<label>_<prop>_<kind>`)
    ///   is generated so `DROP CONSTRAINT` can still target it.
    /// * If the chosen name is already registered with the same
    ///   `(label, property, kind)`, this is a no-op (the existing
    ///   spec is returned). If the name collides on a *different*
    ///   spec, returns `ConstraintNameConflict` unless
    ///   `if_not_exists` is set, in which case the existing spec is
    ///   preserved and returned unchanged.
    /// * UNIQUE constraints implicitly require a backing property
    ///   index. `create_property_constraint` creates one on
    ///   `(label, property)` if it isn't already registered —
    ///   matching Neo4j's "a unique constraint also provides an
    ///   index" contract.
    /// * Before committing, the method scans existing nodes to
    ///   verify the constraint is satisfied. Any violation aborts
    ///   the creation with `ConstraintViolation`; the registry is
    ///   left unchanged.
    ///
    /// The meta write and the implicit-index write are batched into a
    /// single [`WriteBatch`] so the on-disk state stays consistent
    /// under crash.
    pub fn create_property_constraint(
        &self,
        name: Option<&str>,
        scope: &ConstraintScope,
        properties: &[String],
        kind: PropertyConstraintKind,
        if_not_exists: bool,
    ) -> Result<PropertyConstraintSpec> {
        // Arity validation: single-property kinds get exactly one
        // property; NodeKey accepts any positive count. Empty lists
        // are always invalid. NodeKey on relationship scope isn't
        // allowed — the "NODE" in the name is specifically about
        // node semantics; relationship equivalents would need their
        // own variant.
        if properties.is_empty() {
            return Err(Error::ConstraintArity {
                kind: kind.as_string(),
                details: "at least one property is required".into(),
            });
        }
        if !kind.allows_multi_property() && properties.len() != 1 {
            return Err(Error::ConstraintArity {
                kind: kind.as_string(),
                details: format!("expects exactly one property, got {}", properties.len()),
            });
        }
        if matches!(kind, PropertyConstraintKind::NodeKey)
            && matches!(scope, ConstraintScope::Relationship(_))
        {
            return Err(Error::ConstraintArity {
                kind: kind.as_string(),
                details: "NODE KEY cannot be applied to a relationship scope".into(),
            });
        }
        let resolved_name = match name {
            Some(n) => n.to_string(),
            None => default_constraint_name(scope, properties, kind),
        };
        let spec = PropertyConstraintSpec {
            name: resolved_name.clone(),
            scope: scope.clone(),
            properties: properties.to_vec(),
            kind,
        };

        // Idempotency / conflict check against the existing registry
        // under a read lock first — avoids taking the write lock when
        // the answer is "nothing to do".
        {
            let guard = self.constraints.read().expect("constraints lock poisoned");
            if let Some(existing) = guard.iter().find(|s| s.name == resolved_name) {
                if existing == &spec {
                    return Ok(existing.clone());
                }
                if if_not_exists {
                    return Ok(existing.clone());
                }
                return Err(Error::ConstraintNameConflict {
                    name: resolved_name,
                });
            }
        }

        // UNIQUE needs a backing single-property equality index on
        // both scopes so enforcement stays O(log N) per insert. The
        // create calls are idempotent, mirroring Neo4j's "a unique
        // constraint also provides an index" contract. The backing
        // index is not torn down on `DROP CONSTRAINT`; users who
        // want it gone issue a separate `DROP INDEX`. NODE KEY gets
        // the same auto-provisioning against a composite tuple
        // index so its uniqueness check is a single seek instead of
        // an O(M * K) label walk.
        match (kind, scope) {
            (PropertyConstraintKind::Unique, ConstraintScope::Node(label)) => {
                self.create_property_index(label, &properties[0])?;
            }
            (PropertyConstraintKind::Unique, ConstraintScope::Relationship(edge_type)) => {
                self.create_edge_property_index(edge_type, &properties[0])?;
            }
            (PropertyConstraintKind::NodeKey, ConstraintScope::Node(label)) => {
                self.create_property_index_composite(label, properties)?;
            }
            _ => {}
        }

        // Validate existing data against the new constraint before we
        // commit the meta entry. A single pre-existing violation makes
        // the whole declaration fail — matching how Neo4j rejects
        // constraint creation on data that doesn't satisfy it.
        validate_existing_data(self, &spec)?;

        let meta_cf = self.cf(CF_CONSTRAINT_META)?;
        let mut batch = WriteBatch::default();
        batch.put_cf(
            meta_cf,
            resolved_name.as_bytes(),
            constraint_meta_encode(&spec),
        );
        self.db.write(batch)?;

        let mut guard = self.constraints.write().expect("constraints lock poisoned");
        // Re-check under the write lock to avoid a TOCTOU where two
        // concurrent CREATEs race through the read-lock idempotency
        // check. The second writer sees the first's insertion and
        // returns the existing spec.
        if let Some(existing) = guard.iter().find(|s| s.name == resolved_name) {
            return Ok(existing.clone());
        }
        guard.push(spec.clone());
        Ok(spec)
    }

    /// Tear down a constraint by name. When `if_exists` is true,
    /// dropping a non-existent constraint is a no-op. Never drops the
    /// backing index for UNIQUE — users who want it gone issue a
    /// separate `DROP INDEX`.
    pub fn drop_property_constraint(&self, name: &str, if_exists: bool) -> Result<()> {
        let mut guard = self.constraints.write().expect("constraints lock poisoned");
        let idx = guard.iter().position(|s| s.name == name);
        match idx {
            None if if_exists => Ok(()),
            None => Err(Error::ConstraintNotFound {
                name: name.to_string(),
            }),
            Some(i) => {
                let meta_cf = self.cf(CF_CONSTRAINT_META)?;
                let mut batch = WriteBatch::default();
                batch.delete_cf(meta_cf, name.as_bytes());
                self.db.write(batch)?;
                guard.remove(i);
                Ok(())
            }
        }
    }

    /// Snapshot the currently-registered constraints. Cheap clone —
    /// every spec is a handful of small strings and an enum.
    pub fn list_property_constraints(&self) -> Vec<PropertyConstraintSpec> {
        self.constraints
            .read()
            .expect("constraints lock poisoned")
            .clone()
    }

    /// Enforce registered constraints against the post-write state of
    /// `node`. Invoked by the `put_node` path before the batch is
    /// constructed. `existing` is the previously-stored snapshot of
    /// the same node (if any) so the check can distinguish "this node
    /// is updating its own value" from "some other node owns this
    /// value". Relationship-scope constraints are ignored here — the
    /// edge write path has its own entry point.
    fn enforce_constraints(&self, node: &Node, existing: Option<&Node>) -> Result<()> {
        let constraints = self.constraints.read().expect("constraints lock poisoned");
        if constraints.is_empty() {
            return Ok(());
        }
        let now_has_label = |label: &str| node.labels.iter().any(|l| l == label);
        for spec in constraints.iter() {
            let label = match &spec.scope {
                ConstraintScope::Node(l) => l,
                // Relationship-scope constraints apply to edges, not
                // nodes. Skip here; `enforce_edge_constraints` runs
                // on the edge write path.
                ConstraintScope::Relationship(_) => continue,
            };
            if !now_has_label(label) {
                continue;
            }
            // Single-property kinds store the target in
            // `properties[0]`; NodeKey walks the whole list.
            let primary = spec.primary_property();
            match spec.kind {
                PropertyConstraintKind::NotNull => {
                    let present = node
                        .properties
                        .get(primary)
                        .is_some_and(|v| !matches!(v, Property::Null));
                    if !present {
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: label.clone(),
                            property: primary.to_string(),
                            details: format!(
                                "node {} is missing required property `{}`",
                                node.id, primary
                            ),
                        });
                    }
                }
                PropertyConstraintKind::Unique => {
                    let Some(value) = node.properties.get(primary) else {
                        // No value → no uniqueness collision possible.
                        // Matches Neo4j: UNIQUE alone allows NULL;
                        // combine with NOT NULL for strict presence.
                        continue;
                    };
                    if matches!(value, Property::Null) {
                        continue;
                    }
                    if encode_index_value(value).is_none() {
                        continue;
                    }
                    let holders = self.nodes_by_property(label, primary, value)?;
                    for other in holders {
                        if other == node.id {
                            continue;
                        }
                        let was_self = existing
                            .and_then(|n| n.properties.get(primary))
                            .is_some_and(|v| v == value);
                        let _ = was_self;
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: label.clone(),
                            property: primary.to_string(),
                            details: format!("value already held by node {}", other),
                        });
                    }
                }
                PropertyConstraintKind::PropertyType(target) => {
                    let Some(value) = node.properties.get(primary) else {
                        continue;
                    };
                    if matches!(value, Property::Null) {
                        continue;
                    }
                    if !property_matches_type(value, target) {
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: label.clone(),
                            property: primary.to_string(),
                            details: format!(
                                "node {} has value of type {} (expected {})",
                                node.id,
                                value.type_name(),
                                target.as_str()
                            ),
                        });
                    }
                }
                PropertyConstraintKind::NodeKey => {
                    // Presence check first: every property must be
                    // present and non-null. Fails fast before the
                    // seek so a missing-property error takes
                    // precedence over a (potentially) conflicting
                    // existing tuple.
                    let mut my_tuple: Vec<Property> = Vec::with_capacity(spec.properties.len());
                    for prop in &spec.properties {
                        match node.properties.get(prop) {
                            Some(v) if !matches!(v, Property::Null) => my_tuple.push(v.clone()),
                            _ => {
                                return Err(Error::ConstraintViolation {
                                    name: spec.name.clone(),
                                    kind: spec.kind.as_string(),
                                    label: label.clone(),
                                    property: prop.clone(),
                                    details: format!(
                                        "node {} is missing required property `{}`",
                                        node.id, prop
                                    ),
                                });
                            }
                        }
                    }
                    // Uniqueness via the auto-provisioned composite
                    // index (see `create_property_constraint`). O(log N)
                    // per insert instead of the old O(M × K) label walk.
                    let hits = self.nodes_by_properties(label, &spec.properties, &my_tuple)?;
                    if let Some(other_id) = hits.iter().find(|&&id| id != node.id) {
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: label.clone(),
                            property: spec.properties.join(","),
                            details: format!("tuple already held by node {}", other_id),
                        });
                    }
                }
            }
        }
        Ok(())
    }

    /// Enforce registered relationship-scope constraints against the
    /// post-write state of `edge`. Invoked by the `put_edge` path
    /// before the batch is constructed. Walks every constraint whose
    /// scope matches the edge's type and runs the kind-specific
    /// check. `existing` is the prior on-disk snapshot of the same
    /// edge (if any) so the uniqueness check can allow self-updates.
    fn enforce_edge_constraints(&self, edge: &Edge, existing: Option<&Edge>) -> Result<()> {
        let constraints = self.constraints.read().expect("constraints lock poisoned");
        if constraints.is_empty() {
            return Ok(());
        }
        for spec in constraints.iter() {
            let edge_type = match &spec.scope {
                ConstraintScope::Relationship(t) => t,
                // Node-scope constraints don't concern edges.
                ConstraintScope::Node(_) => continue,
            };
            if edge_type != &edge.edge_type {
                continue;
            }
            let primary = spec.primary_property();
            match spec.kind {
                PropertyConstraintKind::NotNull => {
                    let present = edge
                        .properties
                        .get(primary)
                        .is_some_and(|v| !matches!(v, Property::Null));
                    if !present {
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: edge_type.clone(),
                            property: primary.to_string(),
                            details: format!(
                                "edge {} is missing required property `{}`",
                                edge.id, primary
                            ),
                        });
                    }
                }
                PropertyConstraintKind::Unique => {
                    let Some(value) = edge.properties.get(primary) else {
                        // No value → no uniqueness collision possible.
                        // Matches the node path: UNIQUE alone allows
                        // NULL / missing; combine with NOT NULL for
                        // strict presence.
                        continue;
                    };
                    if matches!(value, Property::Null) {
                        continue;
                    }
                    if encode_index_value(value).is_none() {
                        // Value type doesn't support equality in the
                        // index (Float, List, Map, etc.). Skip — the
                        // node path makes the same call for
                        // consistency, and the index can't help us
                        // here anyway.
                        continue;
                    }
                    // Probe the backing edge-property index (created
                    // by `create_property_constraint` above) for
                    // rival holders. O(log N) + O(matching edges)
                    // vs. the previous O(E_type) per-insert scan.
                    let holders = self.edges_by_property(edge_type, primary, value)?;
                    for other_id in holders {
                        if other_id == edge.id {
                            continue;
                        }
                        let was_self = existing
                            .and_then(|e| e.properties.get(primary))
                            .is_some_and(|v| v == value);
                        let _ = was_self;
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: edge_type.clone(),
                            property: primary.to_string(),
                            details: format!("value already held by edge {}", other_id),
                        });
                    }
                }
                PropertyConstraintKind::PropertyType(target) => {
                    let Some(value) = edge.properties.get(primary) else {
                        continue;
                    };
                    if matches!(value, Property::Null) {
                        continue;
                    }
                    if !property_matches_type(value, target) {
                        return Err(Error::ConstraintViolation {
                            name: spec.name.clone(),
                            kind: spec.kind.as_string(),
                            label: edge_type.clone(),
                            property: primary.to_string(),
                            details: format!(
                                "edge {} has value of type {} (expected {})",
                                edge.id,
                                value.type_name(),
                                target.as_str()
                            ),
                        });
                    }
                }
                PropertyConstraintKind::NodeKey => {
                    // Disallowed at create time — see
                    // `create_property_constraint`.
                    unreachable!(
                        "NODE KEY on relationship scope should have been rejected at create time"
                    );
                }
            }
        }
        Ok(())
    }

    /// Tear down a property index: removes the meta entry and every
    /// entry under the `(label, prop)` prefix. Idempotent: dropping a
    /// non-existent index is a no-op. Atomic via one [`WriteBatch`].
    pub fn drop_property_index(&self, label: &str, property: &str) -> Result<()> {
        self.drop_property_index_composite(label, &[property.to_string()])
    }

    pub fn drop_property_index_composite(&self, label: &str, properties: &[String]) -> Result<()> {
        assert!(
            !properties.is_empty(),
            "drop_property_index_composite requires at least one property"
        );
        let spec = PropertyIndexSpec {
            label: label.to_string(),
            properties: properties.to_vec(),
        };
        let mut guard = self.indexes.write().expect("indexes lock poisoned");
        if !guard.contains(&spec) {
            return Ok(());
        }

        // Reject the drop if a UNIQUE or NODE KEY constraint on the
        // same `(label, properties)` is registered — enforcement for
        // those kinds runs a seek through this exact index, so
        // silently removing it would collapse the uniqueness check
        // to "always passes" without producing any user-visible
        // signal. `DROP CONSTRAINT` is the right prerequisite.
        if let Some(constraint) = find_constraint_backing_node_index(
            &self.constraints.read().expect("constraints lock poisoned"),
            label,
            properties,
        ) {
            return Err(Error::IndexInUse { constraint });
        }

        let meta_cf = self.cf(CF_INDEX_META)?;
        let prop_cf = self.cf(CF_PROPERTY_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.delete_cf(meta_cf, index_meta_key(&spec));

        // Interleaved key layout means no clean `[label][props...]`
        // byte-prefix scopes a composite index's entries on its own —
        // an index `(a, b)` would share a `[label][a]` prefix with
        // single-property index `(a)`. Iterate by the label-only
        // prefix and parse each entry's property sequence, deleting
        // those that exactly match this spec's list.
        let label_prefix = property_index_label_prefix(label);
        let iter = self.db.iterator_cf(
            prop_cf,
            IteratorMode::From(&label_prefix, Direction::Forward),
        );
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&label_prefix) {
                break;
            }
            let Some(parsed) = parse_property_index_entry_props(&key) else {
                continue;
            };
            if parsed.len() == properties.len()
                && parsed.iter().zip(properties.iter()).all(|(a, b)| a == b)
            {
                batch.delete_cf(prop_cf, key);
            }
        }

        self.db.write(batch)?;
        guard.retain(|s| s != &spec);
        Ok(())
    }

    /// Snapshot the currently-registered edge property indexes.
    /// Mirror of [`RocksDbStorageEngine::list_property_indexes`] for
    /// relationship scope. Cheap clone — specs are tiny.
    pub fn list_edge_property_indexes(&self) -> Vec<EdgePropertyIndexSpec> {
        self.edge_indexes
            .read()
            .expect("edge_indexes lock poisoned")
            .clone()
    }

    /// Declare a new `(edge_type, property)` edge property index and
    /// backfill it by scanning every edge currently carrying
    /// `edge_type`. Idempotent: re-creating an already-registered
    /// index is a no-op. Mirror of
    /// [`RocksDbStorageEngine::create_property_index`] for
    /// relationship scope; the same "same WriteBatch" atomicity
    /// guarantee applies — a crash mid-backfill leaves the store with
    /// either zero entries or a fully-populated index, never a
    /// partially-built one.
    pub fn create_edge_property_index(&self, edge_type: &str, property: &str) -> Result<()> {
        self.create_edge_property_index_composite(edge_type, &[property.to_string()])
    }

    pub fn create_edge_property_index_composite(
        &self,
        edge_type: &str,
        properties: &[String],
    ) -> Result<()> {
        assert!(
            !properties.is_empty(),
            "create_edge_property_index_composite requires at least one property"
        );
        let spec = EdgePropertyIndexSpec {
            edge_type: edge_type.to_string(),
            properties: properties.to_vec(),
        };
        let mut guard = self
            .edge_indexes
            .write()
            .expect("edge_indexes lock poisoned");
        if guard.contains(&spec) {
            return Ok(());
        }

        let meta_cf = self.cf(CF_EDGE_INDEX_META)?;
        let prop_cf = self.cf(CF_EDGE_PROPERTY_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.put_cf(meta_cf, edge_index_meta_key(&spec), EMPTY);

        for edge_id in self.edges_by_type(edge_type)? {
            let edge = match self.get_edge(edge_id)? {
                Some(e) => e,
                None => continue,
            };
            if let Some(values) = encode_index_tuple(&edge.properties, &spec.properties) {
                batch.put_cf(
                    prop_cf,
                    edge_property_index_composite_key(edge_type, properties, &values, edge_id),
                    EMPTY,
                );
            }
        }

        self.db.write(batch)?;
        guard.push(spec);
        Ok(())
    }

    pub fn drop_edge_property_index(&self, edge_type: &str, property: &str) -> Result<()> {
        self.drop_edge_property_index_composite(edge_type, &[property.to_string()])
    }

    pub fn drop_edge_property_index_composite(
        &self,
        edge_type: &str,
        properties: &[String],
    ) -> Result<()> {
        assert!(
            !properties.is_empty(),
            "drop_edge_property_index_composite requires at least one property"
        );
        let spec = EdgePropertyIndexSpec {
            edge_type: edge_type.to_string(),
            properties: properties.to_vec(),
        };
        let mut guard = self
            .edge_indexes
            .write()
            .expect("edge_indexes lock poisoned");
        if !guard.contains(&spec) {
            return Ok(());
        }

        // Same rationale as the node-side drop guard: a UNIQUE
        // constraint on this relationship type + property seeks
        // through this exact index during enforcement, so silently
        // removing it would defeat the check. Require
        // `DROP CONSTRAINT` first.
        if let Some(constraint) = find_constraint_backing_edge_index(
            &self.constraints.read().expect("constraints lock poisoned"),
            edge_type,
            properties,
        ) {
            return Err(Error::IndexInUse { constraint });
        }

        let meta_cf = self.cf(CF_EDGE_INDEX_META)?;
        let prop_cf = self.cf(CF_EDGE_PROPERTY_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.delete_cf(meta_cf, edge_index_meta_key(&spec));

        // See the node-side drop for why DROP parses entries rather
        // than scoping with a property-name byte prefix.
        let label_prefix = property_index_label_prefix(edge_type);
        let iter = self.db.iterator_cf(
            prop_cf,
            IteratorMode::From(&label_prefix, Direction::Forward),
        );
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&label_prefix) {
                break;
            }
            let Some(parsed) = parse_property_index_entry_props(&key) else {
                continue;
            };
            if parsed.len() == properties.len()
                && parsed.iter().zip(properties.iter()).all(|(a, b)| a == b)
            {
                batch.delete_cf(prop_cf, key);
            }
        }

        self.db.write(batch)?;
        guard.retain(|s| s != &spec);
        Ok(())
    }

    // ---------------------------------------------------------------
    // Point / spatial index (node scope).
    //
    // Z-order (Morton) cell encoding over a fixed per-SRID domain.
    // Each indexed `Property::Point` produces one row keyed by
    // `<label>\0<prop>\0<srid:4><cell:8><node_id:16>` with the point's
    // coordinates stored in the value. Cross-SRID queries are
    // impossible by construction — the SRID is in the key prefix, so
    // a bbox scan is naturally scoped to one CRS.
    //
    // Single-property only for now. Extending to composite spatial
    // or to relationship scope is additive — separate CFs and
    // separate spec shapes.
    // ---------------------------------------------------------------

    pub fn list_point_indexes(&self) -> Vec<PointIndexSpec> {
        self.point_indexes
            .read()
            .expect("point_indexes lock poisoned")
            .clone()
    }

    /// Declare a new point index on `(label, property)` and backfill
    /// it by scanning every node that currently carries the label.
    /// Idempotent: re-creating a registered index is a no-op. Same
    /// "single WriteBatch" atomicity guarantee as the property-index
    /// create path — a crash mid-backfill leaves the store with
    /// either zero entries or a fully-populated index.
    pub fn create_point_index(&self, label: &str, property: &str) -> Result<()> {
        let spec = PointIndexSpec {
            label: label.to_string(),
            property: property.to_string(),
        };
        let mut guard = self
            .point_indexes
            .write()
            .expect("point_indexes lock poisoned");
        if guard.contains(&spec) {
            return Ok(());
        }

        let meta_cf = self.cf(CF_POINT_INDEX_META)?;
        let point_cf = self.cf(CF_POINT_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.put_cf(meta_cf, point_index_meta_key(&spec), EMPTY);

        for node_id in self.nodes_by_label(label)? {
            let node = match self.get_node(node_id)? {
                Some(n) => n,
                None => continue,
            };
            if let Some(Property::Point(p)) = node.properties.get(property) {
                let cell = point_cell(p.srid, p.x, p.y);
                batch.put_cf(
                    point_cf,
                    point_index_key(label, property, p.srid, cell, node_id.as_bytes()),
                    point_index_value(p.x, p.y, p.z),
                );
            }
        }

        self.db.write(batch)?;
        guard.push(spec);
        Ok(())
    }

    /// Tear down a point index. Removes the meta entry and every
    /// entry under the `<label>\0<prop>\0` prefix — that sweep
    /// covers all SRID variants at once, since SRID is to the right
    /// of the label+property header. Idempotent.
    pub fn drop_point_index(&self, label: &str, property: &str) -> Result<()> {
        let spec = PointIndexSpec {
            label: label.to_string(),
            property: property.to_string(),
        };
        let mut guard = self
            .point_indexes
            .write()
            .expect("point_indexes lock poisoned");
        if !guard.contains(&spec) {
            return Ok(());
        }

        let meta_cf = self.cf(CF_POINT_INDEX_META)?;
        let point_cf = self.cf(CF_POINT_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.delete_cf(meta_cf, point_index_meta_key(&spec));

        let prefix = point_index_label_prop_prefix(label, property);
        let iter = self
            .db
            .iterator_cf(point_cf, IteratorMode::From(&prefix, Direction::Forward));
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            batch.delete_cf(point_cf, key);
        }

        self.db.write(batch)?;
        guard.retain(|s| s != &spec);
        Ok(())
    }

    /// Range query: node ids whose indexed point falls inside the
    /// axis-aligned bounding box `[(xlo, ylo), (xhi, yhi)]` under
    /// `srid`. The scan walks the Morton-code cell range that
    /// covers the bbox and applies a precise per-row filter against
    /// the coordinates stored in the value — the cell range is a
    /// superset, so the filter is what guarantees correctness.
    ///
    /// A missing index returns empty rather than erroring, matching
    /// the property-seek convention (lets the planner race a DROP
    /// without a fatal). Results are sorted by `NodeId` for
    /// determinism across runs.
    pub fn nodes_in_bbox(
        &self,
        label: &str,
        property: &str,
        srid: i32,
        xlo: f64,
        ylo: f64,
        xhi: f64,
        yhi: f64,
    ) -> Result<Vec<NodeId>> {
        let spec = PointIndexSpec {
            label: label.to_string(),
            property: property.to_string(),
        };
        {
            let guard = self
                .point_indexes
                .read()
                .expect("point_indexes lock poisoned");
            if !guard.contains(&spec) {
                return Ok(Vec::new());
            }
        }

        let (lo_x, hi_x) = if xlo <= xhi { (xlo, xhi) } else { (xhi, xlo) };
        let (lo_y, hi_y) = if ylo <= yhi { (ylo, yhi) } else { (yhi, ylo) };
        let (min_cell, max_cell) = point_cell_range(srid, lo_x, lo_y, hi_x, hi_y);

        let prefix = point_index_srid_prefix(label, property, srid);
        let header_len = prefix.len();
        let mut seek = prefix.clone();
        seek.extend_from_slice(&min_cell.to_be_bytes());

        let cf = self.cf(CF_POINT_INDEX)?;
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(&seek, Direction::Forward));
        let mut results = Vec::new();
        for item in iter {
            let (key, value) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            let cell = cell_from_point_index_key(CF_POINT_INDEX, &key, header_len)?;
            if cell > max_cell {
                break;
            }
            let (x, y, _z) = decode_point_index_value(CF_POINT_INDEX, &value)?;
            if x < lo_x || x > hi_x || y < lo_y || y > hi_y {
                continue;
            }
            let id_bytes = node_id_from_point_index_key(CF_POINT_INDEX, &key)?;
            results.push(NodeId::from_bytes(id_bytes));
        }
        results.sort();
        Ok(results)
    }

    // ---------------------------------------------------------------
    // Point / spatial index (relationship scope).
    //
    // Mirror of the node-scope block above. Lives in its own CF so
    // node and edge spatial entries can't alias and the two can be
    // dropped independently — matches how non-spatial property
    // indexes are split between `CF_PROPERTY_INDEX` and
    // `CF_EDGE_PROPERTY_INDEX`.
    // ---------------------------------------------------------------

    pub fn list_edge_point_indexes(&self) -> Vec<EdgePointIndexSpec> {
        self.edge_point_indexes
            .read()
            .expect("edge_point_indexes lock poisoned")
            .clone()
    }

    /// Declare a new edge point index and backfill it by scanning
    /// every edge currently carrying `edge_type`. Idempotent.
    /// Single-property / relationship-scope analogue of
    /// [`RocksDbStorageEngine::create_point_index`].
    pub fn create_edge_point_index(&self, edge_type: &str, property: &str) -> Result<()> {
        let spec = EdgePointIndexSpec {
            edge_type: edge_type.to_string(),
            property: property.to_string(),
        };
        let mut guard = self
            .edge_point_indexes
            .write()
            .expect("edge_point_indexes lock poisoned");
        if guard.contains(&spec) {
            return Ok(());
        }

        let meta_cf = self.cf(CF_EDGE_POINT_INDEX_META)?;
        let point_cf = self.cf(CF_EDGE_POINT_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.put_cf(meta_cf, edge_point_index_meta_key(&spec), EMPTY);

        for edge_id in self.edges_by_type(edge_type)? {
            let edge = match self.get_edge(edge_id)? {
                Some(e) => e,
                None => continue,
            };
            if let Some(Property::Point(p)) = edge.properties.get(property) {
                let cell = point_cell(p.srid, p.x, p.y);
                batch.put_cf(
                    point_cf,
                    // Reuse the node-scope key builder: the key layout
                    // `<label>\0<prop>\0<srid:4><cell:8><id:16>` doesn't
                    // care whether `id` is a node or edge id — both are
                    // 16-byte UUIDs. The separate CF is what scopes
                    // relationship entries away from node entries.
                    point_index_key(edge_type, property, p.srid, cell, edge_id.as_bytes()),
                    point_index_value(p.x, p.y, p.z),
                );
            }
        }

        self.db.write(batch)?;
        guard.push(spec);
        Ok(())
    }

    /// Tear down an edge point index. Idempotent.
    pub fn drop_edge_point_index(&self, edge_type: &str, property: &str) -> Result<()> {
        let spec = EdgePointIndexSpec {
            edge_type: edge_type.to_string(),
            property: property.to_string(),
        };
        let mut guard = self
            .edge_point_indexes
            .write()
            .expect("edge_point_indexes lock poisoned");
        if !guard.contains(&spec) {
            return Ok(());
        }

        let meta_cf = self.cf(CF_EDGE_POINT_INDEX_META)?;
        let point_cf = self.cf(CF_EDGE_POINT_INDEX)?;
        let mut batch = WriteBatch::default();
        batch.delete_cf(meta_cf, edge_point_index_meta_key(&spec));

        let prefix = point_index_label_prop_prefix(edge_type, property);
        let iter = self
            .db
            .iterator_cf(point_cf, IteratorMode::From(&prefix, Direction::Forward));
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            batch.delete_cf(point_cf, key);
        }

        self.db.write(batch)?;
        guard.retain(|s| s != &spec);
        Ok(())
    }

    /// Relationship-scope analogue of
    /// [`RocksDbStorageEngine::nodes_in_bbox`]. Same Z-order cell
    /// range + precise bbox filter via stored coords, just over
    /// `CF_EDGE_POINT_INDEX`.
    pub fn edges_in_bbox(
        &self,
        edge_type: &str,
        property: &str,
        srid: i32,
        xlo: f64,
        ylo: f64,
        xhi: f64,
        yhi: f64,
    ) -> Result<Vec<EdgeId>> {
        let spec = EdgePointIndexSpec {
            edge_type: edge_type.to_string(),
            property: property.to_string(),
        };
        {
            let guard = self
                .edge_point_indexes
                .read()
                .expect("edge_point_indexes lock poisoned");
            if !guard.contains(&spec) {
                return Ok(Vec::new());
            }
        }

        let (lo_x, hi_x) = if xlo <= xhi { (xlo, xhi) } else { (xhi, xlo) };
        let (lo_y, hi_y) = if ylo <= yhi { (ylo, yhi) } else { (yhi, ylo) };
        let (min_cell, max_cell) = point_cell_range(srid, lo_x, lo_y, hi_x, hi_y);

        let prefix = point_index_srid_prefix(edge_type, property, srid);
        let header_len = prefix.len();
        let mut seek = prefix.clone();
        seek.extend_from_slice(&min_cell.to_be_bytes());

        let cf = self.cf(CF_EDGE_POINT_INDEX)?;
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(&seek, Direction::Forward));
        let mut results = Vec::new();
        for item in iter {
            let (key, value) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            let cell = cell_from_point_index_key(CF_EDGE_POINT_INDEX, &key, header_len)?;
            if cell > max_cell {
                break;
            }
            let (x, y, _z) = decode_point_index_value(CF_EDGE_POINT_INDEX, &value)?;
            if x < lo_x || x > hi_x || y < lo_y || y > hi_y {
                continue;
            }
            let id_bytes = node_id_from_point_index_key(CF_EDGE_POINT_INDEX, &key)?;
            results.push(EdgeId::from_bytes(id_bytes));
        }
        results.sort();
        Ok(results)
    }

    /// Look up edge ids for a `(edge_type, property, value)` equality
    /// via the edge-property-index CF. Mirror of
    /// [`RocksDbStorageEngine::nodes_by_property`] for relationship
    /// scope; unindexable value types surface as
    /// [`Error::UnindexableValue`] so callers can fall back to a
    /// type-wide scan rather than silently returning empty.
    pub fn edges_by_property(
        &self,
        edge_type: &str,
        property: &str,
        value: &Property,
    ) -> Result<Vec<EdgeId>> {
        self.edges_by_properties(
            edge_type,
            std::slice::from_ref(&property.to_string()),
            std::slice::from_ref(value),
        )
    }

    /// Composite form of [`edges_by_property`]. Same contract as
    /// [`RocksDbStorageEngine::nodes_by_properties`] on the
    /// relationship side.
    pub fn edges_by_properties(
        &self,
        edge_type: &str,
        properties: &[String],
        values: &[Property],
    ) -> Result<Vec<EdgeId>> {
        assert_eq!(
            properties.len(),
            values.len(),
            "composite edge seek: properties and values must have equal length"
        );
        let mut encoded: Vec<Vec<u8>> = Vec::with_capacity(values.len());
        for (p, v) in properties.iter().zip(values.iter()) {
            let bytes = encode_index_value(v).ok_or_else(|| Error::UnindexableValue {
                property: p.clone(),
                kind: v.type_name(),
            })?;
            encoded.push(bytes);
        }
        let cf = self.cf(CF_EDGE_PROPERTY_INDEX)?;
        let prefix = edge_property_index_composite_value_prefix(edge_type, properties, &encoded);
        let mut results = Vec::new();
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(&prefix, Direction::Forward));
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            let bytes = edge_id_from_property_index_key(&key, prefix.len())?;
            results.push(EdgeId::from_bytes(bytes));
        }
        Ok(results)
    }

    /// Look up node ids for a `(label, property, value)` equality via
    /// the property index CF. The caller is responsible for checking
    /// that the index exists first (e.g. the planner only emits
    /// `IndexSeek` when it has verified via
    /// [`RocksDbStorageEngine::list_property_indexes`]).
    ///
    /// Unindexable value types (Float64, List, Map, Null) return
    /// [`Error::UnindexableValue`] — callers should surface this to
    /// the user rather than silently returning an empty result.
    pub fn nodes_by_property(
        &self,
        label: &str,
        property: &str,
        value: &Property,
    ) -> Result<Vec<NodeId>> {
        self.nodes_by_properties(
            label,
            std::slice::from_ref(&property.to_string()),
            std::slice::from_ref(value),
        )
    }

    /// Composite form of [`nodes_by_property`]. Seeks every node
    /// whose `(label, property_i = value_i)` tuple matches in order.
    /// The two slices must have equal length. Unindexable value
    /// types surface as [`Error::UnindexableValue`] the same way
    /// the single-property form does — composite indexes are
    /// all-or-nothing and an unindexable slot can never match a
    /// stored tuple.
    pub fn nodes_by_properties(
        &self,
        label: &str,
        properties: &[String],
        values: &[Property],
    ) -> Result<Vec<NodeId>> {
        assert_eq!(
            properties.len(),
            values.len(),
            "composite seek: properties and values must have equal length"
        );
        let mut encoded: Vec<Vec<u8>> = Vec::with_capacity(values.len());
        for (p, v) in properties.iter().zip(values.iter()) {
            let bytes = encode_index_value(v).ok_or_else(|| Error::UnindexableValue {
                property: p.clone(),
                kind: v.type_name(),
            })?;
            encoded.push(bytes);
        }
        let cf = self.cf(CF_PROPERTY_INDEX)?;
        let prefix = property_index_composite_value_prefix(label, properties, &encoded);
        let mut results = Vec::new();
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(&prefix, Direction::Forward));
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            let bytes = node_id_from_property_index_key(&key, prefix.len())?;
            results.push(NodeId::from_bytes(bytes));
        }
        Ok(results)
    }

    pub fn nodes_by_label(&self, label: &str) -> Result<Vec<NodeId>> {
        let cf = self.cf(CF_LABEL_INDEX)?;
        let prefix = label_index_prefix(label);
        let mut results = Vec::new();
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(&prefix, Direction::Forward));
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            let bytes = id_from_str_index_key(CF_LABEL_INDEX, &key, label.len())?;
            results.push(NodeId::from_bytes(bytes));
        }
        Ok(results)
    }

    pub fn edges_by_type(&self, edge_type: &str) -> Result<Vec<EdgeId>> {
        let cf = self.cf(CF_TYPE_INDEX)?;
        let prefix = type_index_prefix(edge_type);
        let mut results = Vec::new();
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(&prefix, Direction::Forward));
        for item in iter {
            let (key, _) = item?;
            if !key.starts_with(&prefix) {
                break;
            }
            let bytes = id_from_str_index_key(CF_TYPE_INDEX, &key, edge_type.len())?;
            results.push(EdgeId::from_bytes(bytes));
        }
        Ok(results)
    }

    fn scan_adj(&self, cf_name: &'static str, node: NodeId) -> Result<Vec<(EdgeId, NodeId)>> {
        let cf = self.cf(cf_name)?;
        let prefix: &[u8] = node.as_bytes();
        let mut results = Vec::new();
        let iter = self
            .db
            .iterator_cf(cf, IteratorMode::From(prefix, Direction::Forward));
        for item in iter {
            let (key, value) = item?;
            if !key.starts_with(prefix) {
                break;
            }
            let edge_id = edge_from_adj_key(cf_name, &key)?;
            let other = node_from_adj_value(cf_name, &value)?;
            results.push((edge_id, other));
        }
        Ok(results)
    }
}

/// Return the [`meshdb_core::Point`] at `properties[key]` when the
/// property is present and of point type. Used by point-index
/// maintenance to decide whether a node's indexed property changed
/// across a put. Non-point or missing values yield `None`, which the
/// index maintenance treats as "no entry" — the same way
/// `encode_index_tuple` treats missing / unindexable values for
/// property indexes.
fn extract_indexable_point(
    properties: &std::collections::HashMap<String, Property>,
    key: &str,
) -> Option<meshdb_core::Point> {
    match properties.get(key)? {
        Property::Point(p) => Some(*p),
        _ => None,
    }
}

/// Deterministic auto-name for a constraint the user didn't name.
/// Shape: `constraint_<label>_<property_list>_<kind>` where the
/// property list joins the property names with `_` and `<kind>` is
/// `unique`, `not_null`, `type_<t>`, or `node_key`. Stable across
/// restarts — users can target the auto-name with `DROP CONSTRAINT`
/// without having to inspect `SHOW CONSTRAINTS` first.
fn default_constraint_name(
    scope: &ConstraintScope,
    properties: &[String],
    kind: PropertyConstraintKind,
) -> String {
    let joined = properties.join("_");
    format!(
        "constraint_{scope_tag}_{target}_{joined}_{kind_tag}",
        scope_tag = scope.name_tag(),
        target = scope.target(),
        kind_tag = kind.name_tag(),
    )
}

/// Return the name of a UNIQUE or NODE KEY constraint whose backing
/// index is exactly `(label, properties)`, or `None` if no such
/// constraint is registered. The enforcement paths for both kinds seek
/// through that index — dropping it silently defeats the check — so
/// `drop_property_index_composite` consults this helper before
/// removing any entries.
fn find_constraint_backing_node_index(
    constraints: &[PropertyConstraintSpec],
    label: &str,
    properties: &[String],
) -> Option<String> {
    constraints
        .iter()
        .filter(|c| matches!(&c.scope, ConstraintScope::Node(l) if l == label))
        .filter(|c| {
            matches!(
                c.kind,
                PropertyConstraintKind::Unique | PropertyConstraintKind::NodeKey
            )
        })
        .find(|c| c.properties.as_slice() == properties)
        .map(|c| c.name.clone())
}

/// Relationship-scope mirror of
/// [`find_constraint_backing_node_index`]. NODE KEY is node-only, so
/// only UNIQUE can back an edge index.
fn find_constraint_backing_edge_index(
    constraints: &[PropertyConstraintSpec],
    edge_type: &str,
    properties: &[String],
) -> Option<String> {
    constraints
        .iter()
        .filter(|c| matches!(&c.scope, ConstraintScope::Relationship(t) if t == edge_type))
        .filter(|c| matches!(c.kind, PropertyConstraintKind::Unique))
        .find(|c| c.properties.as_slice() == properties)
        .map(|c| c.name.clone())
}

/// Scan existing nodes and verify that `spec` holds. Called on
/// constraint creation so a user declaring a constraint against
/// already-invalid data gets a clear error instead of a partial
/// rollout. Walks only the nodes carrying the constrained label — for
/// label-sparse graphs this avoids the full-node scan.
fn validate_existing_data(
    engine: &RocksDbStorageEngine,
    spec: &PropertyConstraintSpec,
) -> Result<()> {
    match &spec.scope {
        ConstraintScope::Node(label) => validate_existing_nodes(engine, spec, label),
        ConstraintScope::Relationship(edge_type) => {
            validate_existing_edges(engine, spec, edge_type)
        }
    }
}

fn validate_existing_nodes(
    engine: &RocksDbStorageEngine,
    spec: &PropertyConstraintSpec,
    label: &str,
) -> Result<()> {
    let label_members = engine.nodes_by_label(label)?;
    let primary = spec.primary_property();
    match spec.kind {
        PropertyConstraintKind::NotNull => {
            for id in label_members {
                let node = match engine.get_node(id)? {
                    Some(n) => n,
                    None => continue,
                };
                let present = node
                    .properties
                    .get(primary)
                    .is_some_and(|v| !matches!(v, Property::Null));
                if !present {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: label.to_string(),
                        property: primary.to_string(),
                        details: format!("node {id} is missing required property"),
                    });
                }
            }
        }
        PropertyConstraintKind::Unique => {
            use std::collections::HashMap;
            let mut seen: HashMap<Vec<u8>, meshdb_core::NodeId> = HashMap::new();
            for id in label_members {
                let node = match engine.get_node(id)? {
                    Some(n) => n,
                    None => continue,
                };
                let Some(value) = node.properties.get(primary) else {
                    continue;
                };
                let Some(encoded) = encode_index_value(value) else {
                    continue;
                };
                if let Some(&first) = seen.get(&encoded) {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: label.to_string(),
                        property: primary.to_string(),
                        details: format!("duplicate value held by nodes {first} and {id}"),
                    });
                }
                seen.insert(encoded, id);
            }
        }
        PropertyConstraintKind::PropertyType(target) => {
            for id in label_members {
                let node = match engine.get_node(id)? {
                    Some(n) => n,
                    None => continue,
                };
                let Some(value) = node.properties.get(primary) else {
                    continue;
                };
                if matches!(value, Property::Null) {
                    continue;
                }
                if !property_matches_type(value, target) {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: label.to_string(),
                        property: primary.to_string(),
                        details: format!(
                            "node {id} has value of type {} (expected {})",
                            value.type_name(),
                            target.as_str()
                        ),
                    });
                }
            }
        }
        PropertyConstraintKind::NodeKey => {
            use std::collections::HashMap;
            let mut seen: HashMap<Vec<Vec<u8>>, meshdb_core::NodeId> = HashMap::new();
            for id in label_members {
                let node = match engine.get_node(id)? {
                    Some(n) => n,
                    None => continue,
                };
                let mut tuple: Vec<Vec<u8>> = Vec::with_capacity(spec.properties.len());
                let mut missing: Option<&str> = None;
                for prop in &spec.properties {
                    match node.properties.get(prop) {
                        Some(v) if !matches!(v, Property::Null) => {
                            if let Some(encoded) = encode_index_value(v) {
                                tuple.push(encoded);
                            } else {
                                missing = Some(prop);
                                break;
                            }
                        }
                        _ => {
                            missing = Some(prop.as_str());
                            break;
                        }
                    }
                }
                if let Some(prop) = missing {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: label.to_string(),
                        property: prop.to_string(),
                        details: format!("node {id} is missing required property `{prop}`"),
                    });
                }
                if let Some(&first) = seen.get(&tuple) {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: label.to_string(),
                        property: spec.properties.join(","),
                        details: format!("duplicate tuple held by nodes {first} and {id}"),
                    });
                }
                seen.insert(tuple, id);
            }
        }
    }
    Ok(())
}

/// Relationship-scope analogue to `validate_existing_nodes`. Walks
/// `edges_by_type(edge_type)` because we don't have an edge property
/// index; complexity is O(E_type) per newly-declared constraint. `NodeKey` is rejected at create time
/// for relationship scope, so this path doesn't handle it.
fn validate_existing_edges(
    engine: &RocksDbStorageEngine,
    spec: &PropertyConstraintSpec,
    edge_type: &str,
) -> Result<()> {
    let edge_ids = engine.edges_by_type(edge_type)?;
    let primary = spec.primary_property();
    match spec.kind {
        PropertyConstraintKind::NotNull => {
            for id in edge_ids {
                let edge = match engine.get_edge(id)? {
                    Some(e) => e,
                    None => continue,
                };
                let present = edge
                    .properties
                    .get(primary)
                    .is_some_and(|v| !matches!(v, Property::Null));
                if !present {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: edge_type.to_string(),
                        property: primary.to_string(),
                        details: format!("edge {id} is missing required property"),
                    });
                }
            }
        }
        PropertyConstraintKind::Unique => {
            use std::collections::HashMap;
            let mut seen: HashMap<Vec<u8>, meshdb_core::EdgeId> = HashMap::new();
            for id in edge_ids {
                let edge = match engine.get_edge(id)? {
                    Some(e) => e,
                    None => continue,
                };
                let Some(value) = edge.properties.get(primary) else {
                    continue;
                };
                let Some(encoded) = encode_index_value(value) else {
                    continue;
                };
                if let Some(&first) = seen.get(&encoded) {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: edge_type.to_string(),
                        property: primary.to_string(),
                        details: format!("duplicate value held by edges {first} and {id}"),
                    });
                }
                seen.insert(encoded, id);
            }
        }
        PropertyConstraintKind::PropertyType(target) => {
            for id in edge_ids {
                let edge = match engine.get_edge(id)? {
                    Some(e) => e,
                    None => continue,
                };
                let Some(value) = edge.properties.get(primary) else {
                    continue;
                };
                if matches!(value, Property::Null) {
                    continue;
                }
                if !property_matches_type(value, target) {
                    return Err(Error::ConstraintViolation {
                        name: spec.name.clone(),
                        kind: spec.kind.as_string(),
                        label: edge_type.to_string(),
                        property: primary.to_string(),
                        details: format!(
                            "edge {id} has value of type {} (expected {})",
                            value.type_name(),
                            target.as_str()
                        ),
                    });
                }
            }
        }
        PropertyConstraintKind::NodeKey => {
            unreachable!("NODE KEY on relationship scope rejected at create time")
        }
    }
    Ok(())
}

/// Strict `Property` / `PropertyType` match. No numeric coercion — an
/// `Int64` does NOT satisfy `FLOAT`, matching Neo4j's `IS :: FLOAT`
/// semantics. Returns `false` for `Null`; callers should pre-filter
/// null values (`IS :: T` allows nulls by convention — pair with
/// `IS NOT NULL` for strict presence).
fn property_matches_type(value: &Property, target: PropertyType) -> bool {
    matches!(
        (target, value),
        (PropertyType::String, Property::String(_))
            | (PropertyType::Integer, Property::Int64(_))
            | (PropertyType::Float, Property::Float64(_))
            | (PropertyType::Boolean, Property::Bool(_))
    )
}

/// Rehydrate the constraint registry from [`CF_CONSTRAINT_META`] at
/// [`RocksDbStorageEngine::open`] time. Walks the CF sequentially —
/// constraint counts are tiny (single digits in practice) so this
/// stays cheap regardless of graph size.
fn load_constraint_meta(db: &DB) -> Result<Vec<PropertyConstraintSpec>> {
    let cf = db
        .cf_handle(CF_CONSTRAINT_META)
        .ok_or(Error::MissingColumnFamily(CF_CONSTRAINT_META))?;
    let mut specs = Vec::new();
    for item in db.iterator_cf(cf, IteratorMode::Start) {
        let (key, value) = item?;
        let name = std::str::from_utf8(&key)
            .map_err(|_| Error::CorruptBytes {
                cf: CF_CONSTRAINT_META,
                expected: key.len(),
                actual: key.len(),
            })?
            .to_string();
        specs.push(constraint_meta_decode(CF_CONSTRAINT_META, name, &value)?);
    }
    Ok(specs)
}

/// Rehydrate the property-index registry from [`CF_INDEX_META`] at
/// [`RocksDbStorageEngine::open`] time. Runs once per process, so
/// walking the CF sequentially is fine even for large index counts.
fn load_index_meta(db: &DB) -> Result<Vec<PropertyIndexSpec>> {
    let cf = db
        .cf_handle(CF_INDEX_META)
        .ok_or(Error::MissingColumnFamily(CF_INDEX_META))?;
    let mut specs = Vec::new();
    for item in db.iterator_cf(cf, IteratorMode::Start) {
        let (key, _) = item?;
        specs.push(index_meta_key_decode(&key)?);
    }
    Ok(specs)
}

/// Relationship-scope analogue of [`load_index_meta`]. Rehydrates the
/// edge-property-index registry from [`CF_EDGE_INDEX_META`] at open
/// time.
fn load_edge_index_meta(db: &DB) -> Result<Vec<EdgePropertyIndexSpec>> {
    let cf = db
        .cf_handle(CF_EDGE_INDEX_META)
        .ok_or(Error::MissingColumnFamily(CF_EDGE_INDEX_META))?;
    let mut specs = Vec::new();
    for item in db.iterator_cf(cf, IteratorMode::Start) {
        let (key, _) = item?;
        specs.push(edge_index_meta_key_decode(&key)?);
    }
    Ok(specs)
}

/// Rehydrate the point-index registry from [`CF_POINT_INDEX_META`]
/// at open. Same once-per-process walk as the other meta loaders.
fn load_point_index_meta(db: &DB) -> Result<Vec<PointIndexSpec>> {
    let cf = db
        .cf_handle(CF_POINT_INDEX_META)
        .ok_or(Error::MissingColumnFamily(CF_POINT_INDEX_META))?;
    let mut specs = Vec::new();
    for item in db.iterator_cf(cf, IteratorMode::Start) {
        let (key, _) = item?;
        specs.push(point_index_meta_key_decode(&key)?);
    }
    Ok(specs)
}

/// Relationship-scope analogue of [`load_point_index_meta`].
fn load_edge_point_index_meta(db: &DB) -> Result<Vec<EdgePointIndexSpec>> {
    let cf = db
        .cf_handle(CF_EDGE_POINT_INDEX_META)
        .ok_or(Error::MissingColumnFamily(CF_EDGE_POINT_INDEX_META))?;
    let mut specs = Vec::new();
    for item in db.iterator_cf(cf, IteratorMode::Start) {
        let (key, _) = item?;
        specs.push(edge_point_index_meta_key_decode(&key)?);
    }
    Ok(specs)
}

impl StorageEngine for RocksDbStorageEngine {
    fn put_node(&self, node: &Node) -> Result<()> {
        RocksDbStorageEngine::put_node(self, node)
    }

    fn get_node(&self, id: NodeId) -> Result<Option<Node>> {
        RocksDbStorageEngine::get_node(self, id)
    }

    fn detach_delete_node(&self, id: NodeId) -> Result<()> {
        RocksDbStorageEngine::detach_delete_node(self, id)
    }

    fn put_edge(&self, edge: &Edge) -> Result<()> {
        RocksDbStorageEngine::put_edge(self, edge)
    }

    fn get_edge(&self, id: EdgeId) -> Result<Option<Edge>> {
        RocksDbStorageEngine::get_edge(self, id)
    }

    fn delete_edge(&self, id: EdgeId) -> Result<()> {
        RocksDbStorageEngine::delete_edge(self, id)
    }

    fn apply_batch(&self, mutations: &[GraphMutation]) -> Result<()> {
        RocksDbStorageEngine::apply_batch(self, mutations)
    }

    fn all_nodes(&self) -> Result<Vec<Node>> {
        RocksDbStorageEngine::all_nodes(self)
    }

    fn all_edges(&self) -> Result<Vec<Edge>> {
        RocksDbStorageEngine::all_edges(self)
    }

    fn all_node_ids(&self) -> Result<Vec<NodeId>> {
        RocksDbStorageEngine::all_node_ids(self)
    }

    fn outgoing(&self, source: NodeId) -> Result<Vec<(EdgeId, NodeId)>> {
        RocksDbStorageEngine::outgoing(self, source)
    }

    fn incoming(&self, target: NodeId) -> Result<Vec<(EdgeId, NodeId)>> {
        RocksDbStorageEngine::incoming(self, target)
    }

    fn nodes_by_label(&self, label: &str) -> Result<Vec<NodeId>> {
        RocksDbStorageEngine::nodes_by_label(self, label)
    }

    fn edges_by_type(&self, edge_type: &str) -> Result<Vec<EdgeId>> {
        RocksDbStorageEngine::edges_by_type(self, edge_type)
    }

    fn nodes_by_property(
        &self,
        label: &str,
        property: &str,
        value: &Property,
    ) -> Result<Vec<NodeId>> {
        RocksDbStorageEngine::nodes_by_property(self, label, property, value)
    }

    fn nodes_by_properties(
        &self,
        label: &str,
        properties: &[String],
        values: &[Property],
    ) -> Result<Vec<NodeId>> {
        RocksDbStorageEngine::nodes_by_properties(self, label, properties, values)
    }

    fn edges_by_property(
        &self,
        edge_type: &str,
        property: &str,
        value: &Property,
    ) -> Result<Vec<EdgeId>> {
        RocksDbStorageEngine::edges_by_property(self, edge_type, property, value)
    }

    fn create_property_index(&self, label: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::create_property_index(self, label, property)
    }

    fn drop_property_index(&self, label: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::drop_property_index(self, label, property)
    }

    fn create_property_index_composite(&self, label: &str, properties: &[String]) -> Result<()> {
        RocksDbStorageEngine::create_property_index_composite(self, label, properties)
    }

    fn drop_property_index_composite(&self, label: &str, properties: &[String]) -> Result<()> {
        RocksDbStorageEngine::drop_property_index_composite(self, label, properties)
    }

    fn list_property_indexes(&self) -> Vec<PropertyIndexSpec> {
        RocksDbStorageEngine::list_property_indexes(self)
    }

    fn create_edge_property_index(&self, edge_type: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::create_edge_property_index(self, edge_type, property)
    }

    fn drop_edge_property_index(&self, edge_type: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::drop_edge_property_index(self, edge_type, property)
    }

    fn create_edge_property_index_composite(
        &self,
        edge_type: &str,
        properties: &[String],
    ) -> Result<()> {
        RocksDbStorageEngine::create_edge_property_index_composite(self, edge_type, properties)
    }

    fn drop_edge_property_index_composite(
        &self,
        edge_type: &str,
        properties: &[String],
    ) -> Result<()> {
        RocksDbStorageEngine::drop_edge_property_index_composite(self, edge_type, properties)
    }

    fn list_edge_property_indexes(&self) -> Vec<EdgePropertyIndexSpec> {
        RocksDbStorageEngine::list_edge_property_indexes(self)
    }

    fn create_point_index(&self, label: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::create_point_index(self, label, property)
    }

    fn drop_point_index(&self, label: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::drop_point_index(self, label, property)
    }

    fn list_point_indexes(&self) -> Vec<PointIndexSpec> {
        RocksDbStorageEngine::list_point_indexes(self)
    }

    fn nodes_in_bbox(
        &self,
        label: &str,
        property: &str,
        srid: i32,
        xlo: f64,
        ylo: f64,
        xhi: f64,
        yhi: f64,
    ) -> Result<Vec<NodeId>> {
        RocksDbStorageEngine::nodes_in_bbox(self, label, property, srid, xlo, ylo, xhi, yhi)
    }

    fn create_edge_point_index(&self, edge_type: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::create_edge_point_index(self, edge_type, property)
    }

    fn drop_edge_point_index(&self, edge_type: &str, property: &str) -> Result<()> {
        RocksDbStorageEngine::drop_edge_point_index(self, edge_type, property)
    }

    fn list_edge_point_indexes(&self) -> Vec<EdgePointIndexSpec> {
        RocksDbStorageEngine::list_edge_point_indexes(self)
    }

    fn edges_in_bbox(
        &self,
        edge_type: &str,
        property: &str,
        srid: i32,
        xlo: f64,
        ylo: f64,
        xhi: f64,
        yhi: f64,
    ) -> Result<Vec<EdgeId>> {
        RocksDbStorageEngine::edges_in_bbox(self, edge_type, property, srid, xlo, ylo, xhi, yhi)
    }

    fn create_property_constraint(
        &self,
        name: Option<&str>,
        scope: &ConstraintScope,
        properties: &[String],
        kind: PropertyConstraintKind,
        if_not_exists: bool,
    ) -> Result<PropertyConstraintSpec> {
        RocksDbStorageEngine::create_property_constraint(
            self,
            name,
            scope,
            properties,
            kind,
            if_not_exists,
        )
    }

    fn drop_property_constraint(&self, name: &str, if_exists: bool) -> Result<()> {
        RocksDbStorageEngine::drop_property_constraint(self, name, if_exists)
    }

    fn list_property_constraints(&self) -> Vec<PropertyConstraintSpec> {
        RocksDbStorageEngine::list_property_constraints(self)
    }

    fn put_trigger(&self, name: &str, value: &[u8]) -> Result<()> {
        let cf = self.cf(CF_TRIGGER_META)?;
        self.db
            .put_cf(cf, name.as_bytes(), value)
            .map_err(Error::from)
    }

    fn delete_trigger(&self, name: &str) -> Result<()> {
        let cf = self.cf(CF_TRIGGER_META)?;
        self.db.delete_cf(cf, name.as_bytes()).map_err(Error::from)
    }

    fn list_triggers(&self) -> Result<Vec<(String, Vec<u8>)>> {
        let cf = self.cf(CF_TRIGGER_META)?;
        let mut out: Vec<(String, Vec<u8>)> = Vec::new();
        let iter = self.db.iterator_cf(cf, IteratorMode::Start);
        for entry in iter {
            let (k, v) = entry.map_err(Error::from)?;
            // Names are stored as raw UTF-8 bytes — anything else
            // would be a corruption since `put_trigger` only
            // accepts `&str`. Lossy decode is defensive.
            let name = String::from_utf8_lossy(&k).into_owned();
            out.push((name, v.to_vec()));
        }
        Ok(out)
    }

    fn put_pending_tx(&self, key: &[u8], value: &[u8]) -> Result<()> {
        let cf = self.cf(CF_PENDING_TX_META)?;
        self.db.put_cf(cf, key, value).map_err(Error::from)
    }

    fn delete_pending_tx(&self, key: &[u8]) -> Result<()> {
        let cf = self.cf(CF_PENDING_TX_META)?;
        self.db.delete_cf(cf, key).map_err(Error::from)
    }

    fn list_pending_txs(&self) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
        let cf = self.cf(CF_PENDING_TX_META)?;
        let mut out: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
        let iter = self.db.iterator_cf(cf, IteratorMode::Start);
        for entry in iter {
            let (k, v) = entry.map_err(Error::from)?;
            out.push((k.to_vec(), v.to_vec()));
        }
        Ok(out)
    }

    fn create_checkpoint(&self, path: &Path) -> Result<()> {
        RocksDbStorageEngine::create_checkpoint(self, path)
    }

    fn clear_all(&self) -> Result<()> {
        RocksDbStorageEngine::clear_all(self)
    }
}