1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
use crate::ingest::{IngestOptions, IngestReport};
use crate::roles::{PropPredicate, RoleDef, RolesFile, WriteScope};
use crate::subscription::{
event_matches, DbEvent, SubEntry, SubFilter, SubInner, Subscription, DEFAULT_SUB_CAPACITY,
};
use core_query::cypher::ast::{ret_val_label, ArithOp};
use core_query::cypher::{
execute, execute_union, is_subscribable, is_write_tokens, lex, parse, parse_read, parse_write,
plan, Expr, MatchDeleteNodeStmt, NodePat, Operand, Params, Pattern, PlanOp, Query, RetItem,
RetVal, WriteStatement,
};
use core_query::{eval_cmp, eval_filter, expand, neighborhood, Dir, Filter, GraphView, ResultSet};
use core_rules::{
decode_rule_def, ef_max, evaluate, BuildProgress, EngineEdgeDelta, GraphMut, NodeView,
Predicate, RuleDef, RuleEngine, ViewDef, ViewStore,
};
use core_storage::fs::{FileId, Fs, FsIntrospect, RealFs};
use core_storage::fulltext::FulltextIndex;
use core_storage::property_index::PropertyIndex;
use core_storage::v8::encode::{
archived_hnsw_to_owned, archived_rules_meta_to_owned, archived_to_idmap, archived_to_interner,
archived_views_to_owned, decode_last_change_bytes, decode_meta, encode_v8, V8Meta,
};
use core_storage::v8::seam::TopologyView;
use core_storage::wal::{decode_all, encode_record, WalRecord};
use core_storage::EdgePropsView;
use core_storage::{
namespace_of_value, ColumnStore, Direction, EdgeProps, GraphError, IdMap, Interner, Result,
Topology, Value,
};
pub use core_storage::{valid_namespace, NS_DEFAULT, NS_MAX_LEN, NS_PROP};
/// Index of [`NS_DEFAULT`] in `GraphDb::ns_names` — always zero, so the
/// open-time pass over a store with no `ns` column fills `node_ns` with one
/// constant and allocates no names.
const NS_DEFAULT_IDX: u32 = 0;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
/// Print a timing checkpoint when MUSHROOMDB_TRACE_OPEN is set.
/// Zero-cost when the env var is absent (the var check is O(1) after first call).
macro_rules! trace_open {
($phase:literal, $t:expr) => {
if std::env::var("MUSHROOMDB_TRACE_OPEN").is_ok() {
eprintln!(
"[MUSHROOMDB_TRACE_OPEN] {:40} {:>9.3?}",
$phase,
$t.elapsed()
);
}
};
}
/// Print a migration phase checkpoint when MUSHROOMDB_TRACE_MIGRATE is set.
/// Zero-cost when the env var is absent (the var check is O(1) after first call).
macro_rules! trace_migrate {
($phase:literal, $t:expr) => {
if std::env::var("MUSHROOMDB_TRACE_MIGRATE").is_ok() {
eprintln!(
"[MUSHROOMDB_TRACE_MIGRATE] {:40} {:>9.3?}",
$phase,
$t.elapsed()
);
}
};
}
// Test-only: counts how many times `pending_deltas_since().to_vec()` actually
// executes (i.e., at least one view is defined). Used to verify the fast-path
// guard skips the allocation when `view_store.is_empty()`.
#[cfg(test)]
thread_local! {
static DELTA_COPY_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
// Per-thread count of query-subscription `execute` calls in `distribute_events`.
//
// Incremented each time a query subscription actually runs its plan (i.e.,
// the label-skip fast-path did not fire). Because `distribute_events` is
// called synchronously on the writer thread, this thread-local correctly
// isolates each test thread's count even when integration tests run in
// parallel. Read via [`query_sub_exec_count`].
thread_local! {
static QUERY_SUB_EXECS_TL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Return the number of query-subscription re-executions logged on this
/// thread since the process started (or since last reset via
/// [`reset_query_sub_exec_count`]).
///
/// Primarily for integration tests that verify the label-skip fast-path.
#[doc(hidden)]
pub fn query_sub_exec_count() -> usize {
QUERY_SUB_EXECS_TL.with(|c| c.get())
}
/// Reset the per-thread query-subscription execution counter to zero.
#[doc(hidden)]
pub fn reset_query_sub_exec_count() {
QUERY_SUB_EXECS_TL.with(|c| c.set(0));
}
/// Internal state for a single `subscribe_query` subscription.
///
/// On every commit, `distribute_events` re-executes `ops` against the current
/// graph state, diffs the result against `prev_rows`, and pushes
/// `DbEvent::QueryRowAdded` / `QueryRowRemoved` events to `inner`.
///
/// **Full re-run per commit; use LIMIT to bound execution cost.**
/// (Differential evaluation is roadmap / Phase 5.)
pub(crate) struct QuerySubEntry {
/// Compiled plan for the subscribed Cypher query.
ops: Vec<PlanOp>,
/// Column names from the first execution (fixed for the subscription lifetime).
columns: Vec<String>,
/// Serialized (JSON) row key → row data, representing the result set at
/// the end of the last commit. Used to diff against the new result.
prev_row_map: std::collections::HashMap<String, Vec<Option<Value>>>,
/// Weak pointer to the subscriber queue; dead Weak → subscription dropped.
inner: std::sync::Weak<SubInner>,
/// Interned label sym captured at subscribe time from the plan's leading scan
/// (`ScanLabel`, `IndexScan`, or `IndexIntersect` with a concrete label).
///
/// `None` means the plan has an `Expand` op (or no recognizable leading scan
/// with a concrete label), and this subscription must re-execute on every
/// commit without skipping. This is the conservative v0.4.3 boundary: Expand
/// queries are never skipped because edges can alter join results regardless
/// of which node labels were written.
scan_label: Option<u32>,
}
/// A post-commit mutation notification.
///
/// Emitted from `log_then_apply` after the WAL append, fsync, and
/// in-memory `apply` all succeed. Never emitted for rejected operations
/// (validation errors, [`GraphError::RuleOwned`], duplicate keys, no-op
/// deletes/removes). Event payloads carry user keys and rule names, never
/// internal ids.
///
/// **Replay:** [`GraphDb::open`] / [`GraphDb::open_with`] replay the WAL via
/// `apply` only. Emission lives exclusively in `log_then_apply`, so
/// recovery is silent even if a sink were installed (it cannot be: the
/// sink is in-memory and set after open).
///
/// **Ordering:** a `Batch` WAL frame emits one event per inner record, then
/// [`MutationEvent::BatchApplied`]. An ingest commit emits those same inner
/// events, then [`MutationEvent::Ingested`] (not `BatchApplied`). An empty
/// or all-noop batch writes no WAL and emits nothing (including no summary).
///
/// **Derived edges:** rule-created or retracted edges are not individually
/// evented — they are recoverable from the triggering mutation plus the live
/// rule set. Only the triggering record is emitted.
///
/// **Wire form:** externally tagged snake_case JSON
/// (`{"node_inserted":{"label":"A","key":"k"}}`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MutationEvent {
NodeInserted {
label: String,
key: String,
},
PropSet {
key: String,
field: String,
},
PropRemoved {
key: String,
field: String,
},
EdgeInserted {
edge_type: String,
src: String,
dst: String,
},
EdgeDeleted {
edge_type: String,
src: String,
dst: String,
},
NodeDeleted {
key: String,
},
RuleCreated {
name: String,
},
RuleDeleted {
name: String,
},
RuleRebuilt {
name: String,
},
BatchApplied {
ops: usize,
},
Ingested {
label: String,
inserted: usize,
},
}
fn event_from_record(rec: &WalRecord, intern: &Interner, ids: &IdMap) -> Option<MutationEvent> {
match rec {
WalRecord::InsertNode { label, key, .. } => Some(MutationEvent::NodeInserted {
label: label.clone(),
key: key.clone(),
}),
WalRecord::InsertNodeId { label, key, .. } => Some(MutationEvent::NodeInserted {
label: intern.resolve(*label)?.to_string(),
key: key.clone(),
}),
WalRecord::SetProp { key, field, .. } => Some(MutationEvent::PropSet {
key: key.clone(),
field: field.clone(),
}),
WalRecord::SetPropId { id, field, .. } => Some(MutationEvent::PropSet {
key: ids.key_of(*id)?.to_string(),
field: intern.resolve(*field)?.to_string(),
}),
WalRecord::RemoveProp { key, field } => Some(MutationEvent::PropRemoved {
key: key.clone(),
field: field.clone(),
}),
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => Some(MutationEvent::EdgeInserted {
edge_type: edge_type.clone(),
src: src_key.clone(),
dst: dst_key.clone(),
}),
WalRecord::InsertEdgeId { etype, src, dst } => Some(MutationEvent::EdgeInserted {
edge_type: intern.resolve(*etype)?.to_string(),
src: ids.key_of(*src)?.to_string(),
dst: ids.key_of(*dst)?.to_string(),
}),
WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
} => Some(MutationEvent::EdgeDeleted {
edge_type: edge_type.clone(),
src: src_key.clone(),
dst: dst_key.clone(),
}),
WalRecord::DeleteNode { key } => Some(MutationEvent::NodeDeleted { key: key.clone() }),
WalRecord::CreateRule { def_bytes } => {
let def: RuleDef = decode_rule_def(def_bytes).ok()?;
Some(MutationEvent::RuleCreated { name: def.name })
}
WalRecord::DeleteRule { name } => Some(MutationEvent::RuleDeleted { name: name.clone() }),
WalRecord::RebuildRule { name } => Some(MutationEvent::RuleRebuilt { name: name.clone() }),
WalRecord::Batch(_)
| WalRecord::CreateView { .. }
| WalRecord::DeleteView { .. }
| WalRecord::EnableFulltext { .. }
| WalRecord::DisableFulltext { .. }
| WalRecord::EnableIndex { .. }
| WalRecord::DisableIndex { .. }
| WalRecord::Intern { .. }
// History markers are no-ops for mutation events — they carry no new
// state and rules re-derive deterministically on replay.
| WalRecord::DerivedEdgeAdded { .. }
| WalRecord::DerivedEdgeRetracted { .. }
// RenameNode carries no node/edge count change; no special event.
| WalRecord::RenameNode { .. } => None,
}
}
/// Database-wide counters plus per-rule budget/fire stats.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Stats {
pub nodes_live: usize,
pub nodes_tombstoned: usize,
pub edges: u64,
pub rules: Vec<RuleStats>,
/// How many writes hit the rule-chaining depth cap with work still pending,
/// since this handle was opened. Non-zero means some derived edges beyond
/// the cap are stale and no single later write will repair them: split the
/// rule chain or shorten it. Never persisted, so it resets on reopen.
#[serde(default)]
pub chain_truncations: u64,
/// The oldest commit index history still reaches (the WAL horizon floor).
/// `0` means nothing has been pruned and history is complete; a non-zero
/// value means events before that commit were pruned and are gone.
#[serde(default)]
pub history_floor: u64,
/// Live node counts per namespace, in name order. Always carries
/// `default` — a store is at least its default namespace — so a
/// single-tenant store reads `[{"name":"default", …}]` and a reader can
/// tell "no namespaces in use" from one entry.
#[serde(default)]
pub namespaces: Vec<NamespaceStats>,
}
/// Live node count for one namespace; one entry of [`Stats::namespaces`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NamespaceStats {
pub name: String,
pub nodes_live: usize,
}
/// One rule's provenance size, trip latch, and fire counter.
///
/// `tripped` is a one-way latch: once set, the engine adds no new edges for
/// that rule until [`GraphDb::rebuild_rule`] (and only if the full desired
/// set then fits). `fires` counts `on_node_changed` evaluations plus
/// backfill/rebuild participant ticks (rebuild counts even when it is a
/// provenance no-op).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RuleStats {
pub name: String,
pub edges: u64,
pub tripped: bool,
pub fires: u64,
/// Whether this rule uses the approximate IVF-Flat candidate path.
pub approximate: bool,
/// `Some` while this rule's vector index is still being built.
///
/// The rule derives **no** edges until it is `None`: the backfill is one
/// commit that runs after the index is whole, so a caller never sees a
/// partial edge set. Absent from the JSON when the rule is not building,
/// which is every rule created over a corpus at or below
/// [`core_rules::HNSW_BUILD_BATCH`] vectors.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub building: Option<BuildProgress>,
}
/// One entry in the slow-query ring buffer.
#[derive(Debug, Clone, Serialize)]
pub struct SlowQueryEntry {
/// Execution time in whole milliseconds.
pub ms: u64,
/// The Cypher query string that was slow.
pub query: String,
/// The commit sequence number at the time the query ran.
pub at_commit: u64,
}
/// Snapshot of the slow-query log returned by [`GraphDb::slow_query_snapshot`].
#[derive(Debug, Clone, Serialize)]
pub struct SlowQuerySnapshot {
/// Current threshold in milliseconds (0 = disabled).
pub threshold_ms: u64,
/// Total number of slow queries ever recorded (not capped by ring size).
pub count: u64,
/// Most-recent slow queries (up to 16), oldest first.
pub last: Vec<SlowQueryEntry>,
}
/// Internal ring-buffer state protected by a `Mutex` so `query(&self)` can
/// write to it without a mutable borrow.
struct SlowQueryLog {
entries: std::collections::VecDeque<SlowQueryEntry>,
total: u64,
}
/// Maximum number of entries kept in the slow-query ring buffer.
const SLOW_QUERY_RING_CAP: usize = 16;
/// Wire summary of a [`Predicate`]. JSON only — `Explanation` is never
/// bincode-persisted (WAL/snapshots store `RuleDef` bytes, not this type).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PredicateSummary {
pub kind: String,
pub fields: Vec<String>,
pub min: Option<f64>,
pub tolerance: Option<f64>,
pub km: Option<f64>,
pub parts: Option<Vec<PredicateSummary>>,
/// True when the owning rule has `approximate=true` (IVF-Flat candidate path).
/// Always false for predicates reported without rule context (sub-predicates in `parts`).
#[serde(default)]
pub approximate: bool,
}
impl From<&Predicate> for PredicateSummary {
fn from(p: &Predicate) -> Self {
match p {
Predicate::KeyMatch { field } => PredicateSummary {
kind: "key_match".into(),
fields: vec![field.clone()],
min: None,
tolerance: None,
km: None,
parts: None,
approximate: false,
},
Predicate::FieldEqual { field } => PredicateSummary {
kind: "field_equal".into(),
fields: vec![field.clone()],
min: None,
tolerance: None,
km: None,
parts: None,
approximate: false,
},
Predicate::Overlap { field, min } => PredicateSummary {
kind: "overlap".into(),
fields: vec![field.clone()],
min: Some(*min),
tolerance: None,
km: None,
parts: None,
approximate: false,
},
Predicate::NumericWithin { field, tolerance } => PredicateSummary {
kind: "numeric_within".into(),
fields: vec![field.clone()],
min: None,
tolerance: Some(*tolerance),
km: None,
parts: None,
approximate: false,
},
Predicate::GeoRadius { field, km } => PredicateSummary {
kind: "geo_radius".into(),
fields: vec![field.clone()],
min: None,
tolerance: None,
km: Some(*km),
parts: None,
approximate: false,
},
Predicate::VectorSimilar { field, min } => PredicateSummary {
kind: "vector_similar".into(),
fields: vec![field.clone()],
min: Some(*min),
tolerance: None,
km: None,
parts: None,
approximate: false,
},
Predicate::All(inner) => {
let parts: Vec<PredicateSummary> = inner.iter().map(Self::from).collect();
let mut fields = Vec::new();
for part in &parts {
for f in &part.fields {
if !fields.contains(f) {
fields.push(f.clone());
}
}
}
PredicateSummary {
kind: "all".into(),
fields,
min: None,
tolerance: None,
km: None,
parts: Some(parts),
approximate: false,
}
}
Predicate::Any(inner) => {
let parts: Vec<PredicateSummary> = inner.iter().map(Self::from).collect();
let mut fields = Vec::new();
for part in &parts {
for f in &part.fields {
if !fields.contains(f) {
fields.push(f.clone());
}
}
}
PredicateSummary {
kind: "any".into(),
fields,
min: None,
tolerance: None,
km: None,
parts: Some(parts),
approximate: false,
}
}
}
}
}
/// Snapshot of a live node's key, label, and columnar properties.
///
/// `props` is a [`BTreeMap`] so field order is deterministic (sorted by name)
/// regardless of insert order or the columnar store's `HashMap` iteration.
///
/// Deliberately does not derive `Serialize`: `Value`'s serde form is
/// internally tagged. Wire JSON is built by `value_to_json` in the server.
#[derive(Debug, Clone, PartialEq)]
pub struct NodeInfo {
pub key: String,
pub label: String,
pub props: BTreeMap<String, Value>,
}
/// Counts returned by [`GraphDb::delete_node`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DeleteReport {
/// Number of manual (user-inserted) edges removed.
pub manual_edges: u64,
/// Number of derived (rule-owned) edges retracted.
pub derived_edges: u64,
}
/// One directed edge incident on a node, with provenance membership.
///
/// `derived` is true iff `(edge_type, src, dst)` is in the rule engine's
/// Plan-8 `by_node` provenance index.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct EdgeInfo {
pub edge_type: String,
pub src_key: String,
pub dst_key: String,
pub derived: bool,
}
/// One directed edge incident on a node at a point in WAL history, with the
/// rule that derived it when it is rule-owned.
///
/// Returned by [`GraphDb::edges_at`] (sorted by `(edge_type, src_key, dst_key)`)
/// and by [`GraphDb::what_if_set_prop`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct EdgeAt {
pub edge_type: String,
pub src_key: String,
pub dst_key: String,
/// `true` when a rule wrote the edge (`DerivedEdgeAdded` in the WAL, or a
/// live provenance entry).
pub derived: bool,
/// The rule that derived the edge. `None` for a manual edge.
pub rule: Option<String>,
}
/// The derived edges a hypothetical property change would retract and derive.
///
/// Returned by [`GraphDb::what_if_set_prop`]. Both lists are sorted by
/// `(edge_type, src_key, dst_key)` and every entry is rule-derived.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WhatIf {
/// Derived edges that exist now and would be retracted.
pub lost: Vec<EdgeAt>,
/// Derived edges that do not exist now and would be derived.
pub gained: Vec<EdgeAt>,
}
/// An edge with mask-aware endpoint visibility.
///
/// Returned by [`GraphDb::node_edges_masked`] in [`crate::mask::MaskMode::Stub`]
/// mode — hidden endpoints carry `*_restricted: true`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MaskedEdge {
pub edge_type: String,
pub src_key: String,
/// `true` when `src_key` is in the DB but hidden from the mask.
pub src_restricted: bool,
pub dst_key: String,
/// `true` when `dst_key` is in the DB but hidden from the mask.
pub dst_restricted: bool,
pub derived: bool,
}
/// Result of a mask-aware node lookup via [`GraphDb::node_info_masked`].
///
/// `None` from that method means the key does not exist (→ 404).
/// `Some(Restricted)` is only produced when `mask.mode() == MaskMode::Stub`.
#[derive(Debug, PartialEq)]
pub enum MaskedNodeResult {
Visible(NodeInfo),
/// Node exists in the DB but is hidden from this mask.
Restricted,
}
/// One rule-owned edge between two nodes, with the rule name, edge type,
/// direction (src_key → dst_key), and weight if the rule stores one.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Explanation {
pub rule: String,
pub edge_type: String,
pub src_key: String,
pub dst_key: String,
pub weight: Option<f64>,
pub predicate: PredicateSummary,
/// For a via-hop rule, the edge type the rule hops over to reach its
/// candidates. `None` for a plain two-node rule. A via-hop rule whose
/// `via_edge` is itself rule-derived is the chaining case: the hop edge
/// was written by another rule in the same commit.
#[serde(default)]
pub via_edge: Option<String>,
}
/// Report returned by [`GraphDb::backup_to`].
#[derive(Debug, Clone)]
pub struct BackupReport {
/// Filenames copied into the destination directory (sorted ascending).
pub files: Vec<String>,
/// Total bytes written across all copied files.
pub bytes: u64,
/// `true` when the destination opened cleanly and passed post-copy checks.
///
/// For stores that have a `snapshot.bin` this means: all V8 section CRCs
/// matched **and** the destination opened without error.
///
/// For WAL-only stores (no `snapshot.bin`) there is no snapshot to
/// CRC-check; `verified` is `true` when the destination opened and
/// replayed the WAL without error (record-level checksums in the WAL
/// provide the integrity signal, not section CRCs).
pub verified: bool,
}
/// One directed edge in export form, with optional rule attribution for derived edges.
///
/// Returned by [`GraphDb::all_edges_for_export`].
///
/// Does not derive `Eq`/`Ord`: `weight` is an `f64` and NaN breaks a total
/// order. Callers that need a stable edge ordering already sort by
/// `(edge_type, src, dst)` explicitly (see `all_edges_for_export`).
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ExportEdge {
pub edge_type: String,
pub src: String,
pub dst: String,
pub derived: bool,
/// Rule name that created this edge, if derived. `None` for manual edges.
pub rule: Option<String>,
/// The creating rule's declared `weight_prop`, read off this edge, when
/// derived and numeric (`Int`/`Float`). `None` for manual edges, derived
/// edges whose rule declares no `weight_prop`, or a non-numeric value.
pub weight: Option<f64>,
}
/// One edge type's shape, as [`GraphDb::edge_type_census`] counts it.
///
/// Deliberately per *type* and not per edge: everything here is a summary a
/// caller can print in one line, and none of it costs a record per edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EdgeTypeCensus {
pub edge_type: String,
/// Directed edges of this type. Counted the way
/// [`GraphDb::edge_count`] counts: each edge once, from its source.
pub edges: u64,
/// Every label seen on a source of this type, sorted.
pub src_labels: Vec<String>,
/// Every label seen on a destination of this type, sorted.
pub dst_labels: Vec<String>,
/// The rules that declare this `edge_type`, sorted. Empty for a type
/// written by hand.
pub rules: Vec<String>,
/// `(src key, dst key)` of the first edge of this type in the store's own
/// id order — a real pair to quote in an example.
pub sample: Option<(String, String)>,
}
/// Construct the standard write-query result set (columns: created, properties_set, deleted).
fn write_result_set() -> ResultSet {
ResultSet::new(vec![
"created".into(),
"properties_set".into(),
"deleted".into(),
])
}
fn resolve_merge_set_value(op: &Operand, params: &BTreeMap<String, Value>) -> Result<Value> {
match op {
Operand::Lit(v) => Ok(v.clone()),
Operand::Param(name) => params
.get(name)
.cloned()
.ok_or_else(|| GraphError::QueryError {
detail: format!("missing parameter `{name}`"),
}),
_ => Err(GraphError::QueryError {
detail: "ON CREATE/ON MATCH SET value must be a literal or $parameter".into(),
}),
}
}
fn operand_node_vars(op: &Operand, out: &mut Vec<String>) {
match op {
Operand::Prop { var, .. } | Operand::Var(var) => {
if !out.contains(var) {
out.push(var.clone());
}
}
Operand::FuncCall { args, .. } => {
for arg in args {
operand_node_vars(arg, out);
}
}
Operand::BinArith { left, right, .. } => {
operand_node_vars(left, out);
operand_node_vars(right, out);
}
Operand::Case { branches, default } => {
// Branch conditions reference vars already bound (and mask-filtered)
// by the MATCH phase, so collecting from the value operands + ELSE
// is sufficient for RETURN-projection var discovery.
for (_, value) in branches {
operand_node_vars(value, out);
}
if let Some(d) = default {
operand_node_vars(d, out);
}
}
Operand::Index { base, index } => {
operand_node_vars(base, out);
operand_node_vars(index, out);
}
Operand::Lit(_) | Operand::Param(_) => {}
}
}
fn ret_node_vars(items: &[RetItem]) -> Vec<String> {
let mut out = Vec::new();
for item in items {
match &item.value {
RetVal::Var(v) | RetVal::Prop { var: v, .. } => {
if !out.contains(v) {
out.push(v.clone());
}
}
RetVal::FuncCall { args, .. } => {
for arg in args {
operand_node_vars(arg, &mut out);
}
}
RetVal::ScalarExpr(op) => operand_node_vars(op, &mut out),
RetVal::Agg { .. } => {}
}
}
out
}
fn add_var(out: &mut Vec<String>, v: &str) {
if !out.iter().any(|x| x == v) {
out.push(v.to_string());
}
}
fn pattern_node_vars(pats: &[Pattern]) -> Vec<String> {
let mut out = Vec::new();
for p in pats {
if let Some(v) = &p.start.var {
add_var(&mut out, v);
}
for (_, dest) in &p.chain {
if let Some(v) = &dest.var {
add_var(&mut out, v);
}
}
}
out
}
fn pattern_rel_vars(pats: &[Pattern]) -> Vec<String> {
let mut out = Vec::new();
for p in pats {
for (rel, _) in &p.chain {
if rel.hops.is_none() {
if let Some(v) = &rel.var {
add_var(&mut out, v);
}
}
}
}
out
}
fn rel_type_alias(var: &str) -> String {
format!("__rt_{var}")
}
fn ret_column_name(item: &RetItem) -> String {
if let Some(alias) = &item.alias {
return alias.clone();
}
// The same naming rule the planner and the executor use, so a
// write-statement RETURN names its columns exactly as a read query does.
// An aggregate is not legal in a write-statement RETURN; it keeps the
// placeholder it always had.
ret_val_label(&item.value).unwrap_or_else(|| "<agg>".to_string())
}
fn eval_set_return_operand<F: Fs>(
db: &GraphDb<F>,
match_rs: &ResultSet,
row: usize,
rel_vars: &[String],
op: &Operand,
params: &BTreeMap<String, Value>,
) -> Result<Option<Value>> {
match op {
Operand::Lit(v) => Ok(Some(v.clone())),
Operand::Param(name) => params.get(name).cloned().ok_or_else(|| GraphError::QueryError {
detail: format!("missing parameter `{name}`"),
}).map(Some),
Operand::Var(name) if rel_vars.iter().any(|r| r == name) => Err(GraphError::QueryError {
detail: format!(
"cannot return relationship variable '{name}' bare; return its properties ({name}.field) instead"
),
}),
Operand::Var(name) => Ok(match_rs.get(row, name).cloned()),
Operand::Prop { var, field } => {
if rel_vars.iter().any(|r| r == var) {
return Ok(None);
}
let Some(Value::Str(key)) = match_rs.get(row, var) else {
return Ok(None);
};
if let Some(v) = db.get_prop(key, field) {
return Ok(Some(v));
}
// Same stored-wins identity fallback as the read path:
// n.key / n.id / n.label, not only get_prop.
Ok(match field.as_str() {
"key" | "id" => Some(Value::Str(key.clone())),
"label" => db
.node_ref(key)
.map(|n| Value::Str(n.label().to_owned())),
_ => None,
})
}
Operand::FuncCall { name, args } => {
eval_set_return_func(db, match_rs, row, rel_vars, name, args, params)
}
Operand::BinArith { op, left, right } => {
let lv = eval_set_return_operand(db, match_rs, row, rel_vars, left, params)?;
let rv = eval_set_return_operand(db, match_rs, row, rel_vars, right, params)?;
eval_set_return_arith(op, lv, rv)
}
Operand::Case { branches, default } => {
for (cond, value) in branches {
if eval_set_return_expr(db, match_rs, row, rel_vars, cond, params, 0)? {
return eval_set_return_operand(db, match_rs, row, rel_vars, value, params);
}
}
match default {
Some(d) => eval_set_return_operand(db, match_rs, row, rel_vars, d, params),
None => Ok(None),
}
}
Operand::Index { base, index } => {
let base_val = eval_set_return_operand(db, match_rs, row, rel_vars, base, params)?;
let idx_val = eval_set_return_operand(db, match_rs, row, rel_vars, index, params)?;
Ok(core_query::value_ops::index_list(base_val, idx_val))
}
}
}
fn eval_set_return_expr<F: Fs>(
db: &GraphDb<F>,
match_rs: &ResultSet,
row: usize,
rel_vars: &[String],
expr: &Expr,
params: &BTreeMap<String, Value>,
depth: u32,
) -> Result<bool> {
if depth > 256 {
return Err(GraphError::QueryError {
detail: "expression nesting too deep".into(),
});
}
match expr {
Expr::And(lhs, rhs) => {
let l = eval_set_return_expr(db, match_rs, row, rel_vars, lhs, params, depth + 1)?;
let r = eval_set_return_expr(db, match_rs, row, rel_vars, rhs, params, depth + 1)?;
Ok(l && r)
}
Expr::Or(lhs, rhs) => {
let l = eval_set_return_expr(db, match_rs, row, rel_vars, lhs, params, depth + 1)?;
let r = eval_set_return_expr(db, match_rs, row, rel_vars, rhs, params, depth + 1)?;
Ok(l || r)
}
Expr::Not(inner) => Ok(!eval_set_return_expr(
db,
match_rs,
row,
rel_vars,
inner,
params,
depth + 1,
)?),
Expr::Cmp { lhs, op, rhs } => {
let l = eval_set_return_operand(db, match_rs, row, rel_vars, lhs, params)?;
let r = eval_set_return_operand(db, match_rs, row, rel_vars, rhs, params)?;
match (l, r) {
(Some(a), Some(b)) => Ok(eval_cmp(op, &a, &b)),
_ => Ok(false),
}
}
Expr::Truthy(op) => {
let val = eval_set_return_operand(db, match_rs, row, rel_vars, op, params)?;
Ok(match val {
None => false,
Some(Value::Bool(b)) => b,
Some(Value::Int(n)) => n != 0,
Some(Value::Float(f)) => f != 0.0,
Some(Value::Str(s)) => !s.is_empty(),
Some(Value::List(v)) => !v.is_empty(),
Some(Value::Map(m)) => !m.is_empty(),
})
}
Expr::IsNull(op) => {
let val = eval_set_return_operand(db, match_rs, row, rel_vars, op, params)?;
Ok(val.is_none())
}
Expr::IsNotNull(op) => {
let val = eval_set_return_operand(db, match_rs, row, rel_vars, op, params)?;
Ok(val.is_some())
}
Expr::In { expr, list } => {
let Some(needle) = eval_set_return_operand(db, match_rs, row, rel_vars, expr, params)?
else {
return Ok(false);
};
for item_op in list {
match eval_set_return_operand(db, match_rs, row, rel_vars, item_op, params)? {
None => {}
Some(Value::List(items)) => {
for item in items {
if eval_cmp(&core_query::CmpOp::Eq, &needle, &item) {
return Ok(true);
}
}
}
Some(item) if eval_cmp(&core_query::CmpOp::Eq, &needle, &item) => {
return Ok(true);
}
Some(_) => {}
}
}
Ok(false)
}
}
}
fn eval_set_return_arith(
op: &ArithOp,
lv: Option<Value>,
rv: Option<Value>,
) -> Result<Option<Value>> {
match (lv, rv) {
(None, _) | (_, None) => Ok(None),
(Some(Value::Int(a)), Some(Value::Int(b))) => {
let result = match op {
ArithOp::Sub => a.saturating_sub(b),
ArithOp::Mul => a.saturating_mul(b),
ArithOp::Add => a.saturating_add(b),
ArithOp::Div => {
if b == 0 {
return Err(GraphError::QueryError {
detail: "division by zero".into(),
});
}
a.checked_div(b).unwrap_or(i64::MAX)
}
};
Ok(Some(Value::Int(result)))
}
(Some(lv), Some(rv)) => {
let a = match &lv {
Value::Float(f) => *f,
Value::Int(i) => *i as f64,
_ => {
return Err(GraphError::QueryError {
detail: format!("arithmetic operand must be numeric, got {lv:?}"),
})
}
};
let b = match &rv {
Value::Float(f) => *f,
Value::Int(i) => *i as f64,
_ => {
return Err(GraphError::QueryError {
detail: format!("arithmetic operand must be numeric, got {rv:?}"),
})
}
};
let result = match op {
ArithOp::Sub => a - b,
ArithOp::Mul => a * b,
ArithOp::Add => a + b,
ArithOp::Div => {
if b == 0.0 {
return Err(GraphError::QueryError {
detail: "division by zero".into(),
});
}
a / b
}
};
Ok(Some(Value::Float(result)))
}
}
}
fn eval_set_return_func<F: Fs>(
db: &GraphDb<F>,
match_rs: &ResultSet,
row: usize,
rel_vars: &[String],
name: &str,
args: &[Operand],
params: &BTreeMap<String, Value>,
) -> Result<Option<Value>> {
let norm = name.to_ascii_lowercase();
if norm == "type" {
if args.len() != 1 {
return Err(GraphError::QueryError {
detail: format!("type() requires exactly 1 argument, got {}", args.len()),
});
}
let Operand::Var(rel) = &args[0] else {
return Err(GraphError::QueryError {
detail: "type() argument must be a relationship variable (e.g. type(r))".into(),
});
};
return Ok(match_rs.get(row, &rel_type_alias(rel)).cloned());
}
if norm == "key" || norm == "id" {
let fname = if norm == "id" { "id" } else { "key" };
if args.len() != 1 {
return Err(GraphError::QueryError {
detail: format!("{fname}() requires exactly 1 argument, got {}", args.len()),
});
}
let Operand::Var(var) = &args[0] else {
return Err(GraphError::QueryError {
detail: format!("{fname}() argument must be a node variable (e.g. {fname}(n))"),
});
};
if rel_vars.iter().any(|r| r == var) {
return Err(GraphError::QueryError {
detail: format!("{fname}() argument `{var}` is a relationship, not a node"),
});
}
// MATCH rows bind node variables to their key string, so the column
// value *is* the key. `id()` aliases `key()`.
return Ok(match_rs.get(row, var).cloned());
}
let mut vals = Vec::with_capacity(args.len());
for arg in args {
vals.push(eval_set_return_operand(
db, match_rs, row, rel_vars, arg, params,
)?);
}
match norm.as_str() {
"tolower" => {
if vals.len() != 1 {
return Err(GraphError::QueryError {
detail: format!("toLower() requires exactly 1 argument, got {}", vals.len()),
});
}
Ok(vals[0].clone().map(|val| match val {
Value::Str(s) => Value::Str(s.to_ascii_lowercase()),
other => other,
}))
}
"toupper" => {
if vals.len() != 1 {
return Err(GraphError::QueryError {
detail: format!("toUpper() requires exactly 1 argument, got {}", vals.len()),
});
}
Ok(vals[0].clone().map(|val| match val {
Value::Str(s) => Value::Str(s.to_ascii_uppercase()),
other => other,
}))
}
"size" => match vals.first().cloned().flatten() {
None => Ok(None),
Some(Value::Str(s)) => Ok(Some(Value::Int(s.len() as i64))),
Some(Value::List(items)) => Ok(Some(Value::Int(items.len() as i64))),
Some(_) => Ok(None),
},
"coalesce" => Ok(vals.into_iter().flatten().next()),
"abs" => match vals.first().cloned().flatten() {
None => Ok(None),
Some(Value::Int(n)) => Ok(Some(Value::Int(n.saturating_abs()))),
Some(Value::Float(f)) => Ok(Some(Value::Float(f.abs()))),
Some(_) => Ok(None),
},
"round" => match vals.first().cloned().flatten() {
None => Ok(None),
Some(Value::Float(f)) => Ok(Some(Value::Float(f.round()))),
Some(Value::Int(n)) => Ok(Some(Value::Int(n))),
Some(_) => Ok(None),
},
"decay" => {
if vals.len() != 3 {
return Err(GraphError::QueryError {
detail: format!("decay() requires exactly 3 arguments, got {}", vals.len()),
});
}
match (vals[0].clone(), vals[1].clone(), vals[2].clone()) {
(None, _, _) | (_, None, _) | (_, _, None) => Ok(None),
(Some(b), Some(a), Some(h)) => {
let numeric = |v: Value| -> Result<f64> {
match v {
Value::Int(n) => Ok(n as f64),
Value::Float(f) => Ok(f),
other => Err(GraphError::QueryError {
detail: format!(
"decay() requires numeric arguments, got {other:?}"
),
}),
}
};
let b = numeric(b)?;
let a = numeric(a)?;
let h = numeric(h)?;
if h <= 0.0 {
return Err(GraphError::QueryError {
detail: "decay() requires halflife > 0".into(),
});
}
Ok(Some(Value::Float(b * 0.5f64.powf(a / h))))
}
}
}
_ => Err(GraphError::QueryError {
detail: format!(
"unknown function `{name}`; supported: toLower, toUpper, size, coalesce, type, abs, round, decay, key, id"
),
}),
}
}
fn eval_set_return_item<F: Fs>(
db: &GraphDb<F>,
match_rs: &ResultSet,
row: usize,
rel_vars: &[String],
item: &RetItem,
params: &BTreeMap<String, Value>,
) -> Result<Option<Value>> {
match &item.value {
RetVal::Var(v) => eval_set_return_operand(
db,
match_rs,
row,
rel_vars,
&Operand::Var(v.clone()),
params,
),
RetVal::Prop { var, field } => eval_set_return_operand(
db,
match_rs,
row,
rel_vars,
&Operand::Prop {
var: var.clone(),
field: field.clone(),
},
params,
),
RetVal::FuncCall { name, args } => {
eval_set_return_func(db, match_rs, row, rel_vars, name, args, params)
}
RetVal::ScalarExpr(op) => eval_set_return_operand(db, match_rs, row, rel_vars, op, params),
RetVal::Agg { .. } => Err(GraphError::QueryError {
detail: "aggregates are not supported in MATCH … SET … RETURN".into(),
}),
}
}
/// Project user RETURN from original MATCH rows after SET. No rematch.
fn project_set_return_rows<F: Fs>(
db: &GraphDb<F>,
rel_vars: &[String],
match_rs: &ResultSet,
returns: &[RetItem],
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
let columns: Vec<String> = returns.iter().map(ret_column_name).collect();
let mut out = ResultSet::new(columns);
for row in 0..match_rs.len() {
let mut cells = Vec::with_capacity(returns.len());
for item in returns {
cells.push(eval_set_return_item(
db, match_rs, row, rel_vars, item, params,
)?);
}
out.push_row(cells);
}
Ok(out)
}
/// Single construction point for a `GraphMut` view over the split-borrowed graph fields.
/// Callers use `std::mem::take` on the engine before calling this, then restore it after.
/// Extract a `Vec<f64>` from a `Value::List` whose items are all numeric.
/// Returns `None` for non-list values or lists with non-numeric elements.
/// Extra candidates pulled from an approximate index before re-scoring, over and
/// above the `k` asked for.
///
/// The index orders candidates by `f32` distances, which agree with the exact
/// `f64` cosine to about 1e-6. Re-scoring can therefore only reshuffle
/// candidates inside a band that narrow — it cannot move a hit past one that is
/// further away by more than 1e-6 — so the only way a true top-`k` member can be
/// lost is if the index ranked it just outside `k` on the `f32` order. Fetching
/// `k + 16` covers any such band up to 16 members wide, which at 1e-6 means 16
/// vectors within a millionth of each other in cosine: a duplicate cluster, and
/// then the members are interchangeable anyway. `min` is applied to the exact
/// score, never to the index's, so a hit sitting on the threshold is decided
/// exactly.
const VECTOR_RESCORE_MARGIN: usize = 16;
/// Cosine similarity between an already-unit query and node `id`'s `field`
/// vector, read from the **`f64`** properties. `None` when the node has no
/// numeric-list vector there, or its norm is zero.
///
/// The single definition of the score this API reports. Both the brute-force
/// scan and the re-scoring step that follows an index lookup go through it, so
/// the two paths cannot disagree — which is the property
/// `index_and_brute_force_agree_on_scores` pins.
fn exact_vector_similarity(
view: &GraphView<'_>,
id: u32,
field: &str,
q_unit: &[f64],
) -> Option<f64> {
let v = view.prop(id, field)?;
let xs = value_as_float_list(&v.into_value())?;
let v_norm: f64 = xs.iter().map(|x| x * x).sum::<f64>().sqrt();
if v_norm == 0.0 {
return None;
}
Some(
q_unit
.iter()
.zip(xs.iter())
.map(|(a, b)| a * (b / v_norm))
.sum(),
)
}
fn value_as_float_list(v: &Value) -> Option<Vec<f64>> {
match v {
Value::List(items) => items
.iter()
.map(|item| match item {
Value::Float(f) => Some(*f),
Value::Int(i) => Some(*i as f64),
_ => None,
})
.collect(),
_ => None,
}
}
fn make_graph_mut<'a>(
ids: &'a IdMap,
syms: &'a mut Interner,
labels: &'a [u32],
props: core_storage::v8::seam::ColumnsView<'a>,
topo: &'a mut Topology,
base: &'a Option<std::sync::Arc<core_storage::v8::MappedBase>>,
edge_props: &'a mut EdgeProps,
) -> GraphMut<'a> {
GraphMut {
ids,
syms,
labels,
props,
topo,
base_topo: base_csr(base),
edge_props,
}
}
/// The archived CSR of an open V8 snapshot, for the rule engine's graph reads.
///
/// A store opened from a snapshot keeps its edges in the mapping and its
/// overlay empty, so a rule that reads the graph's shape has to see both.
fn base_csr(
base: &Option<std::sync::Arc<core_storage::v8::MappedBase>>,
) -> Option<&core_storage::v8::layout::ArchivedCsr> {
base.as_ref().map(|b| {
b.topology()
.expect("base topology section bounds validated at open")
})
}
/// Build a `ColumnsView` from the disjoint `props` overlay and optional V8 base.
///
/// Takes explicit field references rather than `&self` so the caller can hold
/// simultaneous mutable borrows of other fields (e.g. `syms`, `topo`).
fn build_props_view<'a>(
props: &'a ColumnStore,
base: &'a Option<std::sync::Arc<core_storage::v8::MappedBase>>,
) -> core_storage::v8::seam::ColumnsView<'a> {
match base {
None => core_storage::v8::seam::ColumnsView::owned(props),
Some(b) => {
let archived = b
.columns()
.expect("base columns section bounds validated at open");
core_storage::v8::seam::ColumnsView::with_base_cached(props, archived, b.mixed_cache())
.with_shared_strings(base_string_table(b))
}
}
}
/// The base columns section paired with the string table that resolves its
/// string ids — what `ViewStore` needs to read a neighbour's string property
/// out of a V9 snapshot.
fn base_columns(
base: &Option<std::sync::Arc<core_storage::v8::MappedBase>>,
) -> Option<core_storage::v8::seam::BaseColumns<'_>> {
base.as_ref().map(|b| core_storage::v8::seam::BaseColumns {
cols: b
.columns()
.expect("base columns section bounds validated at open"),
strings: base_string_table(b),
})
}
/// The shared string table of a V9 base, or `None` for a pre-V9 one.
///
/// Every `ColumnsView` built over a base must carry it: without it a V9
/// snapshot's string columns, whose own tables are empty, read back as absent.
fn base_string_table(
base: &core_storage::v8::MappedBase,
) -> Option<&core_storage::v8::layout::ArchivedStringTable> {
base.string_table()
.transpose()
.expect("base strings section bounds validated at open")
}
fn build_topo_view<'a>(
overlay: &'a Topology,
base: &'a Option<std::sync::Arc<core_storage::v8::MappedBase>>,
) -> core_storage::v8::seam::TopologyView<'a> {
match base {
None => core_storage::v8::seam::TopologyView::owned(overlay),
Some(b) => {
let archived_csr = b
.topology()
.expect("base topology section bounds validated at open");
core_storage::v8::seam::TopologyView::with_base(overlay, archived_csr)
}
}
}
/// When [`GraphDb`] calls `Fs::sync` after a WAL append.
///
/// Default is [`Strict`](FsyncPolicy::Strict): every `log_then_apply_with`
/// fsyncs (single `insert_node` / `set_prop`). Ingest and `write_batch`
/// emit one `WalRecord::Batch` and fsync once at that frame (Batched).
/// [`Relaxed`](FsyncPolicy::Relaxed) skips WAL sync; [`GraphDb::snapshot`]
/// is still durable via `write_atomic`. Crash-recovery DST stays Strict.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum FsyncPolicy {
/// Every WAL commit calls `fs.sync` (today's behavior).
#[default]
Strict,
/// Sync only at a `Batch` frame end. Single-op path stays Strict unless
/// this policy is set on the database.
Batched,
/// Never call `fs.sync`. [`GraphDb::snapshot`] still syncs via `write_atomic`.
Relaxed,
}
/// A precondition for a compare-and-set batch write.
///
/// All preconditions in a [`GraphDb::write_batch_cas`] or
/// [`crate::SharedDb::submit_batch_cas`] call are checked atomically before
/// any operation in the batch is applied. If any precondition fails, the
/// entire batch is rejected with [`GraphError::CasConflict`] and no WAL frame
/// is written.
///
/// # Touch definition
///
/// A node's last-change commit (`last_changed`) is updated when any of the
/// following state-changing WAL records touch it:
///
/// - `InsertNode` / `InsertNodeId` — the newly-inserted node.
/// - `SetProp` / `SetPropId` / `RemoveProp` — the property-bearing node.
/// - `InsertEdge` / `InsertEdgeId` / `DeleteEdge` — **both** src and dst
/// endpoints (an edge change touches both sides).
/// - `DeleteNode` — the node is tombstoned; `last_changed` returns `None`
/// for deleted keys so the pre-deletion entry is never observed.
///
/// History markers (`DerivedEdgeAdded` / `DerivedEdgeRetracted`) are
/// state no-ops. The underlying mutation that triggered rule firing already
/// updated the relevant nodes' last-change entries. Rule-management records
/// (`CreateRule`, `DeleteRule`, `RebuildRule`) and view/full-text declarations
/// do not touch any node's last-change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Precondition {
/// The node's last-change commit must equal `expected`.
///
/// Fails with [`GraphError::CasConflict`] when:
/// - The node does not exist (`last_changed` returns `None`), or
/// - The recorded commit seq does not match `expected`.
NodeUnchangedSince { key: String, expected: u64 },
/// The node must not exist (not inserted, or already deleted).
///
/// Fails with [`GraphError::CasConflict`] (expected=`u64::MAX`,
/// actual=`last_changed(key).unwrap_or(0)`) when the node is live.
NodeAbsent { key: String },
}
pub struct GraphDb<F: Fs> {
fs: F,
ids: IdMap,
syms: Interner,
topo: Topology,
props: ColumnStore,
labels: Vec<u32>, // node id -> label symbol
/// Namespace names by index; index [`NS_DEFAULT_IDX`] is always
/// [`NS_DEFAULT`]. Derived beside [`Self::node_ns`], never persisted.
///
/// A private table rather than the shared [`Interner`]: interning
/// `"default"` at open would add a symbol to the store's symbol table and
/// change the bytes of the next snapshot of a store that has no namespaces
/// at all.
ns_names: Vec<String>,
/// Namespace index per dense node id, into [`Self::ns_names`];
/// [`NS_DEFAULT_IDX`] for a node with no `ns` property.
///
/// Derived: built by one pass over the `ns` column at open (which reads
/// nothing when the column does not exist) and maintained at every node
/// insert. Never written to a snapshot or the WAL, because the property it
/// mirrors already is. A namespace cannot change, so no other record shape
/// can move a node between namespaces.
node_ns: Vec<u32>,
edge_props: EdgeProps,
engine: RuleEngine,
view_store: ViewStore,
/// Incremental inverted index for full-text-lite search.
/// Rebuild-on-open: populated from WAL replay + rebuild_all at open end.
fulltext: FulltextIndex,
/// Opt-in equality index over scalar node properties.
/// Rebuild-on-open: declarations replay from the WAL, postings rebuild at
/// open end (mirrors `fulltext`).
prop_index: PropertyIndex,
event_sink: Option<Box<dyn Fn(MutationEvent) + Send + Sync>>,
/// WAL fsync cadence. Default [`FsyncPolicy::Strict`].
fsync: FsyncPolicy,
/// Monotonically increasing per-commit counter. A single `log_then_apply_with`
/// call increments this once; all events emitted from that call share the same
/// `commit_seq` value.
commit_seq: u64,
/// RBAC role definitions loaded from `roles.json` at open.
///
/// `Some(roles)` — loaded successfully (may be empty when no roles are defined).
/// `None` — `roles.json` was present but corrupt; `mask_for_role` returns
/// `Err` for any request (fail-loud, never silently grant empty visibility).
roles: Option<Vec<RoleDef>>,
/// Memo for [`mask_for_role`](GraphDb::mask_for_role), keyed by
/// `(role, commit_seq)` — a scoped reader between two writes resolves once.
///
/// Shared by `Arc` with every [`ReaderSnapshot`](crate::reader::ReaderSnapshot)
/// taken from this handle. Replaced (not cleared) whenever the role
/// definitions change or the store is reloaded, which `commit_seq` does not
/// record; see [`RoleMaskCache`](crate::mask::RoleMaskCache).
role_masks: Arc<crate::mask::RoleMaskCache>,
/// Live subscriptions. Entries with a dead `Weak` are pruned on the next
/// distribute_events call.
subscriptions: Vec<SubEntry>,
/// Live query subscriptions. Re-executed on every commit when non-empty.
/// Dead `Weak` entries are pruned inside `distribute_events`.
query_subscriptions: Vec<QuerySubEntry>,
/// Queue capacity for new subscriptions created by this db. Default is
/// [`DEFAULT_SUB_CAPACITY`]; can be overridden via [`set_sub_capacity`]
/// to test Lagged behaviour with small queues.
sub_capacity: usize,
/// True for as-of instances opened via [`GraphDb::open_at`].
/// Every mutation method and `snapshot()` returns [`GraphError::ReadOnly`]
/// when this flag is set.
read_only: bool,
/// Total WAL commit count at the time [`open_at`] was called.
/// 0 for normal (non-as-of) instances.
total_wal_commits: u64,
/// Immutable mmap-backed base snapshot (V8). When `Some`, `self.topo` is
/// the WAL-replay overlay (empty at open time, populated by apply()) and
/// reads go through a merged `TopologyView`. `self.props` is always
/// fully materialized (base + WAL replay) for HNSW/IVF and view compat.
base: Option<Arc<core_storage::v8::MappedBase>>,
// ── MVCC epoch reader state ───────────────────────────────────────────────
/// Most-recent full overlay clone. Initialized at end of `open_with` /
/// `open_at_with`; refreshed every `FOLD_EVERY_K` commits.
/// `None` only between struct creation and the first fold.
fold_overlay: Option<Arc<crate::reader::FrozenOverlay>>,
/// Per-commit deltas accumulated since the last fold.
delta_tail: Vec<Arc<crate::reader::CommitDelta>>,
/// How many commits have occurred since the last fold.
commits_since_fold: usize,
/// When true, `log_then_apply_with` buffers event notifications instead of
/// firing them immediately. Used by the group-commit drain thread to defer
/// events until after the group fsync (R2: durability before notification).
/// Cleared to false once the drain thread flushes or discards the buffer.
defer_events: bool,
/// Buffered events accumulated while `defer_events` is true.
deferred_events: Vec<DeferredEvent>,
/// Set to true by the group-commit drain thread when a group fsync fails
/// after WAL truncation. All subsequent mutation attempts return an IO
/// error until the database is reopened.
degraded: bool,
/// Set to `true` after `ensure_v8_base_sections_loaded` has read provenance,
/// HNSW, and IVF sections from the mmap base into the engine's retained
/// fields. `false` on all opens until first use; always `true` for non-V8
/// opens (base is None, fast-path sets flag immediately).
v8_sections_loaded: std::sync::atomic::AtomicBool,
/// Serializes the one-time section population in `ensure_v8_base_sections_loaded`.
v8_sections_mutex: std::sync::Mutex<()>,
/// Per-node last-change commit sequence. `last_change[node_id] = seq` means
/// the node was last modified by commit `seq`.
///
/// Loaded from V8 section 11 at open; updated on every state-changing commit
/// and WAL replay frame. V5-V7 stores start with an empty map; pre-WAL-horizon
/// nodes return `None` from `last_changed` until they are next mutated.
///
/// See [`Precondition`] for the full touch definition.
last_change: HashMap<u32, u64>,
/// WAL archive retention policy set by [`set_wal_archive_retention`].
/// `None` = unlimited (keep all archives); `Some(N)` = keep N newest archives,
/// pruning older ones at snapshot time. 0 is treated as unlimited.
wal_archive_retention: Option<u32>,
/// Global frame index of the first commit that is still reachable through
/// surviving archives. Persisted to `wal.floor` sidecar when pruning occurs.
/// Default 0 = all history reachable.
wal_horizon_floor: u64,
/// True when the surviving archive chain forms a continuous WAL history
/// starting from the store's first commit (the genesis chain).
///
/// `open_at` may replay archive-resident commits from empty state only when
/// this flag is true AND `wal_horizon_floor == 0`. Cleared whenever:
/// - a WAL-truncating snapshot (`keep_wal=false`) is taken after archives
/// already exist (breaks the chain for subsequent archives), or
/// - any archive is pruned (floor advances past zero).
///
/// Persisted via the `wal.genesis` marker file; loaded from it at open.
archive_genesis_chain: bool,
/// Transient write-authz context set by `write_batch_authz` /
/// `query_write_authz` for the duration of ONE mutation call.
/// Always `None` at rest. Never serialized, never WAL-replayed.
pending_write_authz: Option<WriteAuthz>,
/// Slow-query threshold in milliseconds. 0 = disabled.
/// Seeded from `MUSHROOMDB_SLOW_QUERY_MS` at open; override via
/// [`GraphDb::set_slow_query_threshold_ms`] (tests must use the setter
/// — env vars are process-global and race parallel test threads).
slow_query_threshold_ms: u64,
/// Ring buffer of recent slow queries (interior-mutable so `query(&self)`
/// can record entries without requiring `&mut self`).
slow_queries: std::sync::Mutex<SlowQueryLog>,
/// Instant at which the database was opened (used by `/metrics` uptime).
started_at: std::time::Instant,
// ── Multi-process state (cross-process lock + WAL tailing) ────────────────
/// Byte offset of the WAL prefix already applied to in-memory state.
///
/// Advanced by exactly the encoded length of every frame this handle
/// appends, and by the decoded byte count of every tail
/// [`refresh`](GraphDb::refresh) absorbs. Rewound by
/// [`set_wal_consumed`](GraphDb::set_wal_consumed) when the group-commit
/// drain thread truncates a failed group. Compared against the WAL's
/// on-disk length to decide staleness.
wal_consumed: u64,
/// Identity of the snapshot this handle's base state came from, as
/// `(len, mtime_nanos)`. A different value means another process replaced
/// the snapshot and the WAL no longer continues our state: refresh reloads.
snapshot_ident: Option<(u64, u64)>,
/// The options this handle was opened with. Replayed verbatim when
/// `refresh` has to rebuild from disk.
open_opts: OpenOptions,
/// True when this handle holds the cross-process write lock for its whole
/// lifetime (a plain read-write open). Per-write lock acquisition is a
/// no-op on such a handle, and never releases the lock.
holds_lifetime_lock: bool,
/// True between a failed lock acquisition and the end of the write scope
/// that failed. Makes every WAL-appending mutation in that scope return
/// [`GraphError::Busy`] instead of writing.
lock_denied: bool,
/// True for an as-of view opened via [`GraphDb::open_at`]. Such a view is
/// pinned to one commit, so it is never stale and never refreshes — later
/// commits by any process are deliberately invisible to it.
pinned: bool,
}
/// One group of deferred event notifications, held until the group fsync
/// completes. Replayed by [`GraphDb::flush_deferred_events`].
struct DeferredEvent {
rec: core_storage::WalRecord,
engine_deltas: Vec<EngineEdgeDelta>,
seq: u64,
ingest: Option<(String, usize)>,
}
/// Options for [`GraphDb::open_with_options`].
#[derive(Clone, Copy, Debug)]
pub struct OpenOptions {
/// Rewrite an old-format snapshot to the current VERSION after a
/// successful load (default `true`). The old snapshot is kept as
/// `snapshot.bin.bak` until the next clean open at the current version,
/// at which point the `.bak` is deleted.
///
/// Set to `false` to open a store without touching any on-disk files
/// (useful for read-only inspection of a store at an older format).
pub auto_migrate: bool,
/// Write the valid WAL prefix back over a torn tail on open (default
/// `true`). Truncating a genuinely torn tail is correct crash recovery.
///
/// Set to `false` for an unattended reader. The valid prefix is still
/// decoded and replayed in memory, but nothing is written: a reader that
/// opens while another process is mid-append would otherwise discard a
/// frame that writer believes durable. `mushroomdb recall`, which runs on
/// every prompt, passes `false` for exactly this reason.
pub repair_wal: bool,
/// Open without ever writing to the store (default `false`).
///
/// A read-only handle:
/// - returns [`GraphError::ReadOnly`] from every mutation and from
/// `snapshot()`;
/// - performs no disk write at open — no WAL repair write-back and no
/// auto-migration rewrite, whatever the other two flags say;
/// - never takes the cross-process write lock, so it opens immediately even
/// while another process is writing, and never makes a writer wait.
///
/// [`refresh`](GraphDb::refresh) and [`is_stale`](GraphDb::is_stale) work
/// normally, so a read-only handle can follow another process's commits.
pub read_only: bool,
}
impl Default for OpenOptions {
fn default() -> Self {
Self {
auto_migrate: true,
repair_wal: true,
read_only: false,
}
}
}
/// How long a writer polls for the cross-process write lock before giving up
/// with [`GraphError::Busy`].
///
/// Long enough to ride out another process's commit (a batch apply plus one
/// fsync), short enough that a stuck peer surfaces as an error rather than a
/// hang.
pub const WRITE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
/// Refusal when a `MERGE` create cannot choose a namespace.
///
/// A role bound to two or more namespaces cannot have its create arm land in
/// `default`, and the statement did not name `ns`. The role must name one.
pub const MERGE_CREATE_NEEDS_ONE_NAMESPACE: &str =
"role-bound token: MERGE create requires the role to name one namespace";
/// Interval between poll attempts while waiting for the cross-process lock.
pub(crate) const LOCK_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
/// Why `load_from_disk` is running, which decides whether it may repair.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LoadOrigin {
/// A fresh open. Crash recovery is this handle's job: a torn WAL tail is
/// the signature of a crash and truncating it is correct, and archives
/// orphaned by an interrupted prune can be swept.
Open,
/// A reload driven by [`GraphDb::refresh`], because another process
/// replaced the snapshot. Nothing here is crash recovery — the store is
/// live and someone else is writing it — so this origin writes nothing.
Reload,
}
/// Authorization context carried by `write_batch_authz` / `query_write_authz`.
///
/// `None` at the call site = full authority (today's zero-cost behavior).
/// `Some(WriteAuthz)` = role-scoped: the decision table (plan §"authz decision
/// table") is evaluated per-op inside `commit_logged_batch` BEFORE any WAL
/// record is built. A denial returns an error with no WAL frame written.
///
/// The mask is ALWAYS `Omit`-mode: role-token paths must never acknowledge
/// hidden-node existence to callers.
#[derive(Clone, Debug)]
pub struct WriteAuthz {
pub role: String,
pub scope: WriteScope,
/// Resolved by `mask_for_role` under the same write guard as the mutation.
/// Always `Omit`-mode — never `Stub`.
pub mask: crate::mask::NodeMask,
}
/// Write `bytes` to `snapshot.bin.bak` atomically with full fsync.
///
/// Uses [`RealFs::write_atomic`] which applies `F_FULLFSYNC` on macOS and
/// `sync_all` on other platforms, then renames the `.tmp` file into place and
/// syncs the directory entry. This is the only correct path for writing the
/// `.bak` — plain `std::fs::write + sync_all` misses both `F_FULLFSYNC` and
/// the directory sync.
pub fn write_snapshot_bak(dir: &std::path::Path, bytes: &[u8]) -> crate::Result<()> {
use core_storage::fs::{FileId, Fs as _};
RealFs::new(dir)
.map_err(core_storage::GraphError::Io)?
.write_atomic(FileId::SnapshotBak, bytes)
.map_err(core_storage::GraphError::Io)
}
/// Return the on-disk snapshot format version without decoding the full snapshot.
///
/// Reads only the 6-byte header (magic + version LE). Returns `None` when no
/// snapshot file exists (WAL-only store). Returns an error if the header is
/// malformed.
pub fn snapshot_version_at(dir: &std::path::Path) -> crate::Result<Option<u16>> {
use std::io::Read as _;
let path = dir.join("snapshot.bin");
let mut header = [0u8; 6];
let n = match std::fs::File::open(&path) {
Ok(mut f) => f.read(&mut header).map_err(core_storage::GraphError::Io)?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(core_storage::GraphError::Io(e)),
};
core_storage::snapshot::peek_version(&header[..n])
}
/// Options for [`GraphDb::snapshot_with`].
#[derive(Debug, Clone, Default)]
pub struct SnapshotOptions {
/// When `true`, the WAL is preserved after the snapshot write.
/// Pre-snapshot commits remain reachable via [`GraphDb::open_at`].
/// When `false` (the default), the WAL is truncated to a minimal
/// baseline so cold-start replay stays fast.
pub keep_wal: bool,
/// When `true`, the current WAL is renamed to `wal.<commit_seq>.archive`
/// before a fresh WAL baseline is written (history-preserving snapshot).
///
/// This is the feature opt-in: `false` (the default) leaves the existing
/// truncation / keep-wal behaviour byte-identical. `archive_wal` takes
/// precedence over `keep_wal` when both are set.
///
/// Archives can be scanned by [`GraphDb::node_history`],
/// [`GraphDb::edge_history`], [`GraphDb::was_linked`], and
/// [`GraphDb::open_at`], extending the reachable history horizon across
/// snapshot boundaries.
pub archive_wal: bool,
}
/// Derive the scan-label sym for the commit-skip fast-path.
///
/// Walks `ops` to find the plan's leading scan op (`ScanLabel`, `IndexScan`,
/// or `IndexIntersect`) with a concrete label string, then interns it.
///
/// Returns `None` in all cases where skipping is unsafe:
/// - Any `Expand` op is present (edge traversal; edges change results regardless
/// of node labels).
/// - The leading scan has no label (`ScanLabel { label: None }` — full scan).
/// - No recognizable leading scan op is found.
///
/// This is the conservative v0.4.3 boundary. The caller stores the result in
/// [`QuerySubEntry::scan_label`] at subscribe time; `None` means always execute.
fn extract_scan_label(ops: &[PlanOp], syms: &mut Interner) -> Option<u32> {
// Any Expand → must always re-execute (edges can change join results).
if ops.iter().any(|op| matches!(op, PlanOp::Expand { .. })) {
return None;
}
for op in ops {
match op {
PlanOp::ScanLabel {
label: Some(label), ..
} => return Some(syms.intern(label)),
PlanOp::IndexScan {
label: Some(label), ..
} => return Some(syms.intern(label)),
PlanOp::IndexIntersect {
label: Some(label), ..
} => return Some(syms.intern(label)),
_ => {}
}
}
None
}
/// How an as-of read is restricted — the argument to
/// [`GraphDb::query_at_scoped`].
///
/// Every variant is resolved against the graph **as it was at the requested
/// commit**, not against the current graph.
#[derive(Debug, Clone, Copy)]
pub enum AsOfScope<'a> {
/// Everything the named role may see. The role *definition* is the current
/// one — `roles.json` is a sidecar and has no past version — but its
/// `keys` and `labels` are resolved against the as-of graph.
Role(&'a str),
/// An explicit node-key allow-list. Keys that did not exist at that commit
/// resolve to nothing.
Keys(&'a [String]),
/// A role intersected with a client-supplied allow-list. The intersection
/// is the never-widen rule: a client mask can only narrow a role.
RoleAndKeys(&'a str, &'a [String]),
/// Every live node in one namespace, as the graph was at that commit.
///
/// A namespace cannot change — it is set at insert and immutable — so the
/// answer is simply "the nodes that existed then and are in this
/// namespace". A name no node uses resolves to nothing, never to
/// everything.
Namespace(&'a str),
}
impl GraphDb<RealFs> {
/// Open the database at `dir` with default options.
///
/// Equivalent to `open_with_options(dir, OpenOptions::default())`.
/// Old-format snapshots (V5, V6) are automatically migrated to the
/// current version on a successful load (see [`OpenOptions::auto_migrate`]).
pub fn open(dir: &std::path::Path) -> Result<Self> {
Self::open_with_options(dir, OpenOptions::default())
}
/// Open the database at `dir` with explicit options.
///
/// When `opts.auto_migrate` is `true` (the default) and the on-disk
/// snapshot is an older format version, this function:
/// 1. Copies the current `snapshot.bin` to `snapshot.bin.bak` (atomic
/// + fsynced) before any modification.
/// 2. Rewrites `snapshot.bin` at the current format version via
/// [`GraphDb::snapshot_with`] with `keep_wal: true` (WAL preserved).
///
/// If migration fails the error is returned and the original files are
/// intact (the `.bak` was written before the new snapshot was attempted).
///
/// A clean open that finds the snapshot already at the current version
/// deletes any leftover `.bak` file.
///
/// WAL-only stores (no snapshot) are never auto-migrated on open.
///
/// `opts.repair_wal` controls the other write this function can make; see
/// [`OpenOptions::repair_wal`]. With both flags `false` the open touches
/// no file on disk.
pub fn open_with_options(dir: &std::path::Path, opts: OpenOptions) -> Result<Self> {
Self::open_dir(dir, opts, true)
}
/// Open without taking the cross-process write lock for the handle's
/// lifetime.
///
/// Only [`SharedDb`](crate::SharedDb) uses this: a long-lived server holds
/// its handle open indefinitely, so it takes the lock per write instead of
/// keeping every other process out of the store for as long as it runs.
pub(crate) fn open_unlocked(dir: &std::path::Path) -> Result<Self> {
Self::open_dir(dir, OpenOptions::default(), false)
}
fn open_dir(dir: &std::path::Path, opts: OpenOptions, hold_lock: bool) -> Result<Self> {
// Header-only peek — 6 bytes, no full decode.
let snap_version = snapshot_version_at(dir)?;
// Full load: decode snapshot + replay WAL + rebuild indexes.
let mut db = Self::open_generic(RealFs::new(dir)?, opts, hold_lock)?;
// A read-only handle writes nothing at open, so it never migrates —
// the old-format snapshot is loaded and left exactly as it is.
if opts.auto_migrate && !opts.read_only {
match snap_version {
Some(ver) if ver < core_storage::snapshot::VERSION => {
let _tm = std::time::Instant::now();
// Copy the original snapshot to .bak at OS level — no in-memory
// buffer required for a 2+ GiB file.
//
// Crash-safety: snapshot.bin remains intact (write_atomic inside
// snapshot_with uses a .tmp+rename) until the V8 write succeeds.
// A torn .bak on crash is acceptable because the original
// snapshot.bin is the authoritative source until after the rename.
std::fs::copy(dir.join("snapshot.bin"), dir.join("snapshot.bin.bak"))
.map_err(core_storage::GraphError::Io)?;
trace_migrate!("bak copy done", _tm);
// Rewrite snapshot at current version; keep WAL intact.
db.snapshot_with(SnapshotOptions {
keep_wal: true,
..SnapshotOptions::default()
})?;
trace_migrate!("snapshot_with done", _tm);
}
Some(_) => {
// Already current version: remove any leftover .bak.
let bak = dir.join("snapshot.bin.bak");
if bak.exists() {
std::fs::remove_file(&bak).map_err(core_storage::GraphError::Io)?;
}
}
None => {
// WAL-only store — nothing to migrate on open.
}
}
}
Ok(db)
}
/// Open a read-only view of the database as it existed after `commit`.
///
/// Commit indices are 0-based over the current WAL: commit 0 is the state
/// after the first WAL frame, commit N-1 is the state after the N-th (most
/// recent) frame. Call [`GraphDb::open`] to read the full current state.
///
/// **Replay base.** [`GraphDb::snapshot`] truncates the WAL when it runs,
/// so as-of can only reach commits recorded in the current WAL (those
/// written after the most recent snapshot, or all commits if no snapshot
/// was ever taken). Commit 0 in `open_at` always refers to the first
/// frame in the WAL that exists on disk, not the first ever write to the
/// database. When the on-disk snapshot recorded that it truncated the
/// WAL (V7, default `keep_wal: false`), it is loaded as the base state
/// before frame replay, so the as-of view includes all pre-snapshot data.
/// Snapshots written with `keep_wal: true` (and legacy V5/V6 snapshots)
/// are ignored and replay is WAL-only, as before.
///
/// **Read-only.** Every mutation method and `snapshot()` on the returned
/// instance returns [`GraphError::ReadOnly`]. Queries, `explain()`, and
/// `stats()` work normally.
///
/// # Errors
/// - [`GraphError::CommitOutOfRange`] if `commit >= wal_commit_count` (including
/// when the WAL is empty after a snapshot).
pub fn open_at(dir: &std::path::Path, commit: u64) -> Result<Self> {
Self::open_at_with(RealFs::new(dir)?, commit)
}
/// Run a **read-only** Cypher query against the graph as it existed at
/// `commit` — the "time-travel" / agent-replay query. Opens a temporal view
/// of this store's directory at that commit and executes the read there.
///
/// The current instance is unaffected. Write statements are rejected (the
/// temporal view is read-only). `commit` is a 0-based WAL commit index;
/// `commit == wal_commit_count` (or `open_at`'s range) yields the newest
/// state. Prefer this over holding many historical instances open.
///
/// # Errors
/// - [`GraphError::CommitOutOfRange`] if `commit` is past the WAL horizon.
/// - A query error for a malformed or write query.
pub fn query_at(
&self,
commit: u64,
cypher: &str,
params: &std::collections::BTreeMap<String, Value>,
) -> Result<ResultSet> {
let temporal = self.open_at_for_read(commit, cypher)?;
temporal.query(cypher, params)
}
/// Run a **read-only** Cypher query at `commit`, restricted by `scope`.
///
/// The **graph** is as of `commit`; the **role definition** is as it is
/// now, because `roles.json` is a sidecar and is never a WAL record — it
/// has no past version to read. A role's `keys` and `labels` are resolved
/// against the commit-`commit` graph, so a role that may see a label sees
/// exactly the nodes that carried it then, and an explicit key that did
/// not exist yet resolves to nothing.
///
/// [`AsOfScope::RoleAndKeys`] intersects the two: a client allow-list can
/// only narrow what a role may see, never widen it.
///
/// Write statements are rejected, exactly as [`GraphDb::query_at`] rejects
/// them.
///
/// # Errors
/// - [`GraphError::CommitOutOfRange`] if `commit` is outside the retained
/// range; the error carries that range.
/// - [`GraphError::KeyNotFound`] with a `role:` prefix for an unknown role,
/// or [`GraphError::Corrupt`] when `roles.json` was corrupt at open.
/// - A query error for a malformed or write query.
pub fn query_at_scoped(
&self,
commit: u64,
cypher: &str,
params: &std::collections::BTreeMap<String, Value>,
scope: AsOfScope<'_>,
) -> Result<ResultSet> {
let temporal = self.open_at_for_read(commit, cypher)?;
let mask = temporal.mask_at_scope(scope)?;
temporal.query_masked(cypher, params, &mask)
}
/// As [`GraphDb::query_at_scoped`], with `namespace` intersected into
/// whatever `scope` resolves to.
///
/// This is what a surface needs when a caller passes `namespace` beside a
/// `role` or a client mask on a time-travel read: [`AsOfScope`] names one
/// restriction, and the namespace is a second one that composes with it
/// rather than replacing it. The intersection is the never-widen rule — a
/// namespace can only narrow what the scope already allows — and both legs
/// are resolved against the graph as it was at `commit`.
///
/// `AsOfScope::Namespace(ns)` is still the way to ask for a namespace alone.
pub fn query_at_scoped_in_namespace(
&self,
commit: u64,
cypher: &str,
params: &std::collections::BTreeMap<String, Value>,
scope: AsOfScope<'_>,
namespace: &str,
) -> Result<ResultSet> {
let temporal = self.open_at_for_read(commit, cypher)?;
let mask = temporal
.mask_at_scope(scope)?
.intersect(&temporal.mask_for_namespace(namespace));
temporal.query_masked(cypher, params, &mask)
}
/// Open the temporal view for a time-travel read and refuse write Cypher.
///
/// Shared by [`GraphDb::query_at`] and [`GraphDb::query_at_scoped`] so both
/// resolve the commit and reject writes identically.
fn open_at_for_read(&self, commit: u64, cypher: &str) -> Result<Self> {
let dir = self.fs.dir().to_path_buf();
let temporal = Self::open_at(&dir, commit)?;
if is_write_tokens(&lex(cypher).map_err(|e| GraphError::QueryError {
detail: format!("lex: {e}"),
})?) {
return Err(GraphError::QueryError {
detail: "query_at is read-only: write statements are not permitted in a \
time-travel query"
.into(),
});
}
Ok(temporal)
}
}
impl<F: Fs> GraphDb<F> {
/// Open over an arbitrary [`Fs`], repairing a torn WAL tail as usual.
pub fn open_with(fs: F) -> Result<Self> {
Self::open_with_repair(fs, true)
}
/// As [`GraphDb::open_with`], but `repair_wal: false` decodes the valid WAL
/// prefix without writing the truncation back. See
/// [`OpenOptions::repair_wal`].
pub fn open_with_repair(fs: F, repair_wal: bool) -> Result<Self> {
Self::open_generic(
fs,
OpenOptions {
repair_wal,
..OpenOptions::default()
},
true,
)
}
/// Shared open path.
///
/// `hold_lock` requests the cross-process write lock for the whole handle
/// lifetime — the right behaviour for a plain read-write `GraphDb`, whose
/// owner writes through it directly. [`SharedDb`](crate::SharedDb) passes
/// `false` and takes the lock per write instead, so that a long-lived
/// server does not keep every other process out of the store.
///
/// A read-only open never takes the lock regardless of `hold_lock`.
fn open_generic(fs: F, opts: OpenOptions, hold_lock: bool) -> Result<Self> {
let mut db = Self::new_empty(fs, opts);
db.read_only = opts.read_only;
if hold_lock && !opts.read_only {
if !db.poll_lock(WRITE_LOCK_WAIT)? {
return Err(GraphError::Busy { holder: None });
}
db.holds_lifetime_lock = true;
}
db.load_from_disk(LoadOrigin::Open)?;
Ok(db)
}
/// A handle with no state loaded: every field at its empty value, the
/// filesystem and options in place. Only [`load_from_disk`] makes it
/// usable.
fn new_empty(fs: F, opts: OpenOptions) -> Self {
Self {
fs,
ids: IdMap::new(),
syms: Interner::new(),
topo: Topology::new(),
props: ColumnStore::new(),
labels: Vec::new(),
ns_names: vec![NS_DEFAULT.to_string()],
node_ns: Vec::new(),
edge_props: EdgeProps::new(),
engine: RuleEngine::new(),
view_store: ViewStore::new(),
fulltext: FulltextIndex::new(),
prop_index: PropertyIndex::new(),
event_sink: None,
fsync: FsyncPolicy::Strict,
commit_seq: 0,
roles: Some(vec![]),
role_masks: Arc::new(crate::mask::RoleMaskCache::new()),
subscriptions: Vec::new(),
query_subscriptions: Vec::new(),
sub_capacity: DEFAULT_SUB_CAPACITY,
read_only: false,
total_wal_commits: 0,
base: None,
fold_overlay: None,
delta_tail: Vec::new(),
commits_since_fold: 0,
defer_events: false,
deferred_events: Vec::new(),
degraded: false,
v8_sections_loaded: std::sync::atomic::AtomicBool::new(false),
v8_sections_mutex: std::sync::Mutex::new(()),
last_change: HashMap::new(),
wal_archive_retention: None,
wal_horizon_floor: 0,
archive_genesis_chain: false,
pending_write_authz: None,
slow_query_threshold_ms: std::env::var("MUSHROOMDB_SLOW_QUERY_MS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(100),
slow_queries: std::sync::Mutex::new(SlowQueryLog {
entries: std::collections::VecDeque::new(),
total: 0,
}),
started_at: std::time::Instant::now(),
wal_consumed: 0,
snapshot_ident: None,
open_opts: opts,
holds_lifetime_lock: false,
lock_denied: false,
pinned: false,
}
}
/// Return every field describing stored graph state to its empty value,
/// leaving this handle's own identity alone.
///
/// Preserved on purpose: the filesystem, open options, lock ownership, the
/// event sink and subscriptions, fsync policy, degraded flag, and the
/// slow-query configuration and log. A caller that registered a sink or a
/// subscription keeps it across a reload.
fn reset_for_reload(&mut self) {
self.ids = IdMap::new();
self.syms = Interner::new();
self.topo = Topology::new();
self.props = ColumnStore::new();
self.labels = Vec::new();
self.ns_names = vec![NS_DEFAULT.to_string()];
self.node_ns = Vec::new();
self.edge_props = EdgeProps::new();
self.engine = RuleEngine::new();
self.view_store = ViewStore::new();
self.fulltext = FulltextIndex::new();
self.prop_index = PropertyIndex::new();
self.commit_seq = 0;
self.roles = Some(vec![]);
// A fresh cache, not a cleared one: any reader snapshot still holding
// the old `Arc` keeps it to itself, so nothing it memoised against the
// pre-reload store can be read back through this handle.
self.role_masks = Arc::new(crate::mask::RoleMaskCache::new());
self.total_wal_commits = 0;
self.base = None;
self.fold_overlay = None;
self.delta_tail = Vec::new();
self.commits_since_fold = 0;
self.deferred_events = Vec::new();
self.v8_sections_loaded
.store(false, std::sync::atomic::Ordering::Release);
self.last_change = HashMap::new();
self.wal_horizon_floor = 0;
self.archive_genesis_chain = false;
self.pending_write_authz = None;
self.wal_consumed = 0;
self.snapshot_ident = None;
}
/// Load the snapshot base and replay the WAL into an empty handle — the
/// whole of what opening a store does after the struct exists.
///
/// Split out of the open path so that [`refresh`](GraphDb::refresh) can
/// rebuild a handle in place, without ownership of `F`, when another
/// process replaces the snapshot underneath it.
///
/// `origin` decides whether the two repair writes this function can make
/// are appropriate; see [`LoadOrigin`].
fn load_from_disk(&mut self, origin: LoadOrigin) -> Result<usize> {
// Both writes below are crash recovery, and only an open is entitled to
// perform them. A read-only handle promises to touch nothing, and a
// reload driven by `refresh` is looking at a store another process is
// actively writing: what looks like a torn tail there is a peer
// mid-append, and what looks like an orphaned archive may be one that
// peer is about to reference.
let may_repair = origin == LoadOrigin::Open && !self.open_opts.read_only;
let repair_wal = self.open_opts.repair_wal && may_repair;
let db = self;
db.wal_horizon_floor = db.fs.read_horizon_floor()?;
db.archive_genesis_chain = db.fs.has_genesis_marker();
// Opening cleanup: remove orphaned archives — archives whose frames all
// fall below the horizon floor. Orphans arise when a crash interrupted
// the retention-prune sequence after the floor was written but before
// all surplus archives were deleted. Safe to delete: floor already
// accounts for their frames.
if may_repair {
db.cleanup_orphaned_archives()?;
}
let _t0 = std::time::Instant::now();
// Peek 6 bytes to determine snapshot version without reading the full
// file. For RealFs this is a true partial read (O(1)); for SimFs the
// default impl reads all bytes and truncates (still correct).
let snap_header = db.fs.read_prefix(FileId::Snapshot, 6)?;
// V8 and V9 share the mmap-able container; V9 only adds section 12.
let is_v8 = snap_header.len() >= 6
&& &snap_header[0..4] == b"GDB1"
&& matches!(
u16::from_le_bytes([snap_header[4], snap_header[5]]),
core_storage::snapshot::VERSION_8 | core_storage::snapshot::VERSION_9
);
if is_v8 {
// V8: map the file zero-copy (RealFs) or read full bytes (SimFs).
// No 2.4GB heap Vec is allocated on RealFs.
let mapped = Arc::new(
if let Some(snap_path) = db.fs.snapshot_path() {
core_storage::v8::MappedBase::map(&snap_path)
} else {
let snap_bytes = db.fs.read(FileId::Snapshot)?;
core_storage::v8::MappedBase::from_bytes(snap_bytes)
}
.map_err(|e| GraphError::Corrupt {
detail: format!("v8: mmap open: {e:?}"),
})?,
);
db.restore_v8_base(Arc::clone(&mapped))?;
trace_open!("restore_v8_base", _t0);
db.base = Some(mapped);
trace_open!("base assigned", _t0);
} else if !snap_header.is_empty() {
// Legacy V5-V7: full read required for decode.
let snap_bytes = db.fs.read(FileId::Snapshot)?;
if let Some(state) = core_storage::snapshot::decode(&snap_bytes)? {
db.restore_snapshot_state(state)?;
}
}
// else: snap_header is empty = no snapshot file, fresh store.
//
// Seed commit_seq from the highest seq persisted in last_change so that
// WAL-replay frames (which start at commit_seq+1) always exceed any seq
// already stored in the snapshot. Without this, a db with one snapshot
// commit would save last_change["a"]=1, then on reopen the first WAL
// frame would replay at seq=1 again — colliding and making WAL-tail
// mutations indistinguishable from the snapshot baseline.
//
// Safety invariant (seq-recycling):
// Recycled seqs (those below the seeded baseline) were NEVER stored in
// last_change because they belonged to a previous db lifetime — a new
// db starts at commit_seq=0 with an empty last_change. Therefore no
// CAS precondition can carry a recycled seq as its `expected` value
// and accidentally match a live node's last_change entry.
//
// `expected:0` on a deleted-then-reinserted node:
// After deletion, last_changed() returns None; callers that call
// last_changed() and then use NodeUnchangedSince get None.unwrap_or(0)
// = 0. The reinserted node gets seq > 0, so a subsequent CAS with
// expected=0 correctly conflicts. The only way to observe actual=0 in
// a CasConflict would be a caller that invented expected=0 without ever
// calling last_changed() — unreachable via the documented API contract.
if let Some(&max_seq) = db.last_change.values().max() {
db.commit_seq = db.commit_seq.max(max_seq);
}
let bytes = db.fs.read(FileId::Wal)?;
let (records, valid_len) = decode_all(&bytes);
// The valid prefix is replayed either way; `repair_wal` only decides
// whether the truncation is written back. A reader that races a live
// appender must not persist a truncation the writer never asked for.
if valid_len < bytes.len() && repair_wal {
db.fs.write_atomic(FileId::Wal, &bytes[..valid_len])?;
}
// WAL-present path: build indexes eagerly BEFORE replay so that the
// first replayed record does not trigger the lazy-init guard (which
// would call reindex_all_load_state on an empty graph, defeating the
// point of restoring IVF/HNSW blobs from the snapshot).
if !records.is_empty() {
db.ensure_v8_base_sections_loaded();
trace_open!("lazy sections loaded (WAL path)", _t0);
}
let replayed = db.apply_frames(records)?;
// The cursor sits at the end of the valid prefix, not the end of the
// file: a torn or still-being-written tail is unconsumed by definition
// and stays visible to `is_stale` until it decodes.
db.wal_consumed = valid_len as u64;
db.snapshot_ident = db.fs.snapshot_ident().map_err(GraphError::Io)?;
trace_open!("wal replay done", _t0);
// Rebuild view values after WAL replay only when there is no V8 base.
// With a V8 base, view values are correct in the snapshot and are updated
// incrementally during WAL replay (on_edge_changed / on_prop_changed).
// A full rebuild would read overlay-only props (empty after restore_v8_base)
// and overwrite correct base values with wrong results (e.g. NeighborAgg
// Sum reads no "score" in overlay → writes 0.0, shadowing the correct
// base value).
if db.base.is_none() {
let topo_view = TopologyView::owned(&db.topo);
db.view_store
.rebuild_all(&mut db.props, &topo_view, &db.ids, &db.syms, &db.labels);
}
// Rebuild full-text index after WAL replay. Corrects drift from
// per-record incremental apply during replay.
db.fulltext.rebuild_all(
&db.ids,
&db.labels,
&db.syms,
build_props_view(&db.props, &db.base),
);
db.prop_index.rebuild_all(
&db.ids,
&db.labels,
&db.syms,
build_props_view(&db.props, &db.base),
);
// Namespaces: one pass over the `ns` column, after the snapshot is
// restored and the WAL replayed. Replay maintains `node_ns` record by
// record as well; this pass is what makes a snapshot-only open right,
// and it reads nothing on a store with no `ns` column.
db.rebuild_node_ns();
// A mid-build snapshot's HNSW blob carries `complete == false`.
// Register it so `serve`'s ticker sees work without waiting for a write.
db.register_outstanding_index_builds();
// Load roles sidecar. Missing file = no roles (Some(vec![])).
// Corrupt/unparseable = poisoned (None); mask_for_role will fail-loud.
db.roles = Self::load_roles_from_fs(&db.fs)?;
// Capture the initial MVCC fold so reader() is ready immediately.
db.fold_now();
trace_open!("open_with complete", _t0);
Ok(replayed)
}
/// Apply decoded WAL frames to in-memory state, exactly as the open-path
/// replay does — same `apply` calls, same per-frame delta drain, same
/// commit-seq and last-change bookkeeping. Rules therefore fire and derived
/// edges appear identically whether a frame arrives at open, from a local
/// commit, or from another process by way of [`refresh`](GraphDb::refresh).
///
/// Returns the number of frames applied.
///
/// Deltas are drained and discarded per frame: replayed frames are already
/// reflected on disk, so they are not news to a subscriber, and draining
/// inside the loop keeps `pending_deltas` O(1) over a large WAL (I-2).
fn apply_frames(&mut self, records: Vec<WalRecord>) -> Result<usize> {
if records.is_empty() {
return Ok(0);
}
// Materialize any state retained in the mmap base before the first
// frame lands, so a replayed record cannot trip the lazy-init guard and
// rebuild indexes from an empty graph. Both calls are idempotent.
self.ensure_v8_base_sections_loaded();
self.engine.consume_retained_state_eager(
&self.ids,
&self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
);
let applied = records.len();
for rec in records {
self.apply(&rec)?;
let _ = self.engine.drain_deltas();
// Track commit_seq during replay so last_change entries are
// consistent with the seqs assigned by log_then_apply_with on
// subsequent live commits. After N replayed frames, commit_seq=N;
// live commits begin at N+1.
self.commit_seq += 1;
let replay_seq = self.commit_seq;
self.update_last_change_from_rec(&rec, replay_seq);
}
// Enforce I-2: if the per-frame drain above is ever removed or skipped,
// this assert catches the regression in debug builds immediately.
debug_assert_eq!(
self.engine.pending_delta_count(),
0,
"pending_deltas non-empty after replay — \
per-frame drain must run inside the loop to keep memory O(1)"
);
// T2 note: the per-frame drain IS the suppression seam for replay.
// Any future as-of replay path (Plan-15 T2) must drain here to feed
// replaying subscribers; the mechanism is already in place.
let _ = self.engine.drain_deltas(); // belt-and-braces no-op after loop drain
Ok(applied)
}
// ── Multi-process safety: cross-process write lock + WAL tailing ──────────
//
// mushroomdb is many-readers / one-writer across processes. Writers take an
// advisory exclusive lock on the store's `LOCK` file; readers never do.
// Every handle tracks how much of the WAL it has consumed, so it can pick
// up another process's commits by decoding only the new tail rather than
// reopening. See `docs/site/concurrency.md`.
/// Whether the store on disk has moved ahead of (or out from under) this
/// handle's in-memory state.
///
/// True when the WAL's length differs from this handle's cursor — another
/// process committed, or is mid-append — or when the snapshot file's
/// identity changed. Costs two metadata lookups and reads no file contents,
/// so it is cheap enough for a read path to call.
///
/// Always false for an as-of view from [`GraphDb::open_at`]: such a view is
/// pinned to one commit and later commits are deliberately invisible to it.
pub fn is_stale(&self) -> Result<bool> {
if self.pinned {
return Ok(false);
}
if self.fs.wal_len().map_err(GraphError::Io)? != self.wal_consumed {
return Ok(true);
}
Ok(self.fs.snapshot_ident().map_err(GraphError::Io)? != self.snapshot_ident)
}
/// Bring this handle up to date with every commit other processes have made,
/// and return how many frames were applied.
///
/// The WAL tail is decoded from this handle's cursor and applied through the
/// same path the open replay uses, so rules fire and derived edges appear
/// exactly as they would on a fresh open. Interners, id maps and indexes
/// stay valid for the same reason.
///
/// A frame another process is still writing is left alone: a trailing
/// partial frame is a wait, not a corruption, and the handle stays stale
/// until that frame is complete. Nothing is written to disk, so a read-only
/// handle can refresh freely.
///
/// When the snapshot file's identity changed, or the WAL is shorter than
/// this handle's cursor, the WAL no longer continues our state — another
/// process snapshotted or archived. The handle is then rebuilt from disk
/// with the options it was opened with, and the return value is the number
/// of frames in the new WAL.
///
/// Returns 0 for an as-of view, which never follows later commits.
///
/// # Errors
///
/// An error here leaves the handle **degraded**: it got partway through
/// applying the tail, or partway through a reload, so its in-memory state
/// no longer matches any point on disk. Further mutations are refused and
/// the handle must be reopened. Nothing on disk was damaged — the store
/// itself is fine, and a fresh open recovers it.
pub fn refresh(&mut self) -> Result<u64> {
if self.pinned {
return Ok(0);
}
let disk_ident = self.fs.snapshot_ident().map_err(GraphError::Io)?;
let wal_len = self.fs.wal_len().map_err(GraphError::Io)?;
if disk_ident != self.snapshot_ident || wal_len < self.wal_consumed {
// The WAL no longer continues our state: rebuild from disk. State
// is cleared first, so a failed load leaves an empty handle — mark
// it degraded rather than let a caller read an empty graph as if
// it were the store's contents.
self.reset_for_reload();
return match self.load_from_disk(LoadOrigin::Reload) {
Ok(frames) => Ok(frames as u64),
Err(e) => {
self.degraded = true;
Err(e)
}
};
}
if wal_len == self.wal_consumed {
return Ok(0);
}
let tail = self
.fs
.read_range(FileId::Wal, self.wal_consumed)
.map_err(GraphError::Io)?;
let (records, valid_len) = decode_all(&tail);
let applied = match self.apply_frames(records) {
Ok(n) => n,
Err(e) => {
// Some frames landed and some did not, and the cursor cannot
// say how many. Advancing it would skip the rest; leaving it
// would replay what already applied. Neither is recoverable in
// place, so refuse further writes and require a reopen.
self.degraded = true;
return Err(e);
}
};
// Advance by the bytes actually decoded, never by the file length: an
// incomplete trailing frame stays unconsumed for the next refresh.
self.wal_consumed += valid_len as u64;
if applied > 0 {
// Peer commits must reach `reader()` snapshots taken from here on.
// A full fold is what open does; refresh does not build per-commit
// deltas, so there is nothing cheaper that stays correct.
self.fold_now();
}
Ok(applied as u64)
}
/// Byte offset of the WAL prefix this handle has applied.
///
/// Exposed for tests that assert the cursor tracks appended bytes exactly.
#[doc(hidden)]
pub fn wal_consumed(&self) -> u64 {
self.wal_consumed
}
/// Rewind the WAL cursor after the group-commit drain thread truncated a
/// failed group off the tail, so the cursor still describes the file.
pub(crate) fn set_wal_consumed(&mut self, len: u64) {
self.wal_consumed = len;
}
/// One non-blocking attempt at the cross-process write lock.
///
/// Takes `&self` so a caller can poll for the lock *before* it acquires the
/// in-process write guard. That ordering is what keeps a busy peer in
/// another process from stalling this process's readers.
///
/// A handle that owns the lock for its lifetime always succeeds.
pub(crate) fn try_cross_process_lock(&self) -> Result<bool> {
if self.holds_lifetime_lock {
return Ok(true);
}
self.fs.try_lock_exclusive().map_err(GraphError::Io)
}
/// Poll for the cross-process write lock until `wait` elapses.
///
/// One attempt is always made, so a zero wait is a single try. Returns
/// `false` when the lock is still held elsewhere at the deadline; nothing
/// has been written and retrying later is safe.
///
/// Only the plain-`GraphDb` open path uses this, where the caller owns the
/// handle outright. [`SharedDb`](crate::SharedDb) polls
/// [`try_cross_process_lock`](GraphDb::try_cross_process_lock) itself so
/// that it holds no in-process guard while it waits.
fn poll_lock(&self, wait: std::time::Duration) -> Result<bool> {
let deadline = std::time::Instant::now() + wait;
loop {
if self.try_cross_process_lock()? {
return Ok(true);
}
let now = std::time::Instant::now();
if now >= deadline {
return Ok(false);
}
std::thread::sleep(LOCK_POLL_INTERVAL.min(deadline.saturating_duration_since(now)));
}
}
/// Open a cross-process write scope, given the outcome of an already-made
/// lock attempt.
///
/// The caller polls for the lock first — outside any in-process guard — and
/// passes what it got. On success this refreshes, so the writes about to
/// happen land on top of every other process's commits. On failure the
/// handle refuses WAL-appending mutations and `snapshot()` with
/// [`GraphError::Busy`] until [`end_write_lock`](GraphDb::end_write_lock)
/// closes the scope, so a caller holding a guard cannot write behind
/// another process's back.
///
/// A handle that already owns the lock for its lifetime skips the refresh:
/// no other process can have written, so there is nothing to pick up.
pub(crate) fn enter_write_scope(&mut self, acquired: bool) -> Result<()> {
self.lock_denied = !acquired;
if !acquired || self.holds_lifetime_lock {
return Ok(());
}
if let Err(e) = self.refresh() {
// Do not hold a lock we cannot use: release it and let the caller
// see the underlying failure.
let _ = self.fs.unlock();
self.lock_denied = true;
return Err(e);
}
Ok(())
}
/// Close a cross-process write scope opened by
/// [`enter_write_scope`](GraphDb::enter_write_scope): release the lock and
/// clear the Busy latch. Safe to call when the lock was never taken.
pub(crate) fn end_write_lock(&mut self) {
self.lock_denied = false;
if !self.holds_lifetime_lock {
// Releasing a lock we do not hold is a no-op; a failure to release
// is reported by the OS closing the descriptor at handle drop.
let _ = self.fs.unlock();
}
}
/// As-of replay for [`GraphDb::open_at`]: snapshot base (only when the
/// snapshot truncated the WAL) plus the first `commit + 1` WAL frames;
/// see [`GraphDb::open_at`] for the semantics. The per-frame drain
/// mirrors `open_with` exactly so pending_delta_count is 0 on exit.
/// Restore all persisted state from a decoded snapshot. Shared by
/// `open_with` and (when the snapshot truncated the WAL) `open_at_with`.
fn restore_snapshot_state(
&mut self,
state: core_storage::snapshot::SnapshotState,
) -> Result<()> {
self.ids = state.ids;
self.syms = state.syms;
self.topo = state.topo;
self.props = state.props;
self.labels = state.labels;
self.edge_props = state.edge_props;
// Cross-section label integrity for V5/V7 snapshots: same invariants as
// restore_v8_base. A crafted bincode snapshot with a short `labels` vec,
// out-of-range sym ids, or a sentinel label on a live node would otherwise
// open successfully and panic later in `NodeRef::label()` or
// `neighborhood_masked()`. Catching it here turns those into typed
// `GraphError::Corrupt` at open time.
{
let ids_len = self.ids.len();
if self.labels.len() != ids_len {
return Err(GraphError::Corrupt {
detail: format!(
"snapshot: labels vec has {} entries but id table has {} total slots",
self.labels.len(),
ids_len,
),
});
}
let syms_len = self.syms.len() as u32;
for (i, &sym) in self.labels.iter().enumerate() {
let is_tombstoned = self.ids.is_tombstoned(i as u32);
if sym == u32::MAX {
if !is_tombstoned {
return Err(GraphError::Corrupt {
detail: format!(
"snapshot: live node at id slot {i} has sentinel label (u32::MAX)"
),
});
}
} else if sym >= syms_len {
return Err(GraphError::Corrupt {
detail: format!(
"snapshot: label at id slot {i} references sym {sym} \
which is out of interner range ({syms_len})"
),
});
}
}
}
let defs: Vec<RuleDef> = state
.rule_defs
.iter()
.map(|b| {
decode_rule_def(b).map_err(|e| GraphError::Corrupt {
detail: format!("snapshot rule_def deserialize: {e}"),
})
})
.collect::<Result<Vec<_>>>()?;
self.engine =
RuleEngine::from_persist(defs, state.provenance, state.rule_tripped, state.rule_fires);
// Candidate indexes are rebuilt lazily on the first mutation (see
// RuleEngine::on_node_changed). HNSW blobs and IVF centroids from the
// snapshot are retained without deserializing so that:
// - clean-open (empty WAL): indexes stay empty; blobs load on first
// ANN query via ensure_hnsw_loaded, or on first mutation via the
// lazy-init guard which calls reindex_all_load_state (the scan
// skips the HNSW build for every side the blob supplies).
// - WAL-present: open_with calls consume_retained_state_eager before
// replay so HNSW/IVF are live before any record fires the hooks.
let ivf_bytes = if state.ivf_state.is_empty() {
Vec::new()
} else {
bincode::serialize(&state.ivf_state).expect("IVF state serialize cannot fail")
};
// Store blobs without eagerly deserializing them.
// `self.ids` is the snapshot's id table at this point — WAL replay has
// not run — so its length is the line an interrupted build is detected
// against.
let snapshot_ids = self.ids.len() as u32;
self.engine
.store_snapshot_state(state.hnsw_state, ivf_bytes, snapshot_ids);
// Restore view defs from snapshot (V5).
// The ColumnStore already contains view values from the snapshot;
// use restore_view (no collision check, no backfill) so the store
// is aware of the definitions. rebuild_all runs after WAL replay.
for def_bytes in &state.view_defs {
let def: ViewDef =
bincode::deserialize(def_bytes).map_err(|e| GraphError::Corrupt {
detail: format!("snapshot view_def deserialize: {e}"),
})?;
self.view_store
.restore_view(def)
.map_err(|e| GraphError::Corrupt {
detail: format!("snapshot view restore: {e}"),
})?;
}
Ok(())
}
/// Restore all persisted state from a V8 `MappedBase` snapshot, **except**
/// topology (`self.topo` stays empty and serves as the WAL-replay overlay).
///
/// `self.props` IS fully materialised from the base so that HNSW/IVF blob
/// deserialization and view rebuild have access to all column data.
fn restore_v8_base(&mut self, mapped: Arc<core_storage::v8::MappedBase>) -> Result<()> {
self.ids = archived_to_idmap(mapped.ids().map_err(|e| GraphError::Corrupt {
detail: format!("v8: ids section: {e:?}"),
})?);
self.syms = archived_to_interner(mapped.syms().map_err(|e| GraphError::Corrupt {
detail: format!("v8: syms section: {e:?}"),
})?);
// C1: self.props is left as an empty overlay. Column reads go through
// props_view() (ColumnsView::with_base), which consults the archived base
// section zero-copy. This avoids the O(columns) heap copy at every open.
// self.topo deliberately left as Topology::new() — overlay path.
let meta = decode_meta(mapped.meta_bytes().map_err(|e| GraphError::Corrupt {
detail: format!("v8: meta section: {e:?}"),
})?)
.map_err(|e| GraphError::Corrupt {
detail: format!("v8: meta decode: {e:?}"),
})?;
self.labels = meta.labels;
// Cross-section label integrity: labels must cover every id slot (live
// and tombstoned), every non-sentinel sym must be within the interner's
// bound, and no live (non-tombstoned) node may carry the u32::MAX
// sentinel label. Without this check, a crafted snapshot where the META
// section (small, CRC-validated) holds a short `labels` vec, out-of-range
// sym ids, or a sentinel label on a live node, would open successfully
// and then panic in `NodeRef::label()`, `neighborhood_masked()`, and
// related read paths. Catching the inconsistency here converts those
// panics into typed `GraphError::Corrupt` at open time.
{
let ids_len = self.ids.len();
if self.labels.len() != ids_len {
return Err(GraphError::Corrupt {
detail: format!(
"v8: labels section has {} entries but id table has {} total slots",
self.labels.len(),
ids_len,
),
});
}
let syms_len = self.syms.len() as u32;
for (i, &sym) in self.labels.iter().enumerate() {
let is_tombstoned = self.ids.is_tombstoned(i as u32);
if sym == u32::MAX {
// Sentinel is only valid for tombstoned slots.
if !is_tombstoned {
return Err(GraphError::Corrupt {
detail: format!(
"v8: live node at id slot {i} has sentinel label (u32::MAX)"
),
});
}
} else if sym >= syms_len {
return Err(GraphError::Corrupt {
detail: format!(
"v8: label at id slot {i} references sym {sym} \
which is out of interner range ({syms_len})"
),
});
}
}
}
// C3: self.edge_props stays as an empty overlay. Reads go through
// edge_props_view() which consults the mmap'd base section zero-copy
// via EdgePropsView::with_base. No heap decode at open time.
// Restore rule engine.
let (rule_def_bytes, rule_tripped, rule_fires) =
archived_rules_meta_to_owned(mapped.rules_meta_section().map_err(|e| {
GraphError::Corrupt {
detail: format!("v8: rules_meta section: {e:?}"),
}
})?);
let defs: Vec<RuleDef> = rule_def_bytes
.iter()
.map(|b| {
decode_rule_def(b).map_err(|e| GraphError::Corrupt {
detail: format!("v8: rule_def deserialize: {e}"),
})
})
.collect::<Result<Vec<_>>>()?;
self.engine = RuleEngine::from_persist(defs, BTreeMap::new(), rule_tripped, rule_fires);
// C4+C5: provenance, HNSW, and IVF sections are NOT read here.
// `ensure_v8_base_sections_loaded` reads them on first use from
// `self.base` (set by the caller immediately after this returns).
// A clean open touches only: header + IDS + SYMS + META + RULES_META.
// Restore view definitions.
let view_defs =
archived_views_to_owned(mapped.views_section().map_err(|e| GraphError::Corrupt {
detail: format!("v8: views section: {e:?}"),
})?);
for def_bytes in &view_defs {
let def: ViewDef =
bincode::deserialize(def_bytes).map_err(|e| GraphError::Corrupt {
detail: format!("v8: view_def deserialize: {e}"),
})?;
self.view_store
.restore_view(def)
.map_err(|e| GraphError::Corrupt {
detail: format!("v8: view restore: {e}"),
})?;
}
// Load the last-change map from section 11 (small section; load eagerly).
// Pre-Task-3 snapshots lack this section; `last_change_bytes` returns &[]
// in that case and `decode_last_change_bytes` returns an empty map.
let last_change_raw = mapped
.last_change_bytes()
.map_err(|e| GraphError::Corrupt {
detail: format!("v8: last_change section: {e:?}"),
})?;
self.last_change = decode_last_change_bytes(last_change_raw);
// Validate that all deferred sections (provenance, HNSW, IVF) fit within
// the file. Pure bounds check — no bytes read, no page faults triggered.
// Catches truncated snapshots at open time before the lazy deferred reads.
mapped.validate_section_bounds().map_err(|e| match e {
GraphError::Corrupt { detail } => GraphError::Corrupt {
detail: format!("v8: section bounds: {detail}"),
},
other => other,
})?;
Ok(())
}
/// Read provenance, HNSW, and IVF sections from the mmap base into the
/// engine's retained fields on first call. Subsequent calls are a no-op
/// (AtomicBool fast-path).
///
/// Must be called before any code path that reads or mutates engine
/// provenance, HNSW, or IVF state:
/// - WAL replay (before `consume_retained_state_eager`)
/// - First mutation (`log_then_apply_with`)
/// - Read-only paths (`stats`, `explain`, `node_edges`)
/// - Snapshot (`snapshot_with`)
///
/// No-op for fresh stores and V5-V7 opens (`self.base` is `None`).
fn ensure_v8_base_sections_loaded(&self) {
use std::sync::atomic::Ordering;
if self.v8_sections_loaded.load(Ordering::Acquire) {
return;
}
let _guard = self
.v8_sections_mutex
.lock()
.expect("v8 sections mutex poisoned");
if self.v8_sections_loaded.load(Ordering::Acquire) {
return; // another caller populated while we waited
}
let _t = std::time::Instant::now();
if let Some(base) = &self.base {
// Provenance: raw rkyv bytes; CRC validated inside section_bytes.
// Bounds are already validated at open time (restore_v8_base →
// validate_section_bounds) — unreachable post-validate_section_bounds;
// unwrap_or_default is a safety belt against impossible errors.
let prov_bytes = base
.provenance_raw_bytes()
.map(|b| b.to_vec())
.unwrap_or_default();
self.engine.store_provenance_bytes(prov_bytes);
// HNSW: decode rkyv blobs into owned map.
let hnsw_state = base
.hnsw_section()
.map(archived_hnsw_to_owned)
.unwrap_or_default();
// IVF: raw bincode bytes; deserialized on first mutation/query.
let ivf_bytes = base.ivf_bytes().map(|b| b.to_vec()).unwrap_or_default();
// Called before WAL replay on a WAL-present open (`open_with`) and
// before any write on a clean one, so this is the snapshot's count.
let snapshot_ids = self.ids.len() as u32;
self.engine
.store_snapshot_state(hnsw_state, ivf_bytes, snapshot_ids);
}
self.v8_sections_loaded.store(true, Ordering::Release);
if std::env::var("MUSHROOMDB_TRACE_OPEN").is_ok() {
eprintln!(
"[MUSHROOMDB_TRACE_OPEN] ensure_v8_base_sections_loaded: {:>9.3?}",
_t.elapsed()
);
}
}
/// Return a `TopologyView` that merges the mmap'd base (when present) with
/// the in-memory WAL overlay. Used by all read paths in db.rs that need
/// the full merged topology without going through `self.view()`.
fn topo_view(&self) -> TopologyView<'_> {
match self.base {
None => TopologyView::owned(&self.topo),
Some(ref base) => {
// SAFETY: base lives as long as self; section bounds validated at open.
// topology() uses access_unchecked; all field reads are bounds-checked in seam.rs.
let archived = base
.topology()
.expect("base topology section bounds validated at open");
TopologyView::with_base(&self.topo, archived)
}
}
}
/// Return a `ColumnsView` that merges the mmap'd base columns (when a V8
/// snapshot is open) with the in-memory WAL overlay. Reads consult the
/// overlay first, then fall through to the archived base section zero-copy.
fn props_view(&self) -> core_storage::v8::seam::ColumnsView<'_> {
match self.base {
None => core_storage::v8::seam::ColumnsView::owned(&self.props),
Some(ref base) => {
// columns() uses access_unchecked; field reads are bounds-checked in seam.rs.
let archived = base
.columns()
.expect("base columns section bounds validated at open");
core_storage::v8::seam::ColumnsView::with_base_cached(
&self.props,
archived,
base.mixed_cache(),
)
.with_shared_strings(base_string_table(base))
}
}
}
/// Return an `EdgePropsView` that merges the mmap'd base edge-props section
/// (when a V8 snapshot is open) with the in-memory WAL overlay.
///
/// Reads consult the overlay first (for post-snapshot mutations), then fall
/// through to the archived base section zero-copy. Tombstones in the
/// overlay mask deleted-from-base entries.
fn edge_props_view(&self) -> EdgePropsView<'_> {
match self.base {
None => EdgePropsView::owned(&self.edge_props),
Some(ref base) => {
// edge_props_section() uses access_unchecked; field reads bounds-checked in seam.rs.
let archived = base
.edge_props_section()
.expect("base edge_props section bounds validated at open");
EdgePropsView::with_base(&self.edge_props, archived)
}
}
}
fn open_at_with(fs: F, commit: u64) -> Result<Self> {
// An as-of view never writes and is pinned to one commit: it takes no
// cross-process lock and does not follow later commits.
let mut db = Self::new_empty(
fs,
OpenOptions {
repair_wal: false,
auto_migrate: false,
read_only: true,
},
);
db.pinned = true; // read_only is set after replay, but pinning is immediate
db.wal_horizon_floor = db.fs.read_horizon_floor()?;
db.archive_genesis_chain = db.fs.has_genesis_marker();
// Same orphaned-archive cleanup as open_with: floor was written first
// during pruning, so a crash may have left stale archives below floor.
db.cleanup_orphaned_archives()?;
// Collect archive frames (oldest-first) and live WAL frames.
// Archives represent pre-snapshot history; the snapshot captures the
// cumulative state at the time of archiving. Crash-window guarantee:
// A: crash before rename → WAL intact, no archive. Reopen: normal.
// B: crash after rename, before new WAL → archive present, WAL
// absent. Reopen: snapshot loaded (full state), no WAL replay.
// C: crash after new baseline WAL written → normal post-archive.
let archive_ns = db.fs.list_archives()?;
let mut archive_frames_all: Vec<WalRecord> = Vec::new();
for n in &archive_ns {
let arc_bytes = db.fs.read_archive(*n)?;
let (arc_frames, _) = decode_all(&arc_bytes);
archive_frames_all.extend(arc_frames);
}
let total_archive_frames = archive_frames_all.len() as u64;
let live_bytes = db.fs.read(FileId::Wal)?;
let (live_records, _valid_len) = decode_all(&live_bytes);
let total_surviving = total_archive_frames + live_records.len() as u64;
// Global total including any pruned history below the horizon floor.
let total = db.wal_horizon_floor + total_surviving;
// Horizon and range check.
if commit < db.wal_horizon_floor {
return Err(GraphError::CommitOutOfRange {
commit,
total,
floor: db.wal_horizon_floor,
});
}
if commit >= total {
return Err(GraphError::CommitOutOfRange {
commit,
total,
floor: db.wal_horizon_floor,
});
}
// Local index into surviving frames (0 = first frame of oldest archive).
let local = commit - db.wal_horizon_floor;
if local < total_archive_frames {
// Target commit is in an archive. Correct replay from empty state
// is only possible when the archive chain is an uninterrupted
// genesis chain (first archive taken from a fresh store, no prior
// WAL truncation) and no archives have been pruned (floor == 0).
//
// If either condition is violated the prefix needed to reconstruct
// the requested state is gone; refuse rather than return wrong data.
if db.wal_horizon_floor > 0 || !db.archive_genesis_chain {
return Err(GraphError::CommitOutOfRange {
commit,
total,
floor: db.wal_horizon_floor,
});
}
// Replay all archive frames up to and including the target commit
// from an empty database state. Archives must be replayed in order
// so that dense-id intern tables are built up correctly.
for rec in archive_frames_all.into_iter().take((local + 1) as usize) {
db.apply(&rec)?;
let _ = db.engine.drain_deltas();
}
} else {
// Target commit is in the live WAL: load snapshot as base, then
// replay the needed live WAL prefix.
//
// Base state: a truncating snapshot (wal_truncated=true) compacts
// all pre-truncation / pre-archive commits. Dense-id records in
// the live WAL reference ids/interns that the snapshot provides.
// Peek 6 bytes (same pattern as open_with).
let snap_header = db.fs.read_prefix(FileId::Snapshot, 6)?;
let is_v8 = snap_header.len() >= 6
&& &snap_header[0..4] == b"GDB1"
&& matches!(
u16::from_le_bytes([snap_header[4], snap_header[5]]),
core_storage::snapshot::VERSION_8 | core_storage::snapshot::VERSION_9
);
if is_v8 {
let state = if let Some(snap_path) = db.fs.snapshot_path() {
let mapped = core_storage::v8::MappedBase::map(&snap_path).map_err(|e| {
GraphError::Corrupt {
detail: format!("v8: open_at mmap: {e:?}"),
}
})?;
core_storage::snapshot::decode_v8_from_mapped(&mapped)?
} else {
let snap_bytes = db.fs.read(FileId::Snapshot)?;
core_storage::snapshot::decode(&snap_bytes)?
};
if let Some(state) = state {
if state.wal_truncated {
db.restore_snapshot_state(state)?;
}
}
} else if !snap_header.is_empty() {
let snap_bytes = db.fs.read(FileId::Snapshot)?;
if let Some(state) = core_storage::snapshot::decode(&snap_bytes)? {
if state.wal_truncated {
db.restore_snapshot_state(state)?;
}
}
}
// else: snap_header empty = no snapshot file.
let live_local = local - total_archive_frames;
for rec in live_records.into_iter().take((live_local + 1) as usize) {
db.apply(&rec)?;
let _ = db.engine.drain_deltas();
}
}
// Pin: pending_delta_count must be 0 after as-of replay, mirroring T1's
// post-loop assert in open_with.
debug_assert_eq!(
db.engine.pending_delta_count(),
0,
"pending_deltas non-empty after open_at replay — \
per-frame drain must run inside the loop to keep memory O(1)"
);
let _ = db.engine.drain_deltas(); // belt-and-braces no-op
// Rebuild view values after WAL replay so derived-edge-driven views
// reflect the as-of state. open_at always uses the legacy path (no V8
// base), so topo_view is always owned.
{
let topo_view = TopologyView::owned(&db.topo);
db.view_store
.rebuild_all(&mut db.props, &topo_view, &db.ids, &db.syms, &db.labels);
}
// Rebuild full-text index for as-of view (mirrors open_with pattern).
db.fulltext.rebuild_all(
&db.ids,
&db.labels,
&db.syms,
build_props_view(&db.props, &db.base),
);
db.prop_index.rebuild_all(
&db.ids,
&db.labels,
&db.syms,
build_props_view(&db.props, &db.base),
);
// Namespaces on the temporal handle, built by the same pass the live
// open uses, so an as-of mask narrows by the namespaces of that commit.
db.rebuild_node_ns();
// Load roles sidecar (current roles, not point-in-time).
db.roles = Self::load_roles_from_fs(&db.fs)?;
db.read_only = true;
db.total_wal_commits = total;
// Capture initial fold so reader() is immediately usable.
db.fold_now();
Ok(db)
}
/// Whether this instance is a read-only as-of view.
pub fn is_read_only(&self) -> bool {
self.read_only
}
// ── MVCC epoch reader ─────────────────────────────────────────────────────
/// Clone the current overlay state into a new `FrozenOverlay` and reset
/// the delta tail. Called automatically every `FOLD_EVERY_K` commits and at
/// the end of `open_with` / `open_at_with` to prime the reader.
fn fold_now(&mut self) {
let frozen = crate::reader::FrozenOverlay {
ids: self.ids.clone(),
syms: self.syms.clone(),
topo: self.topo.clone(),
props: self.props.clone(),
labels: self.labels.clone(),
edge_props: self.edge_props.clone(),
roles: self.roles.clone(),
fulltext: self.fulltext.clone(),
};
self.fold_overlay = Some(Arc::new(frozen));
self.delta_tail.clear();
self.commits_since_fold = 0;
}
/// Capture a lock-free reader snapshot of the current db state.
///
/// The read lock is held only for the duration of this call (to clone a
/// handful of `Arc` handles). Subsequent query operations run without any
/// lock.
pub fn reader(&self) -> crate::reader::ReaderSnapshot {
crate::reader::ReaderSnapshot::new(
self.fold_overlay
.clone()
.expect("fold_overlay is always Some after open_with; call reader() after open"),
self.base.clone(),
self.delta_tail.clone(),
// The snapshot's effective state is exactly this handle's state at
// this commit, so it shares the memo and its version key.
self.commit_seq,
Arc::clone(&self.role_masks),
)
}
/// Total number of WAL commits at the time [`open_at`] was called.
/// Returns 0 for normal (non-as-of) instances.
pub fn total_wal_commits(&self) -> u64 {
self.total_wal_commits
}
/// Apply a record to in-memory state. Used by both live writes and replay,
/// so replay is definitionally identical to the original execution.
fn apply(&mut self, rec: &WalRecord) -> Result<()> {
// Before the record mutates anything: a store restored from a snapshot
// defers building its candidate indexes until the first write, and that
// build is a full node scan. Left where it used to fire — inside the
// engine hook, after `props.set` and the label assignment — the scan
// read the half-applied record and took the in-flight node's vector for
// one the snapshot should have carried, which read as an interrupted
// vector-index build and cost a full `RebuildRule` on the first
// embedded write after every reopen. Hoisted here the scan sees exactly
// the persisted state; the record's own hook then files its vector
// through the ordinary insert path a line later.
self.populate_indexes_before_write();
match rec {
WalRecord::InsertNode { label, key, props } => {
let id = self.ids.try_insert(key)?;
let sym = self.syms.intern(label);
if self.labels.len() <= id as usize {
// gap slots are sentinels, never valid label symbols
self.labels.resize(id as usize + 1, u32::MAX);
}
self.labels[id as usize] = sym;
let mut ns_name = NS_DEFAULT.to_string();
for (field, value) in props {
if field == NS_PROP {
ns_name = namespace_of_value(Some(value)).to_string();
}
self.props.set(id, field, value.clone());
}
self.set_node_ns(id, &ns_name);
// Initialize view values for the new node before the engine runs so
// delta-based increments start from a known zero baseline.
self.view_store
.init_node_views(id, &mut self.props, &self.syms, &self.labels);
// Fire rules for the newly inserted node.
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_node_changed(id, None, &mut gm);
}
self.engine = eng;
// Process derived-edge deltas for view maintenance.
// Fast path: skip the O(delta_count) allocation when no views exist.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
// Full-text index maintenance: index enabled fields for this label.
if self.fulltext.has_label(label) {
for (field, value) in props {
if self.fulltext.is_enabled(label, field) {
self.fulltext.add_tokens(id, field, value);
}
}
}
// Property (equality) index maintenance.
if self.prop_index.has_label(label) {
for (field, value) in props {
self.prop_index.set(label, field, id, value);
}
}
}
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
let src = self.ids.get(src_key).ok_or_else(|| GraphError::Corrupt {
detail: format!("wal replay references unknown key {src_key}"),
})?;
let dst = self.ids.get(dst_key).ok_or_else(|| GraphError::Corrupt {
detail: format!("wal replay references unknown key {dst_key}"),
})?;
let etype = self.syms.intern(edge_type);
// Skip if the edge is already visible in the merged base+overlay
// view. This keeps WAL replay idempotent when the WAL contains
// pre-snapshot records that are already encoded in a V8 base
// (keep_wal=true opens and crash-before-truncation scenarios).
if self.base.is_some()
&& self
.topo_view()
.neighbors(etype, Direction::Out, src)
.contains(&dst)
{
return Ok(());
}
self.topo.add_edge(etype, src, dst);
// View maintenance for manual edge insert.
self.view_store.on_edge_changed(
etype,
src,
dst,
true,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
// Rule engine: via-hop rules must update when user edges change.
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_edge_changed(edge_type, src, dst, &mut gm);
}
self.engine = eng;
if !self.view_store.is_empty() {
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
}
WalRecord::SetProp { key, field, value } => {
let id = self.ids.get(key).ok_or_else(|| GraphError::Corrupt {
detail: format!("wal replay references unknown key {key}"),
})?;
let old_value = build_props_view(&self.props, &self.base)
.get(id, field)
.map(|vr| vr.into_value());
self.props.set(id, field, value.clone());
// Fire rules for the changed field.
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_node_changed(id, Some((field, old_value)), &mut gm);
}
self.engine = eng;
// Derived-edge deltas → view updates.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
// Neighbor-aggregate views that read `field` must also update.
self.view_store.on_prop_changed(
id,
field,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
// Full-text index maintenance: update tokens for this field if indexed.
if self.fulltext.field_indexed(field) {
let label_opt = self.labels.get(id as usize).and_then(|&sym| {
if sym == u32::MAX {
None
} else {
self.syms.resolve(sym)
}
});
if let Some(label) = label_opt {
if self.fulltext.is_enabled(label, field) {
self.fulltext.remove_node_field(id, field);
self.fulltext.add_tokens(id, field, value);
}
}
}
// Property (equality) index maintenance: re-key this node's value.
if self.prop_index.field_indexed(field) {
let label_opt = self.labels.get(id as usize).and_then(|&sym| {
if sym == u32::MAX {
None
} else {
self.syms.resolve(sym)
}
});
if let Some(label) = label_opt {
self.prop_index.set(label, field, id, value);
}
}
}
WalRecord::Intern { id, text } => {
if let Some(existing) = self.syms.get(text) {
if existing != *id {
return Err(GraphError::Corrupt {
detail: format!(
"wal intern mismatch for {text:?}: have {existing}, record {id}"
),
});
}
} else {
let got = self.syms.intern(text);
if got != *id {
return Err(GraphError::Corrupt {
detail: format!(
"wal intern assigned {got} for {text:?}, record wanted {id}"
),
});
}
}
}
WalRecord::InsertNodeId { label, key, props } => {
let id = self.ids.try_insert(key)?;
if self.labels.len() <= id as usize {
self.labels.resize(id as usize + 1, u32::MAX);
}
self.labels[id as usize] = *label;
let label_str = self
.syms
.resolve(*label)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("wal InsertNodeId unknown label intern {label}"),
})?
.to_string();
let mut ns_name = NS_DEFAULT.to_string();
for (field_sym, value) in props {
let field =
self.syms
.resolve(*field_sym)
.ok_or_else(|| GraphError::Corrupt {
detail: format!(
"wal InsertNodeId unknown field intern {field_sym}"
),
})?;
if field == NS_PROP {
ns_name = namespace_of_value(Some(value)).to_string();
}
self.props.set(id, field, value.clone());
}
self.set_node_ns(id, &ns_name);
self.view_store
.init_node_views(id, &mut self.props, &self.syms, &self.labels);
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_node_changed(id, None, &mut gm);
}
self.engine = eng;
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
if self.fulltext.has_label(&label_str) {
for (field_sym, value) in props {
let Some(field) = self.syms.resolve(*field_sym) else {
continue;
};
if self.fulltext.is_enabled(&label_str, field) {
self.fulltext.add_tokens(id, field, value);
}
}
}
if self.prop_index.has_label(&label_str) {
for (field_sym, value) in props {
let Some(field) = self.syms.resolve(*field_sym) else {
continue;
};
self.prop_index.set(&label_str, field, id, value);
}
}
}
WalRecord::InsertEdgeId { etype, src, dst } => {
// Replay-over-snapshot: dense ids in the pre-snapshot WAL may
// already be tombstoned. Skip rather than attaching edges to
// dead ids (DeleteNode keys the live re-insert, not the old id).
if self.ids.is_tombstoned(*src)
|| self.ids.is_tombstoned(*dst)
|| self.ids.key_of(*src).is_none()
|| self.ids.key_of(*dst).is_none()
{
return Ok(());
}
// Skip if already visible in the merged view (same idempotency
// guard as InsertEdge above: prevents double-counting when
// pre-snapshot WAL records are replayed over a V8 base).
if self.base.is_some()
&& self
.topo_view()
.neighbors(*etype, Direction::Out, *src)
.contains(dst)
{
return Ok(());
}
self.topo.add_edge(*etype, *src, *dst);
self.view_store.on_edge_changed(
*etype,
*src,
*dst,
true,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
// Rule engine: via-hop rules fire when user via-edges are inserted.
// Resolve etype back to string so on_edge_changed can match rules by name.
if let Some(etype_str) = self.syms.resolve(*etype).map(|s| s.to_string()) {
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_edge_changed(&etype_str, *src, *dst, &mut gm);
}
self.engine = eng;
if !self.view_store.is_empty() {
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
}
}
WalRecord::SetPropId { id, field, value } => {
if self.ids.is_tombstoned(*id) || self.ids.key_of(*id).is_none() {
return Ok(());
}
let field_str = self
.syms
.resolve(*field)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("wal SetPropId unknown field intern {field}"),
})?
.to_string();
let old_value = build_props_view(&self.props, &self.base)
.get(*id, &field_str)
.map(|vr| vr.into_value());
self.props.set(*id, &field_str, value.clone());
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_node_changed(*id, Some((field_str.as_str(), old_value)), &mut gm);
}
self.engine = eng;
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
self.view_store.on_prop_changed(
*id,
&field_str,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
if self.fulltext.field_indexed(&field_str) {
let label_opt = self.labels.get(*id as usize).and_then(|&sym| {
if sym == u32::MAX {
None
} else {
self.syms.resolve(sym)
}
});
if let Some(label) = label_opt {
if self.fulltext.is_enabled(label, &field_str) {
self.fulltext.remove_node_field(*id, &field_str);
self.fulltext.add_tokens(*id, &field_str, value);
}
}
}
if self.prop_index.field_indexed(&field_str) {
let label_opt = self.labels.get(*id as usize).and_then(|&sym| {
if sym == u32::MAX {
None
} else {
self.syms.resolve(sym)
}
});
if let Some(label) = label_opt {
self.prop_index.set(label, &field_str, *id, value);
}
}
}
WalRecord::CreateRule { def_bytes } => {
let def: RuleDef = decode_rule_def(def_bytes).map_err(|e| GraphError::Corrupt {
detail: format!("CreateRule def_bytes deserialize failed: {e}"),
})?;
// Replay-over-snapshot idempotency: the rule was captured in the snapshot
// so the engine already has it; silently skip to avoid a spurious
// RuleInvalid error in the crash window between snapshot write and WAL
// truncation.
if self.engine.rules().any(|r| r.name == def.name) {
return Ok(());
}
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
let result = {
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.create_rule(def, &mut gm)
};
self.engine = eng;
result.map_err(|e| GraphError::RuleInvalid { detail: e })?;
// Derived-edge fires from backfill → view updates.
// Fast path: skip O(edge_count) allocation when no views exist.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
}
WalRecord::DeleteRule { name } => {
// Replay-over-snapshot idempotency: the snapshot already captured the
// post-delete state so the rule is absent; silently skip to avoid a
// spurious RuleNotFound error in the crash window between snapshot write
// and WAL truncation.
if !self.engine.rules().any(|r| r.name == *name) {
return Ok(());
}
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
let result = {
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.delete_rule(name, &mut gm)
};
self.engine = eng;
result.map_err(|_| GraphError::RuleNotFound { name: name.clone() })?;
// Derived-edge retractions → view updates.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
}
WalRecord::RemoveProp { key, field } => {
// Recovery-safe: unknown key or already-absent field is a
// clean no-op. Crash-window replay over a snapshot that
// already applied this record must not Err.
let Some(id) = self.ids.get(key) else {
return Ok(());
};
// Read old value through the seam for rule retraction.
let old = build_props_view(&self.props, &self.base)
.get(id, field)
.map(|vr| vr.into_value());
self.props.remove(id, field);
// If the base still supplies the value after the overlay removal,
// record a tombstone so ColumnsView::get does not resurrect it.
// This covers both the base-only case AND the both-resident case:
// base-only (in_overlay=false): old prop was only in base, remove
// is a no-op on overlay, base still visible → tombstone needed.
// both-resident (in_overlay=true): overlay had v2, base has v1;
// removing overlay uncovers v1 → tombstone needed.
// Idempotent on double-replay: second pass sees the tombstone →
// get() returns None → condition is false → no duplicate tombstone.
if build_props_view(&self.props, &self.base)
.get(id, field)
.is_some()
{
self.props.record_prop_tombstone(id, field);
}
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_node_changed(id, Some((field, old)), &mut gm);
}
self.engine = eng;
// Derived-edge deltas → view updates.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
// Neighbor-aggregate views that read `field` must also update.
self.view_store.on_prop_changed(
id,
field,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
// Full-text index maintenance: remove tokens for this field.
if self.fulltext.field_indexed(field) {
self.fulltext.remove_node_field(id, field);
}
// Property (equality) index maintenance: drop this node's entry.
if self.prop_index.field_indexed(field) {
if let Some(label) = self.labels.get(id as usize).and_then(|&sym| {
(sym != u32::MAX).then(|| self.syms.resolve(sym)).flatten()
}) {
self.prop_index.remove_node(label, field, id);
}
}
}
WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
} => {
// Recovery-safe: unknown keys, unknown etype, or already-
// absent edge is a clean no-op (remove_edge returns false).
let Some(src) = self.ids.get(src_key) else {
return Ok(());
};
let Some(dst) = self.ids.get(dst_key) else {
return Ok(());
};
let Some(etype) = self.syms.get(edge_type) else {
return Ok(());
};
// I3: phantom-tombstone guard. When a V8 base is present, a
// DeleteEdge WAL record for an edge that was already absorbed into
// the new base (i.e. neither in overlay nor in base) must be skipped.
// Without this guard, remove_edge records a tombstone for an edge
// that no longer exists, incorrectly understating edge_count.
if self.base.is_some()
&& !self
.topo_view()
.neighbors(etype, core_storage::topology::Direction::Out, src)
.contains(&dst)
{
return Ok(());
}
self.topo.remove_edge(etype, src, dst);
self.edge_props.remove_edge(etype, src, dst);
// View maintenance for manual edge delete (topo already updated above).
self.view_store.on_edge_changed(
etype,
src,
dst,
false,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
// Rule engine: via-hop rules must retract when user via-edges are deleted.
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_edge_changed(edge_type, src, dst, &mut gm);
}
self.engine = eng;
if !self.view_store.is_empty() {
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
}
WalRecord::DeleteNode { key } => {
// Recovery-safe: already-tombstoned / unknown key is a clean
// no-op. Crash-window replay over a snapshot that already
// applied this record cannot recover the retired id from the
// key (`IdMap::get` is None), so every subsequent step is
// skipped. Each step is independently idempotent if invoked
// twice on a still-live id: retraction is a no-op on empty
// provenance, `remove_edge` returns false, `remove_all` is a
// no-op, `ids.delete` returns None, label sentinel is sticky.
let Some(n) = self.ids.get(key) else {
return Ok(());
};
// (1) Retract derived edges + de-index while props/labels live.
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
{
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.on_node_removed(n, &mut gm);
}
self.engine = eng;
// Derived-edge retractions → view updates for neighbors.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
// (2) Sweep ALL remaining edges incident to n, both directions,
// every etype. This cascade is intentionally mask-independent:
// topology integrity requires removing every edge touching the
// deleted node regardless of the caller's visibility scope.
// (The mask limits which nodes a role's read phase can return;
// the WAL delete always executes with full storage authority.)
// Collect then remove so neighbor slices stay valid during
// iteration. Remove from topo first, then call view maintenance
// so Avg/Min/Max recompute sees the correct (reduced) neighbor set.
let etypes: Vec<u32> = self.topo.etypes().collect();
let mut doomed = Vec::new();
for et in &etypes {
for &dst in self.topo.neighbors(*et, Direction::Out, n).as_ref() {
doomed.push((*et, n, dst));
}
for &src in self.topo.neighbors(*et, Direction::In, n).as_ref() {
doomed.push((*et, src, n));
}
}
for (et, s, d) in doomed {
self.topo.remove_edge(et, s, d);
self.edge_props.remove_edge(et, s, d);
// View maintenance: n's own view values will be cleared by
// remove_all below; only update surviving neighbors.
self.view_store.on_edge_changed(
et,
s,
d,
false,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
// (3) Drop every remaining prop (`ColumnStore::remove_all`).
self.props.remove_all(n);
// Full-text index maintenance: remove all tokens for this node.
self.fulltext.remove_node(n);
// Property (equality) index maintenance: drop all entries for n.
self.prop_index.remove_node_all(n);
// (4) Retire the dense id and stamp the label sentinel.
self.ids.delete(key);
if let Some(slot) = self.labels.get_mut(n as usize) {
*slot = u32::MAX;
}
}
WalRecord::Batch(inner) => {
// Apply each inner record in order through the same apply path.
// Inner records are validated free of nested Batch by encode_record.
for rec in inner {
self.apply(rec)?;
}
}
WalRecord::RebuildRule { name } => {
// Replay-over-snapshot idempotency: the snapshot may already
// reflect a later delete_rule, so the rule is absent; skip.
if !self.engine.rules().any(|r| r.name == *name) {
return Ok(());
}
let cursor = self.engine.pending_delta_count();
let mut eng = std::mem::take(&mut self.engine);
let result = {
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.rebuild(name, &mut gm)
};
self.engine = eng;
result.map_err(|_| GraphError::RuleNotFound { name: name.clone() })?;
// Derived-edge delta changes → view updates.
if !self.view_store.is_empty() {
#[cfg(test)]
DELTA_COPY_COUNT.with(|c| c.set(c.get() + 1));
let new_deltas: Vec<_> = self.engine.pending_deltas_since(cursor).to_vec();
for d in &new_deltas {
self.view_store.on_edge_changed(
d.etype_sym,
d.src_id,
d.dst_id,
d.fired,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
base_columns(&self.base),
);
}
}
}
WalRecord::CreateView { def_bytes } => {
let def: ViewDef =
bincode::deserialize(def_bytes).map_err(|e| GraphError::Corrupt {
detail: format!("CreateView def_bytes deserialize failed: {e}"),
})?;
// Replay-over-snapshot idempotency: view already present → skip.
if self.view_store.has_view(&def.name) {
return Ok(());
}
self.view_store
.create_view(
def,
&mut self.props,
&build_topo_view(&self.topo, &self.base),
&self.ids,
&self.syms,
&self.labels,
)
.map_err(|e| GraphError::RuleInvalid { detail: e })?;
}
WalRecord::DeleteView { name } => {
// Replay-over-snapshot idempotency: view already absent → skip.
if !self.view_store.has_view(name) {
return Ok(());
}
self.view_store
.delete_view(name, &mut self.props, &self.ids, &self.labels, &self.syms)
.map_err(|_| GraphError::RuleNotFound { name: name.clone() })?;
}
WalRecord::EnableFulltext { label, field } => {
// Replay-over-snapshot idempotency: already enabled → skip.
if self.fulltext.is_enabled(label, field) {
return Ok(());
}
self.fulltext.enable(label, field);
// Backfill: index all live nodes of this label that have the field.
let n = self.ids.len() as u32;
for id in 0..n {
let Some(&sym) = self.labels.get(id as usize) else {
continue;
};
if sym == u32::MAX {
continue; // tombstoned
}
let Some(lbl) = self.syms.resolve(sym) else {
continue;
};
if lbl != label {
continue;
}
if let Some(value) = build_props_view(&self.props, &self.base)
.get(id, field)
.map(|vr| vr.into_value())
{
self.fulltext.add_tokens(id, field, &value);
}
}
}
WalRecord::DisableFulltext { label, field } => {
// Replay-over-snapshot idempotency: already disabled → skip.
if !self.fulltext.is_enabled(label, field) {
return Ok(());
}
// If another label still indexes this field, the postings column
// is kept — but it must not contain node_ids from the now-disabled
// label. Remove them before calling disable() so the field_indexed
// guard inside disable() sees the correct post-removal state.
if self.fulltext.field_indexed_by_other(label, field) {
if let Some(label_sym) = self.syms.get(label) {
for (node_id, &lsym) in self.labels.iter().enumerate() {
if lsym == label_sym {
self.fulltext.remove_node_field(node_id as u32, field);
}
}
}
}
self.fulltext.disable(label, field);
}
WalRecord::EnableIndex { label, field } => {
// Replay-over-snapshot idempotency: already enabled → skip.
if self.prop_index.is_enabled(label, field) {
return Ok(());
}
self.prop_index.enable(label, field);
// Backfill: index all live nodes of this label that have the field.
let n = self.ids.len() as u32;
for id in 0..n {
let Some(&sym) = self.labels.get(id as usize) else {
continue;
};
if sym == u32::MAX {
continue; // tombstoned
}
let Some(lbl) = self.syms.resolve(sym) else {
continue;
};
if lbl != label {
continue;
}
if let Some(value) = build_props_view(&self.props, &self.base)
.get(id, field)
.map(|vr| vr.into_value())
{
self.prop_index.set(label, field, id, &value);
}
}
}
WalRecord::DisableIndex { label, field } => {
self.prop_index.disable(label, field);
}
// History markers carry no replay state — rules re-derive edges
// deterministically on open/replay. Skip unconditionally.
WalRecord::DerivedEdgeAdded { .. } | WalRecord::DerivedEdgeRetracted { .. } => {}
// ── rename_node ──────────────────────────────────────────────────
WalRecord::RenameNode { old_key, new_key } => {
// Recovery-safe: if old_key is already gone (key was renamed
// by a snapshot or a prior replay frame), skip cleanly.
if self.ids.get(old_key).is_none() {
return Ok(());
}
// The rename only updates the key-table; the dense id, all
// topo edges, props, labels, and rule state are id-indexed and
// require no change.
self.ids
.rename(old_key, new_key)
.map_err(|e| GraphError::Corrupt {
detail: format!("wal replay RenameNode {old_key}→{new_key}: {e}"),
})?;
}
}
Ok(())
}
/// Intern `s` in `syms` and emit a WAL `Intern` record so `*Id` records
/// replay on WAL-only `open_at` (no snapshot intern table). Apply is
/// idempotent when the string is already bound. Always emit: after
/// `snapshot()` the WAL is truncated and live intern is not on disk.
fn intern_wal(&mut self, s: &str) -> (u32, WalRecord) {
let id = if let Some(id) = self.syms.get(s) {
id
} else {
self.syms.intern(s)
};
(
id,
WalRecord::Intern {
id,
text: s.to_string(),
},
)
}
/// Rewrite user-facing records into dense-id records. On `Err`, no live
/// state is left mutated: speculative interns made while building the
/// output are rolled back, so a later successful mutation cannot log an
/// `Intern` record whose id replay would never reproduce.
fn rewrite_wal_dense(&mut self, recs: Vec<WalRecord>) -> Result<Vec<WalRecord>> {
let syms_checkpoint = self.syms.len();
let result = self.rewrite_wal_dense_inner(recs);
if result.is_err() {
self.syms.truncate(syms_checkpoint);
}
result
}
fn rewrite_wal_dense_inner(&mut self, recs: Vec<WalRecord>) -> Result<Vec<WalRecord>> {
let mut out = Vec::with_capacity(recs.len());
// Node ids allocated by later apply(InsertNodeId) in this same batch.
let mut pending: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
// Namespace of each node inserted earlier in this same frame, so a SET
// on a node this frame created is measured against the namespace it was
// created in rather than against the store, where it does not exist yet.
let mut pending_ns: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
let mut interned = std::collections::HashSet::<u32>::new();
let mut next = u32::try_from(self.ids.len()).map_err(|_| GraphError::Corrupt {
detail: "id space exhausted".into(),
})?;
let lookup = |ids: &IdMap,
pending: &std::collections::HashMap<String, u32>,
key: &str|
-> Option<u32> { ids.get(key).or_else(|| pending.get(key).copied()) };
for rec in recs {
match rec {
WalRecord::InsertNode { label, key, props } => {
// Namespace validation and normalisation, on the one seam
// every user-visible node insert passes through: insert_node,
// a batch, ingest, Cypher CREATE and MERGE all arrive here
// before the WAL append, and replay never does.
let (props, ns_name) = Self::normalise_insert_ns(&key, props)?;
pending_ns.insert(key.clone(), ns_name);
let (label_id, intern) = self.intern_wal(&label);
if interned.insert(label_id) {
out.push(intern);
}
let mut props_id = Vec::with_capacity(props.len());
for (field, value) in props {
let (field_id, intern) = self.intern_wal(&field);
if interned.insert(field_id) {
out.push(intern);
}
props_id.push((field_id, value));
}
if lookup(&self.ids, &pending, &key).is_none() {
pending.insert(key.clone(), next);
next = next.checked_add(1).ok_or_else(|| GraphError::Corrupt {
detail: "id space exhausted".into(),
})?;
}
out.push(WalRecord::InsertNodeId {
label: label_id,
key,
props: props_id,
});
}
WalRecord::SetProp { key, field, value } => {
// A namespace is set at insert and fixed after: the write is
// refused when it would move the node, and dropped when it
// names the namespace the node is already in. Checked here
// so set_prop, a batch, Cypher SET/MERGE and every upsert
// that merges props get the same answer.
if field == NS_PROP {
let Value::Str(ref to) = value else {
return Err(GraphError::RuleInvalid {
detail: format!(
"node {key}: {NS_PROP} must be a string naming a namespace, \
got {value:?}"
),
});
};
let from = pending_ns
.get(&key)
.cloned()
.or_else(|| self.namespace_of(&key))
.unwrap_or_else(|| NS_DEFAULT.to_string());
let to = to.clone();
if to != from {
return Err(GraphError::NamespaceImmutable {
key: key.clone(),
from,
to,
});
}
continue;
}
let id =
lookup(&self.ids, &pending, &key).ok_or_else(|| GraphError::Corrupt {
detail: format!("dense WAL rewrite missing key {key}"),
})?;
let (field_id, intern) = self.intern_wal(&field);
if interned.insert(field_id) {
out.push(intern);
}
out.push(WalRecord::SetPropId {
id,
field: field_id,
value,
});
}
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
let (etype, intern) = self.intern_wal(&edge_type);
if interned.insert(etype) {
out.push(intern);
}
let src = lookup(&self.ids, &pending, &src_key).ok_or_else(|| {
GraphError::Corrupt {
detail: format!("dense WAL rewrite missing src {src_key}"),
}
})?;
let dst = lookup(&self.ids, &pending, &dst_key).ok_or_else(|| {
GraphError::Corrupt {
detail: format!("dense WAL rewrite missing dst {dst_key}"),
}
})?;
out.push(WalRecord::InsertEdgeId { etype, src, dst });
}
WalRecord::RenameNode {
ref old_key,
ref new_key,
} => {
// Track the rename in `pending` so subsequent InsertEdge /
// SetProp records in this batch can resolve the new key.
let id = lookup(&self.ids, &pending, old_key).ok_or_else(|| {
GraphError::Corrupt {
detail: format!(
"dense WAL rewrite: RenameNode old key {old_key} not found"
),
}
})?;
pending.remove(old_key.as_str());
pending.insert(new_key.clone(), id);
out.push(rec);
}
// # Symbol-order invariant (load-bearing)
//
// Write-time and replay-time symbol assignment must agree: every
// symbol in a `Batch` frame has to receive the same dense id when
// the frame's records are replayed in order as it received when
// the frame was written.
//
// A rule's backfill interns its `edge_type` lazily
// (`core_rules::engine`, every `g.syms.intern(&def.edge_type)`
// site), and that backfill runs from `apply` — during the
// `CreateRule` record itself, and again from any later
// `InsertNodeId` in the same frame that makes the rule fire. At
// write time the whole batch is rewritten before any of it is
// applied, so a later `InsertEdge` in the same batch would win the
// lower id for its edge type; on replay the rule's lazy intern
// gets there first and steals it, and the `Intern` record fails at
// the `wal intern assigned …` check in `apply`.
//
// Pre-interning the rule's `edge_type` here, and emitting its
// `Intern` record ahead of the `CreateRule` record, makes both
// orders identical. `weight_prop` needs no pre-intern:
// `EdgeProps::set` keys props by `String`, never through the
// interner. `via_edge` needs none either: via-hop rules resolve it
// with `syms.get` and skip when it is absent.
//
// `RebuildRule` and `DeleteRule` need no such handling here:
// `RebuildRule` has no `BatchOp` variant, so it never appears
// inside a `Batch` today — it is only ever issued as its own
// standalone commit (`rebuild_rule`, or the auto-rebuild path
// that logs it as a second commit after the triggering op).
// `DeleteRule` does have a `BatchOp` variant and can appear
// inside a `Batch`, but it carries only a rule `name` — no
// `edge_type` or other symbol that needs pre-interning — so
// only `CreateRule` needs this arm.
WalRecord::CreateRule { ref def_bytes } => {
let def = decode_rule_def(def_bytes).map_err(|e| GraphError::Corrupt {
detail: format!("CreateRule def_bytes deserialize failed: {e}"),
})?;
let (etype, intern) = self.intern_wal(&def.edge_type);
if interned.insert(etype) {
out.push(intern);
}
out.push(rec);
}
other => out.push(other),
}
}
Ok(out)
}
fn log_dense(&mut self, recs: Vec<WalRecord>) -> Result<()> {
let recs = self.rewrite_wal_dense(recs)?;
match recs.len() {
0 => Ok(()),
1 => self.log_then_apply(recs.into_iter().next().unwrap()),
_ => self.log_then_apply(WalRecord::Batch(recs)),
}
}
/// Durable write, then notify the event sink. Replay (`apply` during
/// `open`) never enters this function, so it is the replay-silent seam.
fn log_then_apply(&mut self, rec: WalRecord) -> Result<()> {
self.log_then_apply_with(rec, None, self.fsync)
}
/// Whether this frame must fsync under `policy`.
///
/// Batched contract: user-visible batches (>1 mutation) fsync; single
/// mutations do not. The dense rewrite wraps a single mutation in a
/// `Batch([Intern.., <one *Id record>])`, so `Intern` records are excluded
/// from the count — removing that filter would make every single-op write
/// fsync under Batched (or, if the threshold were raised instead, skip a
/// needed fsync for real two-op batches).
fn wal_needs_sync(policy: FsyncPolicy, rec: &WalRecord) -> bool {
match policy {
FsyncPolicy::Relaxed => false,
FsyncPolicy::Strict => true,
FsyncPolicy::Batched => match rec {
// Intern + one mutation is the single-op rewrite, not a user batch.
WalRecord::Batch(inner) => {
inner
.iter()
.filter(|r| !matches!(r, WalRecord::Intern { .. }))
.count()
> 1
}
_ => false,
},
}
}
/// # Apply-infallibility invariant (load-bearing)
///
/// The ordering is: WAL append → fsync → apply. If `apply` returned `Err`
/// for a `Batch` frame after a successful WAL write, the WAL would contain
/// the full frame while in-memory state would reflect only the ops before
/// the failure. On reopen, WAL replay would then apply the entire batch —
/// diverging permanently from what the pre-crash process had in memory.
///
/// For `Batch` frames this situation cannot arise because:
/// - All validation runs via `commit_logged_batch`/`MutPreview` **before**
/// the WAL write. `MutPreview` uses the same `&mut self` that apply will
/// use, with no concurrent mutation between validation exit and apply entry.
/// - Every `apply` arm for a validated op is either infallible by construction
/// (`InsertNode`, `RemoveProp`, `DeleteEdge`, `DeleteNode`), has idempotency
/// guards that return `Ok(())` (`CreateRule`, `DeleteRule`), or is
/// guaranteed-present by validation (`InsertEdge`/`SetProp` key lookups).
/// - `on_node_changed` and `on_node_removed` return `()` — never `Err`.
///
/// A `debug_assert!` below fires in debug builds if `apply` ever returns
/// `Err` for a `Batch` frame, making any future regression immediately visible
/// in tests rather than silently diverging crash-recovery behaviour.
fn log_then_apply_with(
&mut self,
rec: WalRecord,
ingest: Option<(String, usize)>,
policy: FsyncPolicy,
) -> Result<()> {
// Read-only guard: as-of instances must never write the WAL.
if self.read_only {
return Err(GraphError::ReadOnly);
}
// Degraded guard: fsync failure left WAL truncated, or a refresh failed
// partway; in-memory state is ahead of (or out of step with) the
// on-disk WAL, so further mutations would deepen the divergence.
// Reopen the database to recover. Checked before the lock guard: this
// is the more serious condition and the more useful error.
if self.degraded {
return Err(GraphError::Io(std::io::Error::other(
"database degraded after group-commit fsync failure; reopen required",
)));
}
// Cross-process guard: this write scope asked for the store's write
// lock and did not get it. Writing anyway would append frames on top of
// a WAL another process is extending, so refuse instead.
if self.lock_denied {
return Err(GraphError::Busy { holder: None });
}
// Ensure retained provenance bytes are decoded into the live mutable
// fields before any mutation touches self.engine.provenance. This is a
// no-op if provenance was never stored (fresh store) or has already been
// consumed (subsequent mutations). WAL replay calls apply() directly
// and is covered by consume_retained_state_eager before replay.
self.ensure_v8_base_sections_loaded();
self.engine.ensure_provenance_loaded_mut();
// Invariant (I-1): no stale deltas may enter from a previous apply.
// If any engine method ever accumulates deltas before erroring, they would
// contaminate the *next* commit's event stream. This assert fires in debug
// builds, making any future regression visible at the earliest point.
debug_assert_eq!(
self.engine.pending_delta_count(),
0,
"stale engine deltas at log_then_apply_with entry — \
a previous apply arm may have accumulated deltas before erroring; \
the caller must drain_deltas() on any error path before returning"
);
let frame = encode_record(&rec);
self.fs.append(FileId::Wal, &frame)?;
// The cursor advances by exactly the bytes appended: these frames are
// ours and already applied, so a later refresh must not replay them.
self.wal_consumed += frame.len() as u64;
if Self::wal_needs_sync(policy, &rec) {
self.fs.sync(FileId::Wal)?;
}
// Marker writing always needs the engine deltas, but the engine only
// accumulates them when emit_deltas is true (normally gated on subscribers
// or views being present). Enable emission for this apply if it is
// currently off, then restore the original state unconditionally via an
// RAII guard — this prevents a panic in apply() from leaking the flag.
// The same guard resets the engine's transient chaining state. A panic
// unwinding out of a rule hook would otherwise leave `chain_depth`
// non-zero, which makes every later `begin_chain` decide chaining is
// already running and silently switch it off for good.
struct RestoreEmitDeltas(*mut RuleEngine, bool);
impl Drop for RestoreEmitDeltas {
fn drop(&mut self) {
// SAFETY: pointer into self (GraphDb); guard is dropped within
// this frame before log_then_apply_with returns.
unsafe {
(*self.0).set_emit_deltas(self.1);
(*self.0).reset_chain_state();
}
}
}
let original_emit = self.engine.emit_deltas();
if !original_emit {
self.engine.set_emit_deltas(true);
}
// SAFETY: raw pointer into self; guard dropped within this frame.
let _emit_guard = RestoreEmitDeltas(&mut self.engine as *mut _, original_emit);
let apply_result = self.apply(&rec);
// For Batch frames, post-validation apply must be infallible (see above).
// A debug_assert here catches any future change that makes apply fallible
// before the caller notices via silent WAL/memory divergence.
if matches!(&rec, WalRecord::Batch(_)) {
debug_assert!(
apply_result.is_ok(),
"Batch apply returned Err after successful WAL write — \
the validate-then-apply invariant has been violated; \
see log_then_apply_with invariant doc"
);
}
if apply_result.is_err() {
// Discard any partial deltas accumulated by the failed apply.
// They must not ride the next commit's event stream (I-1).
// _emit_guard restores emit_deltas on drop automatically.
let _ = self.engine.drain_deltas();
let _ = self.engine.take_rebuild_needed();
apply_result?;
}
self.commit_seq += 1;
let seq = self.commit_seq;
// Update per-node last-change map for the committed record.
// Must happen after commit_seq is incremented so the seq is correct.
self.update_last_change_from_rec(&rec, seq);
// Drain engine deltas and distribute to subscribers before the existing
// MutationEvent sink fires — both happen post-fsync, post-apply.
// _emit_guard restores emit_deltas after this line when it drops.
let engine_deltas = self.engine.drain_deltas();
// Append history-marker WAL records for any derived-edge changes so
// that `edge_history` and `was_linked` can surface rule-attributed
// events. Markers are STATE NO-OPS during replay; they are written
// without an additional fsync (the triggering commit's sync already
// happened; the next commit's sync covers these lazily).
if !engine_deltas.is_empty() {
let markers: Vec<WalRecord> = engine_deltas
.iter()
.map(|d| {
if d.fired {
WalRecord::DerivedEdgeAdded {
rule: d.rule.clone(),
edge_type: d.edge_type.clone(),
src_key: d.src_key.clone(),
dst_key: d.dst_key.clone(),
}
} else {
WalRecord::DerivedEdgeRetracted {
rule: d.rule.clone(),
edge_type: d.edge_type.clone(),
src_key: d.src_key.clone(),
dst_key: d.dst_key.clone(),
}
}
})
.collect();
let marker_frame = if markers.len() == 1 {
markers.into_iter().next().unwrap()
} else {
WalRecord::Batch(markers)
};
// Ignore append errors: markers are best-effort history
// annotations. Losing them does not affect state correctness.
// The cursor only advances when the bytes actually landed.
let marker_bytes = encode_record(&marker_frame);
if self.fs.append(FileId::Wal, &marker_bytes).is_ok() {
self.wal_consumed += marker_bytes.len() as u64;
}
}
// Record MVCC CommitDelta for the epoch reader. The WAL record is
// stored as-is (including any nested Batch / Intern records); the
// ReaderSnapshot's apply_one function handles all variants.
{
let derived_inserts = engine_deltas
.iter()
.filter(|d| d.fired)
.map(|d| (d.etype_sym, d.src_id, d.dst_id))
.collect();
let derived_deletes = engine_deltas
.iter()
.filter(|d| !d.fired)
.map(|d| (d.etype_sym, d.src_id, d.dst_id))
.collect();
let delta = Arc::new(crate::reader::CommitDelta {
records: vec![rec.clone()],
derived_inserts,
derived_deletes,
});
self.delta_tail.push(delta);
self.commits_since_fold += 1;
if self.commits_since_fold >= crate::reader::FOLD_EVERY_K {
self.fold_now();
}
}
if self.defer_events {
// Group-commit drain thread: hold events until after the group
// fsync so subscribers only observe durable data (R2).
self.deferred_events.push(DeferredEvent {
rec: rec.clone(),
engine_deltas,
seq,
ingest,
});
} else {
self.distribute_events(&rec, &engine_deltas, seq);
self.emit_committed(&rec, ingest);
}
// Drift is only known after apply, so auto-rebuild cannot join the
// triggering op's WAL frame. Issue RebuildRule as a second commit.
// Skip when `rec` is itself RebuildRule: rebuild resets drift, so a
// retrigger loop is impossible if the fit succeeded, but we still
// drain the flag so a leftover cannot re-enter.
// One slice of any outstanding vector-index build rides here too, so a
// store that is being written to finishes its build without anyone
// calling `pump_index_build`. A rule that becomes whole joins the same
// RebuildRule loop below.
let mut rebuilds = self.engine.take_rebuild_needed();
if !matches!(&rec, WalRecord::RebuildRule { .. }) {
// Not after `CreateRule`: that record's own apply already did the
// rule's first slice, and pumping again here would make one
// `create_rule` call do two slices' work under one lock.
// Nothing pending is the overwhelmingly common case and must cost
// a map lookup, not an engine swap: a store being written to has
// long since populated its indexes, so the `pump_index_build`
// entry point owns the not-yet-populated case on its own.
if !matches!(&rec, WalRecord::CreateRule { .. })
&& !self.engine.builds_in_progress().is_empty()
{
rebuilds.extend(self.pump_one_slice().into_iter().map(|b| b.rule));
}
let mut failed = Vec::new();
for name in rebuilds {
if self.engine.rules().any(|r| r.name == name) {
// User op is already durable. A failed second commit must
// not surface as the caller's error.
if let Err(e) =
self.log_then_apply(WalRecord::RebuildRule { name: name.clone() })
{
eprintln!(
"auto-rebuild of rule {name:?} failed after durable user commit: {e}"
);
failed.push(name);
}
}
}
for name in failed {
self.engine.queue_rebuild_needed(name);
}
}
Ok(())
}
/// Install a post-commit hook. Replaces any previous sink.
///
/// The sink runs inside `log_then_apply` after a successful
/// durable commit, while the caller still holds `&mut self`. When this
/// database is behind a [`crate::SharedDb`], that means the **write
/// guard is held**. The sink must never call `read` / `write` (or any
/// other method) on the same `SharedDb` — the `RwLock` is not
/// re-entrant and doing so deadlocks. The sink is `Send + Sync`;
/// `std::sync::mpsc::Sender` is not `Sync` and will not type-check.
/// Intended examples: `std::sync::mpsc::SyncSender`,
/// `tokio::sync::mpsc::Sender`, `tokio::sync::broadcast::Sender`
/// (non-blocking `send`), or `Arc<Mutex<Vec<MutationEvent>>>`.
pub fn set_event_sink(&mut self, sink: Box<dyn Fn(MutationEvent) + Send + Sync>) {
self.event_sink = Some(sink);
}
/// Whether a post-commit event sink is currently installed.
pub fn has_event_sink(&self) -> bool {
self.event_sink.is_some()
}
/// Set WAL fsync cadence. Default [`FsyncPolicy::Strict`].
pub fn set_fsync_policy(&mut self, p: FsyncPolicy) {
self.fsync = p;
}
/// Return the current WAL fsync cadence.
pub fn fsync_policy(&self) -> FsyncPolicy {
self.fsync
}
// ── Group-commit event deferral ───────────────────────────────────────────
/// Enable or disable deferred event mode.
///
/// When `true`, event notifications (subscription `DbEvent`s and legacy
/// `MutationEvent` sink calls) are buffered rather than fired immediately.
/// Call [`flush_deferred_events`] after the group fsync to deliver them,
/// or [`discard_deferred_events`] if the fsync failed and the group must
/// be treated as lost.
pub fn set_deferred_events_mode(&mut self, defer: bool) {
self.defer_events = defer;
}
/// Fire all buffered events accumulated since [`set_deferred_events_mode`]
/// was set to true. Clears the buffer.
///
/// Called by the drain thread AFTER a successful group fsync, so
/// subscribers observe only data that is durably on disk.
pub fn flush_deferred_events(&mut self) {
let events = std::mem::take(&mut self.deferred_events);
for de in events {
self.distribute_events(&de.rec, &de.engine_deltas, de.seq);
self.emit_committed(&de.rec, de.ingest);
}
}
/// Discard all buffered events without firing them.
///
/// Called by the drain thread when a group fsync fails: the WAL has been
/// truncated back to the pre-group offset, so the committed-but-unsynced
/// ops must not be observable to subscribers.
pub fn discard_deferred_events(&mut self) {
self.deferred_events.clear();
}
// ── Degraded state ────────────────────────────────────────────────────────
/// Mark this database as degraded.
///
/// Called by the group-commit drain thread after a group fsync failure and
/// WAL truncation: the in-memory state is now ahead of the on-disk WAL, so
/// further mutations would deepen the divergence. All subsequent calls to
/// [`log_then_apply_with`] return `Err` until the database is reopened.
pub fn set_degraded(&mut self) {
self.degraded = true;
}
fn emit(&self, ev: MutationEvent) {
if let Some(sink) = &self.event_sink {
sink(ev);
}
}
fn emit_committed(&self, rec: &WalRecord, ingest: Option<(String, usize)>) {
match rec {
WalRecord::Batch(inner) => {
for r in inner {
if let Some(ev) = event_from_record(r, &self.syms, &self.ids) {
self.emit(ev);
}
}
match ingest {
Some((label, inserted)) => {
self.emit(MutationEvent::Ingested { label, inserted })
}
None => {
let ops = inner
.iter()
.filter(|r| !matches!(r, WalRecord::Intern { .. }))
.count();
if ops > 1 {
self.emit(MutationEvent::BatchApplied { ops });
}
}
}
}
other => {
if let Some(ev) = event_from_record(other, &self.syms, &self.ids) {
self.emit(ev);
}
}
}
}
// -----------------------------------------------------------------------
// Subscription API
// -----------------------------------------------------------------------
/// Distribute post-commit events to all live subscribers.
///
/// Build a row-key → row-data map from a [`ResultSet`].
///
/// Each row is serialized to JSON to form its key; a debug fallback is used
/// if serialization fails. Used by both the initial-seed path in
/// [`Self::subscribe_query`] and the per-commit diff path in
/// [`Self::distribute_events`] to keep the two in sync.
fn result_to_row_map(
result: &core_query::ResultSet,
) -> std::collections::HashMap<String, Vec<Option<Value>>> {
(0..result.len())
.map(|i| {
let row = result.row(i).to_vec();
let key = serde_json::to_string(&row).unwrap_or_else(|_| format!("{row:?}"));
(key, row)
})
.collect()
}
/// Collect the set of label syms touched by a WAL record.
///
/// Returns `Some(set)` when every record in this commit can be attributed to
/// a known label sym. Returns `None` when the commit must not be skipped:
/// edge records, unresolvable key→label lookups, or any record type not in
/// the explicit handled set.
///
/// Handled record types and their actions:
/// - `InsertNode` → look up label in interner (fails → None)
/// - `InsertNodeId` → label sym is carried directly
/// - `SetProp` → resolve key→id→label (fails → None)
/// - `DeleteNode` → resolve key→id→label (fails → None)
/// - `Batch` → recurse into every inner record
/// - `InsertEdge`, `DeleteEdge`, `InsertEdgeId` → always None (edge records)
/// - everything else → None (conservative)
fn commit_touched_labels(
rec: &WalRecord,
syms: &Interner,
ids: &IdMap,
labels: &[u32],
) -> Option<BTreeSet<u32>> {
let mut out = BTreeSet::new();
if Self::collect_touched_labels(rec, syms, ids, labels, &mut out) {
Some(out)
} else {
None
}
}
fn collect_touched_labels(
rec: &WalRecord,
syms: &Interner,
ids: &IdMap,
labels: &[u32],
out: &mut BTreeSet<u32>,
) -> bool {
match rec {
// String-key insert: the dense rewrite converts this to
// [Intern, InsertNodeId], so this arm fires only for legacy WAL
// records written before the dense path was added.
WalRecord::InsertNode { label, .. } => {
if let Some(sym) = syms.get(label) {
out.insert(sym);
true
} else {
false
}
}
// Dense-id insert (produced by rewrite_wal_dense for every
// insert_node call in the current codebase).
WalRecord::InsertNodeId { label, .. } => {
out.insert(*label);
true
}
// String-key prop set: dense path converts to [Intern, SetPropId].
WalRecord::SetProp { key, .. } => {
if let Some(sym) = Self::resolve_key_label_sym(key, ids, labels) {
out.insert(sym);
true
} else {
false
}
}
// Dense-id prop set (produced by rewrite_wal_dense for set_prop).
WalRecord::SetPropId { id, .. } => {
if let Some(sym) = labels.get(*id as usize).copied().filter(|&s| s != u32::MAX) {
out.insert(sym);
true
} else {
false
}
}
WalRecord::DeleteNode { key } => {
if let Some(sym) = Self::resolve_key_label_sym(key, ids, labels) {
out.insert(sym);
true
} else {
false
}
}
WalRecord::Batch(inner) => inner
.iter()
.all(|r| Self::collect_touched_labels(r, syms, ids, labels, out)),
// Intern is a pure metadata record — it does not touch any node's
// label and is safe to skip for the label-skip predicate.
WalRecord::Intern { .. } => true,
// Edge records: always re-execute (edges can change join results).
WalRecord::InsertEdge { .. }
| WalRecord::DeleteEdge { .. }
| WalRecord::InsertEdgeId { .. } => false,
_ => false,
}
}
/// Resolve a node key to its label sym via the dense id table.
/// Returns `None` if the key is unknown or the label is a tombstone sentinel.
fn resolve_key_label_sym(key: &str, ids: &IdMap, labels: &[u32]) -> Option<u32> {
let id = ids.get(key)?;
let sym = labels.get(id as usize).copied()?;
(sym != u32::MAX).then_some(sym)
}
/// Distribute post-commit events to all live subscribers.
///
/// Called from `log_then_apply_with` after apply + fsync, before the
/// legacy MutationEvent sink. Prunes dead `Weak` entries in-place.
///
/// Query subscriptions (subscribe_query) re-execute their plan on every
/// call and diff the result against the previous run. Zero overhead when
/// no query subscriptions are active.
fn distribute_events(&mut self, rec: &WalRecord, engine_deltas: &[EngineEdgeDelta], seq: u64) {
if self.subscriptions.is_empty() && self.query_subscriptions.is_empty() {
return;
}
if !self.subscriptions.is_empty() {
// Build write events from the WAL record.
let write_events: Vec<DbEvent> =
Self::write_events_from_record(rec, seq, &self.syms, &self.ids);
// Build edge events from engine deltas. Weight is looked up from
// edge_props at distribution time (after apply), so it's always fresh.
let edge_events: Vec<DbEvent> = engine_deltas
.iter()
.map(|d| {
if d.fired {
// The score lives under the rule's declared weight_prop,
// which is not always the literal "weight".
let prop = self
.engine
.rules()
.find(|r| r.name == d.rule)
.and_then(|r| r.weight_prop.as_deref());
let weight = prop.and_then(|p| {
self.edge_props
.get(d.etype_sym, d.src_id, d.dst_id, p)
.and_then(|v| {
if let core_storage::Value::Float(f) = v {
Some(*f)
} else {
None
}
})
});
DbEvent::EdgeFired {
rule: d.rule.clone(),
src_key: d.src_key.clone(),
dst_key: d.dst_key.clone(),
edge_type: d.edge_type.clone(),
weight,
commit_seq: seq,
}
} else {
DbEvent::EdgeRetracted {
rule: d.rule.clone(),
src_key: d.src_key.clone(),
dst_key: d.dst_key.clone(),
edge_type: d.edge_type.clone(),
commit_seq: seq,
}
}
})
.collect();
// Prune dead entries; push matching events to live ones.
self.subscriptions.retain(|entry| {
let Some(inner) = entry.inner.upgrade() else {
return false;
};
for ev in &write_events {
if event_matches(ev, &entry.filter) {
inner.push(ev.clone());
}
}
for ev in &edge_events {
if event_matches(ev, &entry.filter) {
inner.push(ev.clone());
}
}
true
});
// Turn off delta accumulation if all subscribers dropped and no views remain.
if self.subscriptions.is_empty() && self.view_store.is_empty() {
self.engine.set_emit_deltas(false);
}
}
// Query subscriptions: full re-run per commit, then diff rows.
// IMPORTANT: full re-execution on every commit — use LIMIT to bound cost.
// Differential evaluation is roadmap / Phase 5.
if !self.query_subscriptions.is_empty() {
// Take the list out so we can call self.view() without borrow conflict.
let mut query_subs = std::mem::take(&mut self.query_subscriptions);
let empty_params = BTreeMap::new();
query_subs.retain_mut(|entry| {
let Some(inner) = entry.inner.upgrade() else {
return false; // subscriber dropped — prune
};
// Label-skip: if the plan has a known scan label and this commit
// can be proven to touch only different labels (and no rule-derived
// edge deltas fired), the result set cannot have changed — skip.
if let Some(scan_sym) = entry.scan_label {
if engine_deltas.is_empty() {
let touched =
Self::commit_touched_labels(rec, &self.syms, &self.ids, &self.labels);
if touched.map(|t| !t.contains(&scan_sym)).unwrap_or(false) {
return true; // safe to skip — result set unchanged
}
}
}
QUERY_SUB_EXECS_TL.with(|c| c.set(c.get() + 1));
let result = match execute(&self.view(), &entry.ops, &Params(&empty_params)) {
Ok(r) => r,
Err(e) => {
// Keep the subscription alive; skip the diff for this commit.
// Re-run errors are transient (e.g., planner change) and
// self-heal when the next commit succeeds.
eprintln!("[mushroomdb] subscribe_query re-run failed: {e}");
return true;
}
};
// Build new row map: serialized-key → row data.
let new_row_map = Self::result_to_row_map(&result);
// Removed rows: in prev but not in new.
for (key, row) in &entry.prev_row_map {
if !new_row_map.contains_key(key) {
inner.push(DbEvent::QueryRowRemoved {
columns: entry.columns.clone(),
row: row.clone(),
});
}
}
// Added rows: in new but not in prev.
for (key, row) in &new_row_map {
if !entry.prev_row_map.contains_key(key) {
inner.push(DbEvent::QueryRowAdded {
columns: entry.columns.clone(),
row: row.clone(),
});
}
}
entry.prev_row_map = new_row_map;
true
});
self.query_subscriptions = query_subs;
}
}
/// Returns `true` if any live subscriber or view definition requires delta
/// accumulation. Used to set `engine.emit_deltas` on subscribe/view DDL.
fn needs_emit_deltas(&self) -> bool {
!self.view_store.is_empty()
|| self
.subscriptions
.iter()
.any(|e| e.inner.upgrade().is_some())
}
/// Convert a WAL record into `DbEvent` write events with the given seq.
fn write_events_from_record(
rec: &WalRecord,
seq: u64,
intern: &Interner,
ids: &IdMap,
) -> Vec<DbEvent> {
match rec {
WalRecord::InsertNode { label, key, .. } => vec![DbEvent::NodeInserted {
label: label.clone(),
key: key.clone(),
commit_seq: seq,
}],
// *Id arms run after a successful apply, so resolution can only
// fail on a programming error. Skip the event rather than emit a
// fabricated "" that clients can't tell from a real empty value
// (mirrors event_from_record returning None).
WalRecord::InsertNodeId { label, key, .. } => intern
.resolve(*label)
.map(|label| DbEvent::NodeInserted {
label: label.to_string(),
key: key.clone(),
commit_seq: seq,
})
.into_iter()
.collect(),
WalRecord::SetProp { key, field, .. } => vec![DbEvent::PropSet {
key: key.clone(),
field: field.clone(),
commit_seq: seq,
}],
WalRecord::SetPropId { id, field, .. } => ids
.key_of(*id)
.zip(intern.resolve(*field))
.map(|(key, field)| DbEvent::PropSet {
key: key.to_string(),
field: field.to_string(),
commit_seq: seq,
})
.into_iter()
.collect(),
WalRecord::RemoveProp { key, field } => vec![DbEvent::PropRemoved {
key: key.clone(),
field: field.clone(),
commit_seq: seq,
}],
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => vec![DbEvent::EdgeInserted {
edge_type: edge_type.clone(),
src: src_key.clone(),
dst: dst_key.clone(),
commit_seq: seq,
}],
WalRecord::InsertEdgeId { etype, src, dst } => (|| {
Some(DbEvent::EdgeInserted {
edge_type: intern.resolve(*etype)?.to_string(),
src: ids.key_of(*src)?.to_string(),
dst: ids.key_of(*dst)?.to_string(),
commit_seq: seq,
})
})()
.into_iter()
.collect(),
WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
} => vec![DbEvent::EdgeDeleted {
edge_type: edge_type.clone(),
src: src_key.clone(),
dst: dst_key.clone(),
commit_seq: seq,
}],
WalRecord::DeleteNode { key } => vec![DbEvent::NodeDeleted {
key: key.clone(),
commit_seq: seq,
}],
WalRecord::Batch(inner) => inner
.iter()
.flat_map(|r| Self::write_events_from_record(r, seq, intern, ids))
.collect(),
WalRecord::CreateRule { .. }
| WalRecord::DeleteRule { .. }
| WalRecord::RebuildRule { .. }
| WalRecord::CreateView { .. }
| WalRecord::DeleteView { .. }
| WalRecord::EnableFulltext { .. }
| WalRecord::DisableFulltext { .. }
| WalRecord::EnableIndex { .. }
| WalRecord::DisableIndex { .. }
| WalRecord::Intern { .. }
// History markers produce no DbEvent — the engine delta already
// fired the EdgeFired/EdgeRetracted subscription events.
| WalRecord::DerivedEdgeAdded { .. }
| WalRecord::DerivedEdgeRetracted { .. }
| WalRecord::RenameNode { .. } => vec![],
}
}
/// Subscribe to edge-fire and edge-retract events for one named rule.
///
/// Returns `Err(GraphError::RuleNotFound)` if `rule_name` is not
/// currently registered. Dropping the returned [`Subscription`] handle
/// unregisters the subscriber — no further events are queued, no
/// resources leak.
pub fn subscribe_rule(&mut self, rule_name: &str) -> core_storage::Result<Subscription> {
if self.read_only {
return Err(core_storage::GraphError::ReadOnly);
}
if !self.engine.rules().any(|r| r.name == rule_name) {
return Err(core_storage::GraphError::RuleNotFound {
name: rule_name.to_string(),
});
}
let inner = SubInner::new(self.sub_capacity());
self.subscriptions.push(SubEntry {
filter: SubFilter::Rule(rule_name.to_string()),
inner: std::sync::Arc::downgrade(&inner),
});
self.engine.set_emit_deltas(true);
Ok(Subscription(inner))
}
/// Subscribe to edge-fire and edge-retract events for **all** rules.
///
/// Returns `Err(GraphError::ReadOnly)` if called on an as-of instance —
/// as-of instances never commit, so `distribute_events` never runs and the
/// subscription would never deliver events.
pub fn subscribe_all_rules(&mut self) -> core_storage::Result<Subscription> {
if self.read_only {
return Err(core_storage::GraphError::ReadOnly);
}
let inner = SubInner::new(self.sub_capacity());
self.subscriptions.push(SubEntry {
filter: SubFilter::AllRules,
inner: std::sync::Arc::downgrade(&inner),
});
self.engine.set_emit_deltas(true);
Ok(Subscription(inner))
}
/// Subscribe to write events: node insert/delete, prop set/remove.
///
/// Does not include edge-fire / edge-retract (rule-derived edge events).
///
/// Returns `Err(GraphError::ReadOnly)` if called on an as-of instance —
/// as-of instances never commit, so `distribute_events` never runs and the
/// subscription would never deliver events.
pub fn subscribe_writes(&mut self) -> core_storage::Result<Subscription> {
if self.read_only {
return Err(core_storage::GraphError::ReadOnly);
}
let inner = SubInner::new(self.sub_capacity());
self.subscriptions.push(SubEntry {
filter: SubFilter::Writes,
inner: std::sync::Arc::downgrade(&inner),
});
self.engine.set_emit_deltas(true);
Ok(Subscription(inner))
}
/// Subscribe to incremental Cypher query results.
///
/// Parses and plans `cypher`; rejects the query if the plan is not in the
/// allowlisted subset (see [`core_query::cypher::is_subscribable`]):
/// - `MATCH (n:Label) WHERE … RETURN … [LIMIT n]`
/// - `MATCH (a)-[r:TYPE]->(b) RETURN … [LIMIT n]` (exactly one hop)
///
/// SKIP is not supported — it shifts the result window on every commit,
/// causing spurious Added/Removed churn for rows whose data never changed.
/// Multi-hop Expand chains are not supported; each additional MATCH clause
/// widens scope beyond the documented single-scan / single-hop subset.
///
/// After each successful commit, the plan is **fully re-executed** and the
/// result is diffed against the previous run. Added rows produce
/// [`DbEvent::QueryRowAdded`]; removed rows produce
/// [`DbEvent::QueryRowRemoved`].
///
/// **Full re-run per commit; use LIMIT to bound execution cost.**
/// The existing 1 M intermediate-row cap applies. Differential evaluation
/// is roadmap / Phase 5.
///
/// Returns `Err(GraphError::ReadOnly)` if called on an as-of instance —
/// as-of instances never commit, so `distribute_events` never runs and the
/// subscription would never deliver events.
///
/// Returns `Err(GraphError::QueryError)` if the query fails to parse, plan,
/// or if the plan shape is not in the allowlist.
pub fn subscribe_query(&mut self, cypher: &str) -> Result<Subscription> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
let tokens = lex(cypher).map_err(|e| GraphError::QueryError {
detail: format!("lex: {e}"),
})?;
let ast = parse(&tokens).map_err(|e| GraphError::QueryError {
detail: format!("parse: {e}"),
})?;
let ops = plan(&ast).map_err(|e| GraphError::QueryError {
detail: format!("plan: {e}"),
})?;
if !is_subscribable(&ops) {
return Err(GraphError::QueryError {
detail: "subscribe_query only supports allowlisted plan shapes: \
MATCH (n:Label) WHERE … RETURN … [LIMIT n] or \
MATCH (a)-[r:TYPE]->(b) RETURN … [LIMIT n] (exactly one hop). \
Not supported: multi-hop Expand chains, SKIP (creates \
unstable offset windows), ORDER BY, DISTINCT, aggregates, \
variable-length paths, OPTIONAL MATCH, WITH, UNWIND. \
Use LIMIT to bound re-execution cost."
.to_string(),
});
}
// Execute once to capture initial state (initial rows are not emitted as
// events — the subscriber learns the baseline via the first query call).
let empty_params = BTreeMap::new();
let initial = execute(&self.view(), &ops, &Params(&empty_params)).map_err(|e| {
GraphError::QueryError {
detail: format!("execute: {e}"),
}
})?;
let columns = initial.columns().to_vec();
let prev_row_map = Self::result_to_row_map(&initial);
let inner = SubInner::new(self.sub_capacity());
// Derive the scan-label sym for the commit-skip fast-path. Any Expand op
// or unrecognized leading scan → None (always re-execute).
let scan_label = extract_scan_label(&ops, &mut self.syms);
self.query_subscriptions.push(QuerySubEntry {
ops,
columns,
prev_row_map,
inner: std::sync::Arc::downgrade(&inner),
scan_label,
});
Ok(Subscription(inner))
}
/// Queue capacity used for new subscriptions.
fn sub_capacity(&self) -> usize {
self.sub_capacity
}
/// Override per-subscriber queue capacity for subsequently created
/// subscriptions on this db instance.
///
/// Default is [`DEFAULT_SUB_CAPACITY`] (65,536 events). Use a smaller
/// value in tests to exercise the [`DbEvent::Lagged`] path without
/// generating tens of thousands of events.
///
/// This is a test-support escape hatch. Calling it in production reduces
/// subscriber reliability (more Lagged events). It is hidden from rustdoc
/// to discourage accidental production use.
#[doc(hidden)]
pub fn set_sub_capacity(&mut self, capacity: usize) {
self.sub_capacity = capacity;
}
// -----------------------------------------------------------------------
/// Start an atomic batch.
///
/// The returned [`BatchBuilder`] borrows `self` mutably until
/// [`BatchBuilder::commit`]. Builder methods queue ops only — no
/// validation, no WAL I/O. `commit` validates every queued op against
/// live state plus preceding ops in this batch (duplicate key inside
/// the batch is `Err`; an edge between two nodes created earlier in
/// the batch is valid; `delete_node` then insert of the same key is a
/// fresh identity). Validation never mutates the database. Any failure
/// leaves WAL bytes and in-memory state identical to before `commit`.
/// On success, one `WalRecord::Batch` frame is appended (one fsync)
/// and each inner record is applied in order so rules fire per record.
/// An empty batch, or a batch of only no-ops, writes zero WAL bytes.
///
/// **Rule-window limitation:** batch validation cannot see edges that a
/// rule created earlier in the *same* batch will derive at apply time, so
/// a `delete_edge` / `insert_edge` in that window is silently no-oped
/// where sequential calls would return `Err(RuleOwned)`. State integrity
/// is unaffected (idempotent apply, provenance intact). Create rules in
/// their own batch, or sequentially, when later ops may touch derived
/// edges.
pub fn batch(&mut self) -> BatchBuilder<'_, F> {
BatchBuilder {
db: self,
ops: Vec::new(),
}
}
/// Closure-style atomic write batch.
///
/// Equivalent to calling [`GraphDb::batch`], invoking `build` to queue ops,
/// then committing. All ops queued inside `build` are validated in order and
/// committed as a single `WalRecord::Batch` frame (one fsync). Rules fire
/// once per inner record, in order, after commit — semantically identical to
/// sequential single-op writes.
///
/// **Error semantics — validate-then-apply.** `build` queues ops without
/// touching the database. [`BatchBuilder::commit`] validates every op against
/// live state plus earlier ops in this batch before writing anything. If op N
/// fails validation (duplicate key, unknown key, rule-owned edge, …) the
/// entire batch is rejected: no WAL bytes are written and no in-memory state
/// changes. The database is identical to its state before `write_batch` was
/// called.
///
/// **Atomicity is crash-level, NOT isolation-level.** On replay after a crash,
/// a partial (torn) `Batch` frame applies NONE of its ops — the frame is
/// either fully applied or not at all. However, while applying a committed
/// batch, concurrent readers may observe intermediate states as ops are applied
/// sequentially in memory. There is no interactive transaction isolation in v1.
/// This is documented as "crash-atomic write batches; no interactive
/// transactions or read isolation."
///
/// **Returns** `(nodes_inserted, edges_inserted)`. An empty or all-noop batch
/// writes zero WAL bytes and returns `(0, 0)`.
///
/// # Example
///
/// ```rust,ignore
/// let (nodes, edges) = db.write_batch(|b| {
/// b.insert_node("Person", "alice", vec![("age".into(), Value::Int(30))]);
/// b.insert_node("Person", "bob", vec![]);
/// b.insert_edge("KNOWS", "alice", "bob");
/// b.set_prop("alice", "role", Value::Str("admin".into()));
/// b.delete_node("old_key");
/// })?;
/// // One fsync; on crash replay: all five ops land or none do.
/// ```
pub fn write_batch<C>(&mut self, build: C) -> Result<(usize, usize)>
where
C: FnOnce(&mut BatchBuilder<'_, F>),
{
let mut b = self.batch();
build(&mut b);
b.commit()
}
/// Insert `rows` as nodes of `label`. One call is one atomic batch:
/// auto-declared KeyMatch rules (if any) first, then the accepted node
/// inserts, so incremental fire sees the new rules. Per-row key problems
/// are collected in [`IngestReport::row_errors`] and skipped; a commit
/// `Err` means nothing was applied.
///
/// Auto-FK rule names are `auto_fk_<src_label_lowercase>_<field>` so
/// distinct source labels sharing an FK field each get their own rule.
pub fn ingest(
&mut self,
label: &str,
rows: Vec<BTreeMap<String, Value>>,
opts: &IngestOptions,
) -> Result<IngestReport> {
self.ingest_with_edges(label, rows, opts, &[])
}
/// [`ingest`] plus user edges in the **same** previewed WAL batch.
/// A failing edge rejects the whole request; nothing is applied.
pub fn ingest_with_edges(
&mut self,
label: &str,
rows: Vec<BTreeMap<String, Value>>,
opts: &IngestOptions,
edges: &[(String, String, String)],
) -> Result<IngestReport> {
crate::ingest::run(self, label, rows, opts, edges)
}
/// Parse `json` as an array of objects and ingest via [`GraphDb::ingest`].
///
/// JSON `null` fields are silently omitted (not stored, not a row error).
/// Nested objects and arrays-of-objects are a per-row error (row skipped).
/// Parse failures and a top-level value that is not an array of objects
/// return [`GraphError::IngestError`].
pub fn ingest_json(
&mut self,
label: &str,
json: &str,
opts: &IngestOptions,
) -> Result<IngestReport> {
crate::ingest::run_json(self, label, json, opts)
}
fn commit_logged_batch(
&mut self,
ops: Vec<BatchOp>,
ingest: Option<(String, usize)>,
// Two-source rule: write_batch_authz threads authz here directly (never
// touches pending_write_authz); query_write_authz sets the field instead
// and passes None. Only one source is non-None per call.
param_authz: Option<WriteAuthz>,
) -> Result<(usize, usize)> {
// Read-only guard: catches empty-batch calls before the early-return
// that skips log_then_apply_with, ensuring all mutation entry points fail.
if self.read_only {
return Err(GraphError::ReadOnly);
}
// Ensure provenance is decoded before MutPreview accesses it
// (note_delete_rule / is_rule_owned may call engine.provenance()).
self.engine.ensure_provenance_loaded_mut();
// ── Authz pre-check ──────────────────────────────────────────────────
// Evaluate the decision table per-op BEFORE MutPreview so that a denial
// produces no WAL frame (all-or-nothing at the authz boundary extends
// the existing validate-then-apply contract to role-scope checks).
//
// `batch_created` tracks key→label for nodes created by earlier ops in
// THIS batch, so InsertEdgeUpsert can count same-batch placeholder nodes
// as visible without needing to call `self.ids.get` on not-yet-committed
// keys (they won't be there yet).
//
// Two-source rule: param_authz (write_batch_authz path) takes precedence;
// fall back to self.pending_write_authz (query_write_authz/Cypher path).
// Cloning the field copy avoids a simultaneous borrow of self.ids below.
let authz_opt = param_authz.or_else(|| self.pending_write_authz.clone());
if let Some(ref authz) = authz_opt {
let mut batch_created: BTreeMap<String, String> = BTreeMap::new();
for op in &ops {
self.check_single_op_authz(authz, op, &batch_created)?;
// Update batch_created after a passing authz check so that
// subsequent ops in this batch see the nodes as "about to exist".
match op {
BatchOp::InsertNode { label, key, .. } => {
// Only track genuinely new nodes (absent from the
// snapshot at authz-check time). A pre-existing visible
// key would be a DuplicateKey — not a real creation —
// so MutPreview handles it. Letting it into batch_created
// would allow a later SetProp to bypass update_labels
// via the "batch-created → always updatable" ruling
// (delete+recreate exploit, fix for I1 review round 2).
//
// Accepted edge: for a delete+recreate-with-different-
// label batch, node_status resolves the pre-delete
// (store) label for any subsequent update checks. This
// grants no net-new capability — a role that can delete+
// create can already place arbitrary props via
// InsertNode's own props field.
if self.ids.get(key.as_str()).is_none() {
batch_created.insert(key.clone(), label.clone());
}
}
BatchOp::InsertEdgeUpsert {
placeholder_label,
src_key,
dst_key,
..
} => {
// Both endpoints will be created if not already in store.
for ep_key in [src_key, dst_key] {
if self.ids.get(ep_key.as_str()).is_none()
&& !batch_created.contains_key(ep_key.as_str())
{
batch_created.insert(ep_key.clone(), placeholder_label.clone());
}
}
}
_ => {}
}
}
}
let recs = {
let mut preview = MutPreview::new(self);
let mut recs = Vec::with_capacity(ops.len());
for op in ops {
match op {
BatchOp::InsertNode { label, key, props } => {
preview.check_insert_node(&key)?;
preview.note_insert_node(&key, &props);
recs.push(WalRecord::InsertNode { label, key, props });
}
BatchOp::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
if preview.prepare_insert_edge(&edge_type, &src_key, &dst_key)? {
preview.note_insert_edge(&edge_type, &src_key, &dst_key);
recs.push(WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
});
}
}
BatchOp::SetProp { key, field, value } => {
if let Some(view_name) = preview.db.view_store.view_for_prop(&field) {
return Err(GraphError::ViewPropReadOnly {
view_name: view_name.to_string(),
});
}
preview.check_live_key(&key)?;
preview.note_set_prop(&key, &field, &value);
recs.push(WalRecord::SetProp { key, field, value });
}
BatchOp::RemoveProp { key, field } => {
if preview.prepare_remove_prop(&key, &field)? {
preview.note_remove_prop(&key, &field);
recs.push(WalRecord::RemoveProp { key, field });
}
}
BatchOp::DeleteEdge {
edge_type,
src_key,
dst_key,
} => {
if preview.prepare_delete_edge(&edge_type, &src_key, &dst_key)? {
preview.note_delete_edge(&edge_type, &src_key, &dst_key);
recs.push(WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
});
}
}
BatchOp::DeleteNode { key } => {
preview.check_live_key(&key)?;
preview.note_delete_node(&key);
recs.push(WalRecord::DeleteNode { key });
}
BatchOp::CreateRule(def) => {
preview.check_create_rule(&def)?;
let def_bytes =
bincode::serialize(&def).map_err(|e| GraphError::Corrupt {
detail: format!("serialize rule: {e}"),
})?;
preview.note_create_rule(&def);
recs.push(WalRecord::CreateRule { def_bytes });
}
BatchOp::DeleteRule { name } => {
preview.check_delete_rule(&name)?;
preview.note_delete_rule(&name);
recs.push(WalRecord::DeleteRule { name });
}
BatchOp::RenameNode { old_key, new_key } => {
preview.check_rename_node(&old_key, &new_key)?;
preview.note_rename_node(&old_key, &new_key);
recs.push(WalRecord::RenameNode { old_key, new_key });
}
BatchOp::InsertEdgeUpsert {
edge_type,
src_key,
dst_key,
placeholder_label,
} => {
// Auto-create any missing endpoints as plain InsertNode ops.
// Rules fire and last-change is updated for each created node.
for key in [&src_key, &dst_key] {
if !preview.has_key(key) {
preview.check_insert_node(key)?;
preview.note_insert_node(key, &[]);
recs.push(WalRecord::InsertNode {
label: placeholder_label.clone(),
key: key.clone(),
props: vec![],
});
}
}
if preview.prepare_insert_edge(&edge_type, &src_key, &dst_key)? {
preview.note_insert_edge(&edge_type, &src_key, &dst_key);
recs.push(WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
});
}
}
}
}
recs
};
if recs.is_empty() {
return Ok((0, 0));
}
// rewrite_wal_dense converts every InsertNode/InsertEdge into its
// *Id form, so only the dense variants can appear in `recs` here.
let recs = self.rewrite_wal_dense(recs)?;
// The rewrite can empty a non-empty batch: a `SET n.ns` naming the
// namespace the node is already in is a no-op and is dropped there. An
// empty `Batch` frame would still take a commit sequence and a WAL
// record, so a batch that turns out to be nothing writes nothing.
if recs.is_empty() {
return Ok((0, 0));
}
let nodes_inserted = recs
.iter()
.filter(|r| matches!(r, WalRecord::InsertNodeId { .. }))
.count();
let edges_inserted = recs
.iter()
.filter(|r| matches!(r, WalRecord::InsertEdgeId { .. }))
.count();
// Ingest / write_batch / query_write: one Batch frame, one fsync per call
// under Strict. Pass self.fsync directly so Strict stays Strict —
// wal_needs_sync(Strict, _) always returns true regardless of op count.
// Mapping Strict → Batched (the prior bug) caused wal_needs_sync to
// short-circuit on single-op batches and silently skip the fsync.
// Batched fsyncs only for multi-op batches; Relaxed always skips.
self.log_then_apply_with(WalRecord::Batch(recs), ingest, self.fsync)?;
Ok((nodes_inserted, edges_inserted))
}
fn commit_batch(&mut self, ops: Vec<BatchOp>) -> Result<(usize, usize)> {
self.commit_logged_batch(ops, None, None)
}
/// Commit one submission WITHOUT an fsync — for use inside `commit_group`
/// and the group-commit drain thread, which do a single group fsync later.
fn commit_batch_nosync(&mut self, ops: Vec<BatchOp>) -> Result<(usize, usize)> {
// Restore fsync policy even on panic via a raw-pointer drop guard.
// A panic here would poison the RwLock anyway, but the correct policy
// must be in place if the guard is ever unwrapped.
struct RestoreFsync(*mut FsyncPolicy, FsyncPolicy);
impl Drop for RestoreFsync {
fn drop(&mut self) {
// SAFETY: the pointer is valid for the full duration of
// commit_batch_nosync; the guard is dropped before the frame
// returns, and GraphDb outlives this frame.
unsafe {
*self.0 = self.1;
}
}
}
let saved = self.fsync;
// SAFETY: raw pointer into self; guard dropped within this frame.
let _g = RestoreFsync(&mut self.fsync as *mut FsyncPolicy, saved);
self.fsync = FsyncPolicy::Relaxed;
self.commit_logged_batch(ops, None, None)
}
/// Commit multiple op-batches as a **group**: each submission gets its own
/// WAL `Batch` frame, but there is exactly **one** `Fs::sync` for the whole
/// group (under `Strict` / `Batched` policy; `Relaxed` skips all syncs).
///
/// # Durability semantics
///
/// A crash before the group fsync may lose **all** submissions in the group.
/// A crash after the group fsync preserves all of them. No submission is
/// ever torn: each WAL frame is either fully applied on replay or dropped
/// in its entirety (CRC-protected frame boundaries).
///
/// Events and subscription notifications fire per-submission immediately
/// after apply, which may be before the group fsync. From a subscriber's
/// perspective this is equivalent to the `Relaxed` durability window.
/// Submitters using [`SharedDb::submit_batch`] only unblock after the group
/// fsync, so from their perspective durability is fully guaranteed.
///
/// # MVCC interplay
///
/// Each submission records its own `CommitDelta`; the fold-every-K counter
/// increments per submission (not per group), preserving existing reader
/// snapshot semantics.
///
/// # Returns
///
/// One `Result<(nodes_inserted, edges_inserted)>` per input group element,
/// in order. Failures are per-submission (validation errors); the group
/// fsync error (if any) is returned as the second tuple element.
pub fn commit_group(
&mut self,
groups: Vec<Vec<BatchOp>>,
) -> (Vec<Result<(usize, usize)>>, Option<GraphError>) {
let mut results = Vec::with_capacity(groups.len());
for ops in groups {
results.push(self.commit_batch_nosync(ops));
}
let any_ok = results.iter().any(|r| r.is_ok());
let sync_err = if self.fsync != FsyncPolicy::Relaxed && any_ok {
self.fs
.sync(core_storage::fs::FileId::Wal)
.map_err(GraphError::Io)
.err()
} else {
None
};
(results, sync_err)
}
/// Like [`commit_group`] but skips the group fsync entirely.
///
/// Used by the drain thread to apply submissions under the write lock and
/// then perform the single fsync OUTSIDE the lock (via
/// `core_storage::sync_wal_at`), reducing the write-lock hold time visible
/// to concurrent readers.
pub fn commit_group_nosync(
&mut self,
groups: Vec<Vec<BatchOp>>,
) -> Vec<Result<(usize, usize)>> {
let mut results = Vec::with_capacity(groups.len());
for ops in groups {
results.push(self.commit_batch_nosync(ops));
}
results
}
pub fn insert_node(
&mut self,
label: &str,
key: &str,
props: Vec<(String, Value)>,
) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
MutPreview::new(self).check_insert_node(key)?;
self.log_dense(vec![WalRecord::InsertNode {
label: label.into(),
key: key.into(),
props,
}])
}
pub fn insert_edge(&mut self, edge_type: &str, src_key: &str, dst_key: &str) -> Result<bool> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if !MutPreview::new(self).prepare_insert_edge(edge_type, src_key, dst_key)? {
return Ok(false);
}
self.log_dense(vec![WalRecord::InsertEdge {
edge_type: edge_type.into(),
src_key: src_key.into(),
dst_key: dst_key.into(),
}])?;
Ok(true)
}
pub fn set_prop(&mut self, key: &str, field: &str, value: Value) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if let Some(view_name) = self.view_store.view_for_prop(field) {
return Err(GraphError::ViewPropReadOnly {
view_name: view_name.to_string(),
});
}
MutPreview::new(self).check_live_key(key)?;
self.log_dense(vec![WalRecord::SetProp {
key: key.into(),
field: field.into(),
value,
}])
}
/// Set several properties on one live node in a single WAL commit.
///
/// Every per-property check [`set_prop`](Self::set_prop) runs — view-owned
/// names, live key, the `ns` immutability rule and its type — is evaluated
/// for the whole list before any record is logged. The first refusal
/// returns and the node is unchanged. An empty list writes nothing.
pub fn set_props(&mut self, key: &str, props: Vec<(String, Value)>) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
MutPreview::new(self).check_live_key(key)?;
for (field, _) in &props {
if let Some(view_name) = self.view_store.view_for_prop(field) {
return Err(GraphError::ViewPropReadOnly {
view_name: view_name.to_string(),
});
}
}
if props.is_empty() {
return Ok(());
}
self.write_batch(|b| {
for (field, value) in props {
b.set_prop(key, &field, value);
}
})
.map(|_| ())
}
/// Remove a property. Returns `Ok(false)` (and does not log) if the field
/// is already absent. Unknown or tombstoned keys are `Err(KeyNotFound)`.
pub fn remove_prop(&mut self, key: &str, field: &str) -> Result<bool> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if let Some(view_name) = self.view_store.view_for_prop(field) {
return Err(GraphError::ViewPropReadOnly {
view_name: view_name.to_string(),
});
}
if !MutPreview::new(self).prepare_remove_prop(key, field)? {
return Ok(false);
}
self.log_then_apply(WalRecord::RemoveProp {
key: key.into(),
field: field.into(),
})?;
Ok(true)
}
/// Delete a user edge. Returns `Ok(false)` (and does not log) if the edge
/// is absent. Unknown keys are `Err(KeyNotFound)`. Rule-owned edges — in
/// provenance, or a pair a live rule would derive — are `Err(RuleOwned)`
/// (the rule would just put the edge back; delete or change the rule).
pub fn delete_edge(&mut self, edge_type: &str, src_key: &str, dst_key: &str) -> Result<bool> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if !MutPreview::new(self).prepare_delete_edge(edge_type, src_key, dst_key)? {
return Ok(false);
}
self.log_then_apply(WalRecord::DeleteEdge {
edge_type: edge_type.into(),
src_key: src_key.into(),
dst_key: dst_key.into(),
})?;
Ok(true)
}
/// Delete a live node. Unknown or already-tombstoned keys are
/// `Err(KeyNotFound)` and are not logged. Validation runs before the WAL
/// write; `apply` of a logged `DeleteNode` for an already-tombstoned key
/// (crash window) is a clean no-op.
///
/// Returns a [`DeleteReport`] with counts of manual and derived edges
/// removed (computed from live state before the deletion is applied).
pub fn delete_node(&mut self, key: &str) -> Result<DeleteReport> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
// Provenance must be loaded before we query provenance_touching.
self.engine.ensure_provenance_loaded_mut();
let id = self
.ids
.get(key)
.ok_or_else(|| GraphError::KeyNotFound { key: key.into() })?;
// Count edges before the delete is applied so we can report counts.
let derived_set: BTreeSet<(u32, u32, u32)> = self
.engine
.provenance_touching(id)
.map(|(_, etype, src, dst)| (etype, src, dst))
.collect();
let derived_edges = derived_set.len() as u64;
let mut total_topo = 0u64;
let tv = self.topo_view();
for et in tv.etypes() {
total_topo += tv.neighbors(et, Direction::Out, id).len() as u64
+ tv.neighbors(et, Direction::In, id).len() as u64;
}
// For symmetric rules (e.g. Overlap), a→b and b→a are two separate directed
// triples in both the topo scan (Out and In from id) and in provenance_touching.
// The subtraction remains correct because both counts include both directions.
let manual_edges = total_topo.saturating_sub(derived_edges);
self.log_then_apply(WalRecord::DeleteNode { key: key.into() })?;
Ok(DeleteReport {
manual_edges,
derived_edges,
})
}
/// Rename a live node's key. The dense id (and therefore all edges,
/// props, history, and last-change tracking) is unaffected.
///
/// Returns `Err(KeyNotFound)` if `old` is not a live key.
/// Returns `Err(DuplicateKey)` if `new` is already live.
pub fn rename_node(&mut self, old: &str, new: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
MutPreview::new(self).check_rename_node(old, new)?;
self.log_then_apply(WalRecord::RenameNode {
old_key: old.into(),
new_key: new.into(),
})
}
/// Return the IVF drift counter for the dst-side candidate index of `rule`.
/// `None` if the rule does not exist or is not approximate.
///
/// The drift counter increments on IVF insert/remove after the last fit.
/// When dst-side drift exceeds [`core_rules::IVF_DRIFT_REBUILD`], apply
/// WAL-logs `RebuildRule` as a second commit (rebuild resets the counter).
pub fn ivf_dst_drift(&self, rule: &str) -> Option<u64> {
// SideIvfExport = (centroids, node→cluster, drift)
self.engine
.export_ivf_state()
.remove(rule)
.map(|(_src, dst)| dst.2)
}
/// Validate and WAL-log a new rule, then backfill derived edges inside apply.
/// Validation and duplicate-name check run before logging so invalid rules
/// never enter the WAL.
pub fn create_rule(&mut self, def: RuleDef) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
MutPreview::new(self).check_create_rule(&def)?;
let def_bytes = bincode::serialize(&def).map_err(|e| GraphError::Corrupt {
detail: format!("serialize rule: {e}"),
})?;
self.log_then_apply(WalRecord::CreateRule { def_bytes })
}
/// Override this handle's HNSW build-slice size, or `None` to restore
/// [`core_rules::HNSW_BUILD_BATCH`].
///
/// Exposed for tests that need a small slice without a large corpus; not
/// part of the stable surface.
#[doc(hidden)]
pub fn set_hnsw_build_batch(&mut self, batch: Option<usize>) {
self.engine.set_hnsw_build_batch(batch);
}
/// Rules whose vector index is still being built, in name order.
///
/// The same list [`GraphDb::stats`] reports per rule in `building`.
/// After a clean open this includes a build a snapshot cut short, so
/// `serve`'s ticker can pump it without a write.
pub fn builds_in_progress(&self) -> Vec<BuildProgress> {
self.engine.builds_in_progress()
}
/// Advance any vector index still building and backfill each rule that
/// finishes. Returns what is still outstanding.
///
/// A map lookup when nothing is pending, so it is cheap to call on a timer.
/// One write lock and at most [`core_rules::HNSW_BUILD_BATCH`] vector
/// inserts per pending rule per call, so a caller can drive a large build
/// to completion without ever holding the lock for more than a slice.
///
/// A rule that finishes here is backfilled through the same
/// `WalRecord::RebuildRule` second commit that IVF drift already uses, so
/// its derived edges are produced by [`GraphDb::rebuild_rule`]'s code path
/// and appear all at once.
///
/// Every ordinary write pumps one slice on its own (see the post-commit
/// hook in `log_then_apply_with`), so this is for quiescent stores and for
/// operators who want the build finished before traffic arrives.
pub fn pump_index_build(&mut self) -> Result<Vec<BuildProgress>> {
Ok(self.pump_index_build_reporting()?.1)
}
/// [`GraphDb::pump_index_build`], also reporting the builds that **this**
/// call finished, so a progress display can say so.
///
/// A build can be registered and completed inside a single call — that is
/// what a mid-build snapshot looks like on reopen, where the index scan
/// finishes the graph and only the backfill is outstanding — and the
/// outstanding list alone cannot show that anything happened.
pub fn pump_index_build_reporting(
&mut self,
) -> Result<(Vec<BuildProgress>, Vec<BuildProgress>)> {
// A read-only handle cannot issue the `RebuildRule` a finished build
// needs, so it would advance the index and then silently fail to
// produce the edges. Refusing is the honest answer.
if self.read_only {
return Err(GraphError::ReadOnly);
}
let finished = self.pump_one_slice();
for done in &finished {
// The index is whole but the rule still owns no edges. A failed
// second commit must leave the rule re-pumpable rather than
// silently edge-less, so the error is surfaced here — unlike the
// post-commit hook, this call is not riding someone else's commit.
self.log_then_apply(WalRecord::RebuildRule {
name: done.rule.clone(),
})?;
}
Ok((finished, self.engine.builds_in_progress()))
}
/// Run the deferred candidate-index build, if it is still owed, against the
/// graph as it stands *now* — before the caller applies anything.
///
/// A no-op bool test once the indexes are populated, which is after the
/// first write of the handle's life, and for a store with no rules at all.
fn populate_indexes_before_write(&mut self) {
if !self.engine.needs_index_population() {
return;
}
// The retained snapshot blobs arrive with the V8 base sections; without
// them the scan would rebuild every graph the snapshot already holds.
self.ensure_v8_base_sections_loaded();
if !self.engine.needs_index_population() {
return;
}
let mut eng = std::mem::take(&mut self.engine);
{
let gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.populate_indexes(&gm);
}
self.engine = eng;
}
/// One slice of build work for every pending rule. Returns the rules whose
/// index just became whole, which the caller must `RebuildRule`.
///
/// Goes through the engine even with nothing pending when the indexes have
/// not been populated yet: that call adopts the persisted graphs and, for
/// an incomplete blob already registered at open, leaves the remainder to
/// this slice rather than inserting it inline.
fn pump_one_slice(&mut self) -> Vec<BuildProgress> {
// The retained snapshot blobs — and the id count an interrupted build
// is recognised against — arrive with the V8 base sections, which a
// clean open reads lazily. Without this a freshly opened handle pumps
// against empty retained state and concludes there is nothing to do,
// which is precisely the store `build-index` exists for.
self.ensure_v8_base_sections_loaded();
let mut eng = std::mem::take(&mut self.engine);
let finished = {
let mut gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.pump_index_build(&mut gm)
};
self.engine = eng;
finished
}
/// Register a sliced build a snapshot cut short, from blobs with
/// `complete == false`.
///
/// Peeks the V8 mmap for incomplete entries without copying complete
/// graphs. V5–V7 already hold the blobs in the engine from restore.
fn register_outstanding_index_builds(&mut self) {
if self.engine.indexes_populated() {
return;
}
let extra = self.collect_incomplete_hnsw_blobs();
let mut eng = std::mem::take(&mut self.engine);
{
let gm = make_graph_mut(
&self.ids,
&mut self.syms,
&self.labels,
build_props_view(&self.props, &self.base),
&mut self.topo,
&self.base,
&mut self.edge_props,
);
eng.register_incomplete_hnsw_builds(&extra, &gm);
}
self.engine = eng;
}
/// Incomplete `(src, dst)` HNSW blobs from the V8 mmap, copied only when
/// `complete` is false. Empty when there is no mmap base (V5–V7 uses the
/// engine's retained map instead).
fn collect_incomplete_hnsw_blobs(&self) -> BTreeMap<String, (Vec<u8>, Vec<u8>)> {
let Some(base) = &self.base else {
return BTreeMap::new();
};
let Ok(archived) = base.hnsw_section() else {
return BTreeMap::new();
};
archived
.rules
.iter()
.filter_map(|e| {
let src = e.src_blob.as_slice();
let dst = e.dst_blob.as_slice();
if core_rules::hnsw::hnsw_blob_complete(src) == Some(false)
|| core_rules::hnsw::hnsw_blob_complete(dst) == Some(false)
{
Some((e.name.as_str().to_string(), (src.to_vec(), dst.to_vec())))
} else {
None
}
})
.collect()
}
/// WAL-log rule deletion. Returns RuleNotFound if the rule does not exist.
pub fn delete_rule(&mut self, name: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
MutPreview::new(self).check_delete_rule(name)?;
self.log_then_apply(WalRecord::DeleteRule { name: name.into() })
}
/// Return a snapshot of all registered rules.
pub fn rules(&self) -> Vec<RuleDef> {
self.engine.rules().cloned().collect()
}
// -----------------------------------------------------------------------
// Rule suggestion API
// -----------------------------------------------------------------------
/// Profile the database and suggest linking rules with previewed edge counts.
///
/// Uses the default seed ([`core_rules::SUGGEST_DEFAULT_SEED`]) for deterministic
/// sampling. Suggestions are sorted by estimated edge count (descending).
/// **NO auto-accept** — call [`GraphDb::create_rule`] explicitly to apply.
pub fn suggest_rules(&self) -> Vec<core_rules::RuleSuggestion> {
self.suggest_rules_seeded(core_rules::SUGGEST_DEFAULT_SEED)
}
/// Like [`suggest_rules`] but with a caller-supplied RNG seed for
/// reproducibility. Same seed + same data = identical output.
pub fn suggest_rules_seeded(&self, seed: u64) -> Vec<core_rules::RuleSuggestion> {
self.suggest_rules_with_config(&core_rules::suggest::SuggestConfig::default(), seed)
.suggestions
}
/// [`suggest_rules_seeded`] with a fully custom [`SuggestConfig`].
///
/// Returns a [`core_rules::SuggestReport`] that includes both the candidate list
/// and a `truncated` flag indicating whether the global budget fired before all
/// candidates were evaluated.
pub fn suggest_rules_with_config(
&self,
config: &core_rules::suggest::SuggestConfig,
seed: u64,
) -> core_rules::SuggestReport {
use std::collections::BTreeMap;
// Collect (node_id, key) pairs per label, skipping tombstoned nodes.
let mut label_nodes: BTreeMap<String, Vec<(u32, String)>> = BTreeMap::new();
for id in 0..self.ids.len() as u32 {
let Some(key) = self.ids.key_of(id) else {
continue;
};
let Some(&sym) = self.labels.get(id as usize) else {
continue;
};
if sym == u32::MAX {
continue; // tombstoned
}
let Some(label) = self.syms.resolve(sym) else {
continue;
};
label_nodes
.entry(label.to_string())
.or_default()
.push((id, key.to_string()));
}
let existing = self.rules();
let pv = build_props_view(&self.props, &self.base);
let all_fields: Vec<String> = pv.field_names();
core_rules::suggest::suggest_rules(
&label_nodes,
&|id, field| pv.get(id, field).map(|vr| vr.into_value()),
&all_fields,
&existing,
config,
seed,
)
}
/// Recompute a rule's derived edges from scratch. WAL-logged so un-trip
/// plus later mutations replay identically (rebuild is a pure function
/// of state).
///
/// Only exit from the tripped latch: if the full desired set fits the
/// budget, it is applied completely and `tripped` clears; if it still
/// exceeds the budget, provenance is left untouched and `tripped` stays
/// true. Counts as a fire evaluation (see [`RuleStats::fires`]).
/// Unknown rule → `RuleNotFound`, nothing logged.
pub fn rebuild_rule(&mut self, name: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if !self.engine.rules().any(|r| r.name == name) {
return Err(GraphError::RuleNotFound { name: name.into() });
}
self.log_then_apply(WalRecord::RebuildRule { name: name.into() })
}
// -----------------------------------------------------------------------
// Materialized view API
// -----------------------------------------------------------------------
/// Register a new materialized property view, backfill its values for all
/// existing nodes, and WAL-log the definition.
///
/// # Errors
/// - `ReadOnly`: called on an as-of instance.
/// - `RuleInvalid`: name collision, view_prop collision, or invalid def.
pub fn create_view(&mut self, def: ViewDef) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
// Pre-validate before WAL write.
def.validate()
.map_err(|e| GraphError::RuleInvalid { detail: e })?;
if self.view_store.has_view(&def.name) {
return Err(GraphError::RuleInvalid {
detail: format!("view {:?} already exists", def.name),
});
}
if let Some(existing) = self.view_store.view_for_prop(&def.view_prop) {
return Err(GraphError::RuleInvalid {
detail: format!(
"view_prop {:?} is already used by view {:?}",
def.view_prop, existing
),
});
}
let def_bytes = bincode::serialize(&def).map_err(|e| GraphError::Corrupt {
detail: format!("serialize view: {e}"),
})?;
// Enable delta accumulation before the view is registered so subsequent
// incremental edge events reach view maintenance from this point onward.
// (The backfill inside create_view reads topo directly; it does not rely
// on pending deltas.)
self.engine.set_emit_deltas(true);
self.log_then_apply(WalRecord::CreateView { def_bytes })
}
/// Remove a named view and delete its values from every node.
///
/// # Errors
/// - `ReadOnly`: called on an as-of instance.
/// - `RuleNotFound`: view does not exist.
pub fn delete_view(&mut self, name: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if !self.view_store.has_view(name) {
return Err(GraphError::RuleNotFound { name: name.into() });
}
let result = self.log_then_apply(WalRecord::DeleteView { name: name.into() });
// After deletion, disable accumulation if no listeners remain.
if !self.needs_emit_deltas() {
self.engine.set_emit_deltas(false);
}
result
}
/// Snapshot of all registered view definitions.
pub fn views(&self) -> Vec<ViewDef> {
self.view_store.views().cloned().collect()
}
// -----------------------------------------------------------------------
// Full-text-lite API
// -----------------------------------------------------------------------
/// Enable full-text indexing for all nodes of `label` on property `field`.
///
/// After this call, every subsequent write to `(label, field)` is reflected
/// in the index incrementally. Existing nodes are backfilled immediately.
/// The declaration is persisted as a WAL record; the index itself is rebuilt
/// from scratch on re-open (no snapshot format changes).
///
/// # Errors
/// - [`GraphError::ReadOnly`]: called on an as-of instance.
/// - [`GraphError::RuleInvalid`]: `(label, field)` is already indexed.
pub fn enable_fulltext(&mut self, label: &str, field: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if self.fulltext.is_enabled(label, field) {
return Err(GraphError::RuleInvalid {
detail: format!("full-text index for ({label:?}, {field:?}) already enabled"),
});
}
self.log_then_apply(WalRecord::EnableFulltext {
label: label.into(),
field: field.into(),
})
}
/// Disable full-text indexing for `(label, field)` and drop its postings.
///
/// # Errors
/// - [`GraphError::ReadOnly`]: called on an as-of instance.
/// - [`GraphError::RuleNotFound`]: `(label, field)` is not currently indexed.
pub fn disable_fulltext(&mut self, label: &str, field: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if !self.fulltext.is_enabled(label, field) {
return Err(GraphError::RuleNotFound {
name: format!("fulltext({label},{field})"),
});
}
self.log_then_apply(WalRecord::DisableFulltext {
label: label.into(),
field: field.into(),
})
}
/// Whether `(label, field)` is currently indexed for full-text search.
pub fn is_fulltext_enabled(&self, label: &str, field: &str) -> bool {
self.fulltext.is_enabled(label, field)
}
/// Every `(label, field)` pair with a live full-text index, sorted.
///
/// Note that [`GraphDb::search`] is keyed by field alone — a pair only
/// declares which nodes are *indexed*, so callers that want to search
/// everything indexed should query each distinct field once.
pub fn fulltext_pairs(&self) -> Vec<(String, String)> {
let mut v: Vec<(String, String)> = self.fulltext.enabled_pairs().cloned().collect();
v.sort();
v
}
/// Enable an equality index for all nodes of `label` on scalar property
/// `field`. Subsequent `WHERE n.field = value` lookups become O(matches)
/// instead of an O(N_label) scan. Existing nodes are backfilled; the
/// declaration persists via WAL and the postings rebuild on re-open.
///
/// # Errors
/// - [`GraphError::ReadOnly`]: called on an as-of instance.
/// - [`GraphError::RuleInvalid`]: `(label, field)` is already indexed.
pub fn enable_index(&mut self, label: &str, field: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if self.prop_index.is_enabled(label, field) {
return Err(GraphError::RuleInvalid {
detail: format!("property index for ({label:?}, {field:?}) already enabled"),
});
}
self.log_then_apply(WalRecord::EnableIndex {
label: label.into(),
field: field.into(),
})
}
/// Disable the equality index for `(label, field)` and drop its postings.
///
/// # Errors
/// - [`GraphError::ReadOnly`]: called on an as-of instance.
/// - [`GraphError::RuleNotFound`]: `(label, field)` is not currently indexed.
pub fn disable_index(&mut self, label: &str, field: &str) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
if !self.prop_index.is_enabled(label, field) {
return Err(GraphError::RuleNotFound {
name: format!("index({label},{field})"),
});
}
self.log_then_apply(WalRecord::DisableIndex {
label: label.into(),
field: field.into(),
})
}
/// Whether `(label, field)` currently has an equality index.
pub fn is_index_enabled(&self, label: &str, field: &str) -> bool {
self.prop_index.is_enabled(label, field)
}
/// Search a full-text-indexed field.
///
/// Returns `(node_key, match_count)` pairs sorted by match_count descending,
/// ties broken by key (lexicographic). Tombstoned nodes are excluded.
///
/// **Query syntax:**
/// - Space-separated terms are AND'd: `"foo bar"` requires both.
/// - `OR` between terms forms disjunction: `"foo OR bar"` matches either.
/// - Trailing `*` on a term is a prefix match: `"rust*"` matches `rustlang`, `rusty`.
/// - `AND` keyword is accepted explicitly and is the default.
/// - Tokenization is unicode-alphanumeric (same as index time); case-insensitive.
///
/// **Unindexed field:** returns `Ok(vec![])` if `field` is not indexed.
/// Pin: this is the documented, tested, stable behavior for v1.
///
/// **Memory / performance:** O(postings) lookup; no scan. The index is
/// in-memory and proportional to total indexed text across all enabled fields.
///
/// **v2 grammar:** supports `"phrase"`, `-negation`, `prefix*`, `OR`, `AND`.
/// Results are BM25-scored (k1=1.2, b=0.75) and sorted by score descending,
/// key ascending for deterministic tiebreaking.
pub fn search(&self, field: &str, query: &str) -> Vec<(String, f64)> {
// Resolve node_ids to keys (excluding tombstones) then re-sort by
// (score DESC, key ASC) to give a deterministic, key-lexicographic
// tiebreak. FulltextIndex::search sorts by (score DESC, node_id ASC)
// which diverges from key order when nodes were not inserted in key-lex order.
let mut results: Vec<(String, f64)> = self
.fulltext
.search(field, query, 0)
.into_iter()
.filter_map(|(id, score)| self.ids.key_of(id).map(|key| (key.to_string(), score)))
.collect();
results.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(&b.0))
});
results
}
/// [`search`](Self::search), stopping at the `k` best hits.
///
/// Same ranking and the same deterministic tiebreak, but the index drops
/// everything past `k` before any key is resolved, so a caller that wants
/// the top few out of a field that matched thousands does not pay to
/// materialise and re-sort the tail. `k == 0` means no limit, exactly as
/// [`search`](Self::search) behaves.
///
/// The BM25 scoring itself is not bounded by `k` — every candidate is
/// scored either way — so this trims the resolve and the sort, not the
/// search.
pub fn search_top(&self, field: &str, query: &str, k: usize) -> Vec<(String, f64)> {
// A tombstoned id resolves to nothing, so asking the index for exactly
// `k` could return fewer. Over-fetching a little and truncating after
// the filter keeps the count right without unbounding the call.
let want = if k == 0 { 0 } else { k.saturating_mul(2) };
let mut results: Vec<(String, f64)> = self
.fulltext
.search(field, query, want)
.into_iter()
.filter_map(|(id, score)| self.ids.key_of(id).map(|key| (key.to_string(), score)))
.collect();
results.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(&b.0))
});
if k > 0 {
results.truncate(k);
}
results
}
/// Hybrid search: Reciprocal Rank Fusion (RRF) over fulltext + vector results.
///
/// Takes up to `4*k` fulltext hits for `(text_field, query_text)` and up to
/// `4*k` vector hits for `(vector_field, query_vec, min=0.0)`, then fuses
/// them with RRF using a fixed constant of 60.
///
/// ```text
/// score(d) = Σ 1 / (60 + rank_i(d)) (rank 1-based per list)
/// ```
///
/// Returns the top `k` nodes by fused score, ties broken by node key
/// ascending (deterministic).
///
/// # Vector leg fallback
///
/// When `query_vec` is empty the vector leg is skipped entirely and
/// results are ranked by the text list alone through the same RRF path
/// (each text result scores `1/(60 + rank)` from that single list).
///
/// When `label` is `None`, the vector leg **always** returns empty results.
/// Internally `label` is mapped to `""`, which does not match any rule-created
/// HNSW index (all such indexes are keyed to a specific non-empty label), and
/// the brute-force fallback finds no nodes with an empty label. The fused
/// ranking is therefore text-only in this case.
pub fn search_hybrid(
&self,
text_field: &str,
query_text: &str,
vector_field: &str,
query_vec: &[f64],
label: Option<&str>,
k: usize,
) -> Vec<(String, f64)> {
use std::collections::HashMap;
const RRF_K: f64 = 60.0;
let pool = 4 * k;
// Accumulate per-node RRF scores.
let mut scores: HashMap<String, f64> = HashMap::new();
// Text leg.
let text_hits = self.search(text_field, query_text);
for (rank0, (key, _count)) in text_hits.into_iter().take(pool).enumerate() {
let rank = (rank0 + 1) as f64;
*scores.entry(key).or_insert(0.0) += 1.0 / (RRF_K + rank);
}
// Vector leg (skipped when query_vec is empty).
if !query_vec.is_empty() {
let vec_hits = self.find_similar_vector(vector_field, label, query_vec, pool, 0.0);
for (rank0, (key, _sim)) in vec_hits.into_iter().enumerate() {
let rank = (rank0 + 1) as f64;
*scores.entry(key).or_insert(0.0) += 1.0 / (RRF_K + rank);
}
}
// Sort: score DESC, then key ASC for deterministic tie-breaking.
let mut ranked: Vec<(String, f64)> = scores.into_iter().collect();
ranked.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(&b.0))
});
ranked.truncate(k);
ranked
}
/// For DST/testing: scratch BM25 search over live nodes without the index.
/// Walks every live node, re-stems field tokens, computes corpus stats, and
/// returns BM25-ranked results.
///
/// The oracle: the ordered key list of `search(field, q)` must equal that of
/// `scratch_search(field, q)` at every quiescent state.
#[doc(hidden)]
pub fn scratch_search(&self, field: &str, query: &str) -> Vec<(String, f64)> {
use core_storage::fulltext::{parse_query, value_tokens_stemmed_with_positions};
use std::collections::BTreeMap;
let groups = parse_query(query);
if groups.is_empty() {
return vec![];
}
// --- Pass 1: collect all live indexed nodes with stemmed token data ---
struct NodeData {
key: String,
/// stemmed_token → positions (sorted)
tokens: BTreeMap<String, Vec<u32>>,
dl: u32,
}
let mut nodes: Vec<NodeData> = Vec::new();
for id in 0..self.ids.len() as u32 {
let Some(key) = self.ids.key_of(id) else {
continue;
};
let Some(&sym) = self.labels.get(id as usize) else {
continue;
};
if sym == u32::MAX {
continue;
}
let label = match self.syms.resolve(sym) {
Some(l) => l,
None => continue,
};
if !self.fulltext.is_enabled(label, field) {
continue;
}
let Some(value) = self.props_view().get(id, field).map(|vr| vr.into_value()) else {
continue;
};
// Use value_tokens_stemmed_with_positions so list elements are
// separated by POSITION_GAP — identical to the index path, which
// prevents phrase queries from matching across element boundaries.
let stemmed_with_pos = match &value {
Value::Str(_) | Value::List(_) => value_tokens_stemmed_with_positions(&value),
_ => continue,
};
let dl = stemmed_with_pos.len() as u32;
let mut tok_map: BTreeMap<String, Vec<u32>> = BTreeMap::new();
for (tok, pos) in stemmed_with_pos {
tok_map.entry(tok).or_default().push(pos);
}
nodes.push(NodeData {
key: key.to_string(),
tokens: tok_map,
dl,
});
}
if nodes.is_empty() {
return vec![];
}
// --- BM25 corpus stats ---
let n = nodes.len() as f64;
let avg_dl: f64 = nodes.iter().map(|nd| nd.dl as f64).sum::<f64>() / n;
// df per stemmed token across all live indexed nodes.
let mut df_map: BTreeMap<&str, f64> = BTreeMap::new();
for nd in &nodes {
for tok in nd.tokens.keys() {
*df_map.entry(tok.as_str()).or_insert(0.0) += 1.0;
}
}
const K1: f64 = 1.2;
const B: f64 = 0.75;
// --- Pass 2: score each node against each OR-group ---
let mut results: Vec<(String, f64)> = Vec::new();
for nd in &nodes {
let dl = nd.dl as f64;
let mut total_score = 0.0f64;
'group: for group in &groups {
let mut group_score = 0.0f64;
for term in group {
if term.negated {
// Negated: if doc has this stemmed token → group fails.
let present = if term.prefix {
nd.tokens.keys().any(|t| t.starts_with(term.token.as_str()))
} else {
nd.tokens.contains_key(term.token.as_str())
};
if present {
continue 'group;
}
continue;
}
if term.prefix {
// Prefix: sum BM25 for all matching stemmed tokens.
let mut prefix_matched = false;
for (tok, positions) in &nd.tokens {
if tok.starts_with(term.token.as_str()) {
let tf = positions.len() as f64;
let df = df_map.get(tok.as_str()).copied().unwrap_or(1.0);
let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
let tf_norm =
tf * (K1 + 1.0) / (tf + K1 * (1.0 - B + B * dl / avg_dl));
group_score += idf * tf_norm;
prefix_matched = true;
}
}
if !prefix_matched {
continue 'group;
}
} else {
// term.token is already stemmed by parse_query; use directly.
match nd.tokens.get(term.token.as_str()) {
None => continue 'group,
Some(positions) => {
let tf = positions.len() as f64;
let df = df_map.get(term.token.as_str()).copied().unwrap_or(1.0);
let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
let tf_norm =
tf * (K1 + 1.0) / (tf + K1 * (1.0 - B + B * dl / avg_dl));
group_score += idf * tf_norm;
}
}
}
}
if group_score > 0.0 {
total_score += group_score;
}
}
if total_score > 0.0 {
results.push((nd.key.clone(), total_score));
}
}
results.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(&b.0))
});
results
}
/// Return the current view-maintained value of `view_prop` for node `key`.
/// Equivalent to `get_prop` but documents that it reads a view-managed column.
pub fn get_view_prop(&self, key: &str, view_prop: &str) -> Option<Value> {
let id = self.ids.get(key)?;
self.props_view()
.get(id, view_prop)
.map(|vr| vr.into_value())
}
/// For testing / DST oracle: scratch recompute of a view value for one node.
///
/// Returns `None` if the node does not exist, the view does not exist, or
/// the view has no result for the node (e.g. Avg with no qualifying neighbors).
#[doc(hidden)]
pub fn scratch_view_value(&self, key: &str, view_name: &str) -> Option<Value> {
let node = self.ids.get(key)?;
let def = self.view_store.views().find(|v| v.name == view_name)?;
// Use TopologyView so that NeighborAgg sees base + overlay edges
// without materialising a temporary Topology (I1).
let topo_view = self.topo_view();
core_rules::views::compute_view_value(
def,
node,
self.props_view(),
&topo_view,
&self.ids,
&self.syms,
&self.labels,
)
}
// -----------------------------------------------------------------------
// Graph algorithm API
// -----------------------------------------------------------------------
/// Run PageRank over the unified topology (manual + derived edges).
///
/// Returns a [`PageRankReport`] with scores sorted descending (ties: key
/// ascending). Set `config.edge_type` to restrict to one edge type.
/// `config.converged` is `true` only when the power iteration converged
/// within `config.max_iters` and within any time budget.
pub fn pagerank(&self, config: &crate::algo::PageRankConfig) -> crate::algo::PageRankReport {
let topo = build_topo_view(&self.topo, &self.base);
let edge_props = self.edge_props_view();
crate::algo::pagerank(
&topo,
&self.ids,
&self.syms,
&self.labels,
&edge_props,
config,
)
}
/// Weakly-connected components over the unified topology (treated as
/// undirected regardless of how edges were inserted).
///
/// Component IDs are the key of the smallest member in the component
/// (deterministic). Result sorted by (component_id, key).
pub fn connected_components(&self, config: &crate::algo::WccConfig) -> crate::algo::WccReport {
let topo = build_topo_view(&self.topo, &self.base);
let edge_props = self.edge_props_view();
crate::algo::wcc(
&topo,
&self.ids,
&self.syms,
&self.labels,
&edge_props,
config,
)
}
/// Degree centrality for every live node.
///
/// `direction`: `AlgoDir::Out` = out-degree, `AlgoDir::In` = in-degree,
/// `AlgoDir::Both` = out + in (total directed degree).
///
/// For one-shot ranking use this; for a live property updated on every
/// write, create a Degree materialized view instead (see `docs/site/algorithms.md`).
pub fn degree_centrality(
&self,
config: &crate::algo::DegreeConfig,
) -> crate::algo::DegreeReport {
let topo = build_topo_view(&self.topo, &self.base);
let edge_props = self.edge_props_view();
crate::algo::degree_centrality(
&topo,
&self.ids,
&self.syms,
&self.labels,
&edge_props,
config,
)
}
/// Louvain community detection over the unified topology (undirected).
///
/// See [`crate::algo::LouvainConfig`] for edge-type/weight/label
/// restriction and [`crate::algo::CommunityReport`] for the shape of the
/// result (communities sorted size-desc, then smallest member key asc).
pub fn communities(&self, config: &crate::algo::LouvainConfig) -> crate::algo::CommunityReport {
let topo = build_topo_view(&self.topo, &self.base);
let edge_props = self.edge_props_view();
crate::algo::louvain(
&topo,
&self.ids,
&self.syms,
&self.labels,
&edge_props,
config,
)
}
/// Write a vector of `(node_key, score)` pairs as `prop_name` on each node,
/// atomically via a single write-batch (one WAL frame, one fsync).
///
/// # Errors
/// - [`GraphError::ReadOnly`]: called on an as-of instance.
/// - [`GraphError::RuleInvalid`]: `prop_name` is managed by an existing view
/// (collision check mirrors `create_view`).
/// - [`GraphError::KeyNotFound`]: a key in `scores` does not exist as a live node.
pub fn write_scores(&mut self, prop_name: &str, scores: &[(String, f64)]) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
// Collision check: refuse if prop_name is view-managed.
if let Some(view_name) = self.view_store.view_for_prop(prop_name) {
return Err(GraphError::RuleInvalid {
detail: format!(
"prop {:?} is managed by view {:?} and cannot be written as scores",
prop_name, view_name
),
});
}
// Refuse if prop_name is a view name itself (confusing namespace collision).
if self.view_store.has_view(prop_name) {
return Err(GraphError::RuleInvalid {
detail: format!(
"prop_name {:?} collides with an existing view name",
prop_name
),
});
}
// Write all scores in a single crash-atomic batch.
self.write_batch(|b| {
for (key, score) in scores {
b.set_prop(key, prop_name, Value::Float(*score));
}
})?;
Ok(())
}
/// Return the value of `field` for the node with key `key`, or `None` if
/// the node or field is absent. Reads through the overlay-over-base
/// `ColumnsView`, materialising base values on demand (zero heap cost for
/// overlay hits; one clone per base hit).
pub fn get_prop(&self, key: &str, field: &str) -> Option<Value> {
let id = self.ids.get(key)?;
self.props_view().get(id, field).map(|vr| vr.into_value())
}
pub fn has_node(&self, key: &str) -> bool {
self.ids.get(key).is_some()
}
/// Borrow the raw id map. Used by `NodeMask::from_keys` to resolve keys.
pub(crate) fn ids(&self) -> &IdMap {
&self.ids
}
// -----------------------------------------------------------------------
// Namespaces
// -----------------------------------------------------------------------
/// The index `name` already has in `ns_names`, if any.
fn ns_index_of(&self, name: &str) -> Option<u32> {
self.ns_names
.iter()
.position(|n| n == name)
.map(|i| i as u32)
}
/// The index for `name`, appending it to `ns_names` when it is new.
///
/// The table holds one entry per distinct namespace in the store — a
/// tenant count, not a node count — so the linear scan is cheaper than a
/// map and keeps `namespaces()` allocation-free of a second index.
fn ns_index_for(&mut self, name: &str) -> u32 {
match self.ns_index_of(name) {
Some(i) => i,
None => {
self.ns_names.push(name.to_string());
(self.ns_names.len() - 1) as u32
}
}
}
/// The namespace name at `idx`, or [`NS_DEFAULT`] for an index this handle
/// does not know (unreachable; the default is the narrowing answer).
fn ns_name(&self, idx: u32) -> &str {
self.ns_names
.get(idx as usize)
.map(String::as_str)
.unwrap_or(NS_DEFAULT)
}
/// The namespace index of dense node `id`, defaulting for an id with no
/// entry (a node inserted before this handle rebuilt the array cannot
/// exist: every insert path maintains it).
fn node_ns_idx(&self, id: u32) -> u32 {
self.node_ns
.get(id as usize)
.copied()
.unwrap_or(NS_DEFAULT_IDX)
}
/// File node `id` under namespace `name`, growing `node_ns` as `labels`
/// grows. Called from `apply` for every node insert, live and replayed.
fn set_node_ns(&mut self, id: u32, name: &str) {
let idx = if name == NS_DEFAULT {
NS_DEFAULT_IDX
} else {
self.ns_index_for(name)
};
if self.node_ns.len() <= id as usize {
self.node_ns.resize(id as usize + 1, NS_DEFAULT_IDX);
}
self.node_ns[id as usize] = idx;
}
/// Rebuild `node_ns` from the `ns` column — one pass, at the end of an
/// open or a reload, after the snapshot is restored and the WAL replayed.
///
/// A store with no `ns` column reads nothing: the column-name check fails
/// and the vector is filled with one constant.
fn rebuild_node_ns(&mut self) {
let total = self.ids.len();
self.ns_names.truncate(1);
self.node_ns.clear();
self.node_ns.resize(total, NS_DEFAULT_IDX);
let has_ns_column = {
let cv = self.props_view();
cv.field_names().iter().any(|f| f == NS_PROP)
};
if !has_ns_column {
return;
}
// Collected first so the props view is released before `ns_index_for`
// takes `&mut self`.
let named: Vec<(u32, String)> = {
let cv = self.props_view();
(0..total as u32)
.filter_map(|id| match cv.get(id, NS_PROP).map(|vr| vr.into_value()) {
Some(Value::Str(s)) if s != NS_DEFAULT => Some((id, s)),
_ => None,
})
.collect()
};
for (id, name) in named {
let idx = self.ns_index_for(&name);
self.node_ns[id as usize] = idx;
}
}
/// Every namespace with at least one live node, in name order.
///
/// `["default"]` on any store that has never named a namespace, including
/// an empty one: a store is always at least its default namespace.
pub fn namespaces(&self) -> Vec<String> {
let mut out: BTreeSet<&str> = BTreeSet::new();
out.insert(NS_DEFAULT);
for (id, &idx) in self.node_ns.iter().enumerate() {
if idx == NS_DEFAULT_IDX || !self.is_live_node(id as u32) {
continue;
}
out.insert(self.ns_name(idx));
}
out.into_iter().map(str::to_string).collect()
}
/// The namespace of `key`, or `None` when the key names no live node.
pub fn namespace_of(&self, key: &str) -> Option<String> {
let id = self.ids.get(key)?;
if !self.is_live_node(id) {
return None;
}
Some(self.ns_name(self.node_ns_idx(id)).to_string())
}
/// Every live node in `namespace`, as a visibility mask.
///
/// Built off `node_ns` on whichever handle this is, so on a temporal handle
/// it is the namespace's membership at that commit. A name no node uses
/// gives an empty mask — a namespace scope never widens.
pub fn mask_for_namespace(&self, namespace: &str) -> crate::mask::NodeMask {
let Some(idx) = self.ns_index_of(namespace) else {
return crate::mask::NodeMask::from_ids(std::collections::HashSet::new());
};
let visible: std::collections::HashSet<u32> = (0..self.ids.len() as u32)
.filter(|&id| self.node_ns_idx(id) == idx && self.is_live_node(id))
.collect();
crate::mask::NodeMask::from_ids(visible)
}
/// Live-node test used by the namespace accessors: a deleted node keeps its
/// dense id and its `node_ns` slot, and the label sentinel is what marks it
/// gone — the same test `mask_for_role`'s label leg applies implicitly.
fn is_live_node(&self, id: u32) -> bool {
self.labels
.get(id as usize)
.is_some_and(|&sym| sym != u32::MAX)
&& self.ids.key_of(id).is_some()
}
/// Per-namespace live node counts for [`Stats`], in name order.
fn namespace_stats(&self) -> Vec<NamespaceStats> {
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
counts.insert(NS_DEFAULT, 0);
for id in 0..self.ids.len() as u32 {
if !self.is_live_node(id) {
continue;
}
*counts
.entry(self.ns_name(self.node_ns_idx(id)))
.or_insert(0) += 1;
}
counts
.into_iter()
.filter(|&(name, n)| n > 0 || name == NS_DEFAULT)
.map(|(name, nodes_live)| NamespaceStats {
name: name.to_string(),
nodes_live,
})
.collect()
}
/// The namespace a create-class op would put its node in: the `ns` entry of
/// the props it carries, normalised, with absent meaning [`NS_DEFAULT`].
fn created_namespace<'a>(key: &str, props: &'a [(String, Value)]) -> Result<&'a str> {
Ok(namespace_of_value(Self::sole_ns_entry(key, props)?))
}
/// The one `ns` entry in a node's props, or `None` when it carries none.
///
/// A props list naming `ns` twice is refused. Without that refusal the
/// write path and the authorisation path can read the same list
/// differently — one taking the first entry, the other the last — and
/// `CREATE (n:L {ns: 'mine', ns: 'theirs'})` lands a node in a namespace
/// the role was checked against the other of. One entry is the only shape
/// where "the node's namespace" is a single fact, so it is the only shape
/// accepted, and every reader of it agrees by construction.
fn sole_ns_entry<'a>(key: &str, props: &'a [(String, Value)]) -> Result<Option<&'a Value>> {
let mut found: Option<&'a Value> = None;
for (field, value) in props {
if field != NS_PROP {
continue;
}
if found.is_some() {
return Err(GraphError::RuleInvalid {
detail: format!(
"node {key}: {NS_PROP} is given more than once; a node has exactly \
one namespace"
),
});
}
found = Some(value);
}
Ok(found)
}
/// The definition of the role a write authorisation names.
///
/// `None` when `roles.json` was corrupt at open or the role has since been
/// removed — neither can reach a write, because the authorisation carries a
/// mask `mask_for_role` already resolved for that name.
fn role_def_for(&self, role: &str) -> Option<&RoleDef> {
self.roles.as_ref()?.iter().find(|r| r.name == role)
}
/// Validate the `ns` entry of a node's props and drop an explicit default.
///
/// Runs on the write path only (see `rewrite_wal_dense`), never on replay:
/// a record that reached the WAL was already accepted here.
fn normalise_insert_ns(
key: &str,
props: Vec<(String, Value)>,
) -> Result<(Vec<(String, Value)>, String)> {
// One `ns` or none: this is where that is enforced, so every later
// reader of the list — the authorisation gate, the two `apply` arms,
// `node_ns` — is looking at a single entry and cannot disagree about
// which one counts.
Self::sole_ns_entry(key, &props)?;
let mut name = NS_DEFAULT.to_string();
let mut out = Vec::with_capacity(props.len());
for (field, value) in props {
if field != NS_PROP {
out.push((field, value));
continue;
}
let Value::Str(ref s) = value else {
return Err(GraphError::RuleInvalid {
detail: format!(
"node {key}: {NS_PROP} must be a string naming a namespace, \
got {value:?}"
),
});
};
if !valid_namespace(s) {
return Err(GraphError::RuleInvalid {
detail: format!(
"node {key}: {s:?} is not a valid namespace name — 1 to {NS_MAX_LEN} \
characters of [A-Za-z0-9_.-]"
),
});
}
name = s.clone();
// An explicit default stores nothing, so a single-tenant store
// never grows an `ns` column.
if name != NS_DEFAULT {
out.push((field, value));
}
}
Ok((out, name))
}
// -----------------------------------------------------------------------
// RBAC role resolution
// -----------------------------------------------------------------------
/// Parse `roles.json` bytes from `fs`.
///
/// Return values:
/// `Ok(Some(roles))` — file absent (returns `vec![]`) **or** file present
/// and valid; in both cases `mask_for_role` uses the
/// list normally (an absent file means no roles defined).
/// `Ok(None)` — file present but corrupt or unrecognised version
/// → poisoned state; `mask_for_role` returns `Err` for
/// any role name until the file is fixed and the DB
/// re-opened (or `apply_schema` is called to repair it).
///
/// Note: `None` signals corruption, not absence — the opposite of what an
/// optional "file missing" convention would suggest. The open path stores
/// this result on `db.roles` directly.
fn load_roles_from_fs(fs: &F) -> Result<Option<Vec<RoleDef>>> {
let bytes = fs.read(FileId::Roles).map_err(GraphError::Io)?;
if bytes.is_empty() {
// Empty bytes means either the file is absent or zero-byte — both
// are treated identically as "no roles defined". A zero-byte
// roles.json does NOT widen access: an absent file and a zero-byte
// file both resolve to an empty role list (sees nothing by default).
return Ok(Some(vec![]));
}
match serde_json::from_slice::<RolesFile>(&bytes) {
Ok(f) if matches!(f.version, 1..=4) => Ok(Some(f.roles)),
// Corrupt or unrecognised version (>4): poison the roles state.
// Never widen: a version this binary does not know may carry a
// narrowing this binary would not apply.
_ => Ok(None),
}
}
/// Resolve a role to a node-visibility mask against the current graph state.
///
/// Returns `Err` when:
/// - `roles.json` was present but corrupt at open (poisoned state), or
/// - `role` does not match any defined role name.
///
/// The mask union is: explicit `keys` (unknown keys silently ignored) plus
/// all live nodes carrying any label in `labels` that also pass the role's
/// [`visible_where`](crate::roles::RoleDef::visible_where) predicate, if it
/// has one. Label resolution is live — new nodes of an allowed label are
/// visible without re-applying the schema, and a property edited out of the
/// predicate takes its node out of the mask on the next read. An empty
/// union = empty mask = sees nothing.
///
/// This is the one resolver every read path calls, live and as-of alike, so
/// the predicate applies everywhere at once. On an as-of handle the role
/// *definition* is the current one and the graph is the historical one: the
/// predicate is evaluated against the property values at the commit being
/// read.
///
/// The result is memoised per `(role, commit_seq)`, so a scoped reader
/// between two writes resolves the role once. See
/// [`RoleMaskCache`](crate::mask::RoleMaskCache) for why that cannot go
/// stale.
pub fn mask_for_role(&self, role: &str) -> Result<crate::mask::NodeMask> {
self.role_masks
.get_or_build(role, self.commit_seq, || self.build_mask_for_role(role))
.map(|m| (*m).clone())
}
/// The mask an [`AsOfScope`] names, resolved against this handle.
///
/// Shared by [`GraphDb::query_at_scoped`] and
/// [`GraphDb::query_at_scoped_in_namespace`] so one scope resolves one way
/// however the namespace leg is added.
fn mask_at_scope(&self, scope: AsOfScope<'_>) -> Result<crate::mask::NodeMask> {
// One resolver answers "what may this role see" — `mask_for_role` — and
// it runs against this handle, so on a temporal one the answer is the
// as-of one.
Ok(match scope {
AsOfScope::Role(role) => self.mask_for_role(role)?,
AsOfScope::Keys(keys) => {
crate::mask::NodeMask::from_keys(self, keys.iter().map(String::as_str))
}
AsOfScope::RoleAndKeys(role, keys) => {
self.mask_for_role(role)?
.intersect(&crate::mask::NodeMask::from_keys(
self,
keys.iter().map(String::as_str),
))
}
AsOfScope::Namespace(namespace) => self.mask_for_namespace(namespace),
})
}
/// Resolve `role` against the current graph, ignoring the memo.
fn build_mask_for_role(&self, role: &str) -> Result<crate::mask::NodeMask> {
let roles = self.roles.as_ref().ok_or_else(|| GraphError::Corrupt {
detail:
"roles.json was corrupt at open; fix the file and re-open to restore role access"
.into(),
})?;
let def = roles
.iter()
.find(|r| r.name == role)
.ok_or_else(|| GraphError::KeyNotFound {
key: format!("role:{role}"),
})?;
let mut visible = std::collections::HashSet::new();
// Key leg: resolve explicit keys to dense ids (unknown keys ignored).
// An administrative grant, never narrowed by the predicate.
for key in &def.keys {
if let Some(id) = self.ids.get(key) {
visible.insert(id);
}
}
// Label leg: live scan — iterate labels vec for matching symbol, and
// when the role carries a predicate, test the property as well. The
// property comes from the store's own merged view (overlay over the
// mmap'd base), so an as-of handle reads the values of its own commit.
let props = def.visible_where.as_ref().map(|_| self.props_view());
for label_name in &def.labels {
if let Some(sym) = self.syms.get(label_name) {
for (i, &s) in self.labels.iter().enumerate() {
if s != sym {
continue;
}
let id = i as u32;
match (&def.visible_where, &props) {
(Some(pred), Some(view)) => {
let value = view.get(id, &pred.field).map(|vr| vr.into_value());
if pred.holds(value.as_ref()) {
visible.insert(id);
}
}
_ => {
visible.insert(id);
}
}
}
}
}
// Namespace leg: an intersection over the whole union, the key leg
// included. A namespace is a tenancy boundary, so a key naming a node in
// another tenant's namespace is not an administrative grant — and
// `apply_schema` has already refused that role, so this only has to be
// right about the node that moved into existence afterwards.
if def.namespaces.is_some() {
visible.retain(|&id| def.sees_namespace(self.ns_name(self.node_ns_idx(id))));
}
Ok(crate::mask::NodeMask::from_ids(visible))
}
/// Return the current list of role definitions.
///
/// Returns an empty list when no roles are defined or when `roles.json`
/// was corrupt at open (check [`mask_for_role`](Self::mask_for_role) for
/// the fail-loud error in that case).
pub fn roles(&self) -> Vec<RoleDef> {
self.roles.as_deref().unwrap_or(&[]).to_vec()
}
// ── Role-scoped write authz ───────────────────────────────────────────────
/// Execute `ops` with optional role-scoped write authorization.
///
/// - `None` → full authority, identical to [`write_batch`](Self::write_batch)
/// (zero-cost bypass of all authz checks).
/// - `Some(authz)` → the decision table is evaluated per-op BEFORE any WAL
/// record is built. A denial returns an error with no WAL frame written
/// (all-or-nothing at the authz boundary, then at the MutPreview boundary).
///
/// See the plan's "authz decision table" section for the full semantics.
pub fn write_batch_authz(
&mut self,
authz: Option<&WriteAuthz>,
ops: Vec<BatchOp>,
) -> Result<(usize, usize)> {
// Thread authz as a direct parameter — never touches pending_write_authz.
self.commit_logged_batch(ops, None, authz.cloned())
}
/// Execute a Cypher write statement with role-scoped write authorization.
///
/// Resolves scope + mask from `self.roles` inside the call (same write-guard
/// lifetime as execution, satisfying §5 lock discipline). The resolved
/// `WriteAuthz` is stored as `pending_write_authz` for the duration of the
/// call so that all inner `batch.commit()` calls are authz-checked.
///
/// MERGE is handled specially: the MERGE scope precondition (§3.3) is
/// checked in `exec_merge` BEFORE `has_node` to close the §6.2
/// timing-oracle item (hidden ≡ absent for unscoped roles).
///
/// Roles with `write: None` (v1 behavior) → `RoleWriteDenied` with
/// "this endpoint is not permitted".
pub fn query_write_authz(
&mut self,
role: &str,
cypher: &str,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
// Resolve scope (fails fast if role has no write scope).
// write:None → byte-identical v1 blanket-403 body (plan §v1-sidecar mandate).
let scope =
{
let roles = self.roles.as_deref().ok_or_else(|| GraphError::Corrupt {
detail: "roles.json was corrupt at open; re-open to restore role access".into(),
})?;
let def = roles.iter().find(|r| r.name == role).ok_or_else(|| {
GraphError::KeyNotFound {
key: format!("role:{role}"),
}
})?;
def.write
.clone()
.ok_or_else(|| GraphError::RoleWriteDenied {
reason: "role-bound token: writes are not permitted".into(),
})?
};
// Resolve mask inside the call (same guard, §5 coherence).
let mask = self.mask_for_role(role)?;
self.pending_write_authz = Some(WriteAuthz {
role: role.into(),
scope,
mask,
});
// RAII guard: always clears pending_write_authz on scope exit, including
// on panic or early-return, mirroring the RestoreEmitDeltas precedent.
struct ClearPendingAuthzOnDrop(*mut Option<WriteAuthz>);
impl Drop for ClearPendingAuthzOnDrop {
fn drop(&mut self) {
// SAFETY: pointer into the owning GraphDb; guard is dropped
// within this function's frame before it returns.
unsafe { *self.0 = None };
}
}
// SAFETY: raw pointer into self; guard dropped before this fn returns.
let _authz_guard = ClearPendingAuthzOnDrop(&mut self.pending_write_authz as *mut _);
let tokens = lex(cypher).map_err(|e| GraphError::QueryError {
detail: format!("lex: {e}"),
})?;
let stmt = parse_write(&tokens).map_err(|e| GraphError::QueryError {
detail: format!("parse: {e}"),
})?;
self.exec_write_stmt(stmt, params)
}
/// Execute `ops` with optional role-scoped write authorization, suppressing
/// fsync (for use inside the group-commit drain thread, which performs one
/// group fsync after releasing the write lock).
///
/// Identical to [`write_batch_authz`] except the fsync policy is temporarily
/// forced to `Relaxed` for the duration of the call, matching the drain-thread
/// contract established by [`commit_batch_nosync`].
pub(crate) fn write_batch_authz_nosync(
&mut self,
authz: Option<&WriteAuthz>,
ops: Vec<BatchOp>,
) -> Result<(usize, usize)> {
let saved = self.fsync;
struct RestoreFsync(*mut FsyncPolicy, FsyncPolicy);
impl Drop for RestoreFsync {
fn drop(&mut self) {
// SAFETY: pointer into the owning GraphDb; guard is dropped
// within the enclosing function's frame before it returns.
unsafe { *self.0 = self.1 };
}
}
// SAFETY: raw pointer into self; guard dropped before this fn returns.
let _g = RestoreFsync(&mut self.fsync as *mut FsyncPolicy, saved);
self.fsync = FsyncPolicy::Relaxed;
self.commit_logged_batch(ops, None, authz.cloned())
}
/// Execute a `/ingest` request with role-scoped write authorization.
///
/// Resolves the role's `WriteScope` and `NodeMask` inside this call (same
/// write-guard lifetime as the mutation, satisfying §5 lock discipline).
/// Sets `pending_write_authz` for the duration of the call so that the
/// `commit_ingest` → `commit_logged_batch` path picks up the authz context
/// and evaluates the decision table per-op before any WAL write.
///
/// §7.3: roles with empty `create_labels` will see every `InsertNode` op
/// denied by the decision table with the appropriate §4.3 scope reason;
/// no special HTTP-layer check is needed.
///
/// Roles with `write: None` return `RoleWriteDenied` with
/// "writes are not permitted" (byte-identical to v1 blanket 403).
pub fn ingest_with_edges_authz(
&mut self,
role: &str,
label: &str,
rows: Vec<std::collections::BTreeMap<String, Value>>,
opts: &crate::ingest::IngestOptions,
edges: &[(String, String, String)],
) -> Result<crate::ingest::IngestReport> {
// Resolve scope (fails fast if role has no write scope).
// write:None → byte-identical v1 blanket-403 body (plan §v1-sidecar mandate).
let scope =
{
let roles = self.roles.as_deref().ok_or_else(|| GraphError::Corrupt {
detail: "roles.json was corrupt at open; re-open to restore role access".into(),
})?;
let def = roles.iter().find(|r| r.name == role).ok_or_else(|| {
GraphError::KeyNotFound {
key: format!("role:{role}"),
}
})?;
def.write
.clone()
.ok_or_else(|| GraphError::RoleWriteDenied {
reason: "role-bound token: writes are not permitted".into(),
})?
};
let mask = self.mask_for_role(role)?;
self.pending_write_authz = Some(WriteAuthz {
role: role.into(),
scope,
mask,
});
// RAII guard: always clears pending_write_authz on scope exit, including
// on panic or early-return, mirroring the RestoreEmitDeltas precedent.
struct ClearPendingAuthzOnDrop(*mut Option<WriteAuthz>);
impl Drop for ClearPendingAuthzOnDrop {
fn drop(&mut self) {
// SAFETY: pointer into the owning GraphDb; guard is dropped
// within this function's frame before it returns.
unsafe { *self.0 = None };
}
}
// SAFETY: raw pointer into self; guard dropped before this fn returns.
let _authz_guard = ClearPendingAuthzOnDrop(&mut self.pending_write_authz as *mut _);
self.ingest_with_edges(label, rows, opts, edges)
}
/// Evaluate the write-authz decision table for one `BatchOp`.
///
/// Called by `commit_logged_batch` for each op when `pending_write_authz`
/// is `Some`, BEFORE MutPreview. A denial returns an error immediately;
/// the remaining ops are not evaluated and no WAL frame is written.
///
/// `batch_created` carries the key→label pairs of nodes that earlier ops in
/// THIS batch will create. Used by `InsertEdgeUpsert` to count same-batch
/// placeholder nodes as visible (spec: "a placeholder endpoint the SAME
/// batch creates counts as visible if its label passed the create-class gate").
fn check_single_op_authz(
&self,
authz: &WriteAuthz,
op: &BatchOp,
batch_created: &BTreeMap<String, String>,
) -> Result<()> {
// Helper: 3-way node status under the authz mask.
//
// Batch-created nodes (from earlier InsertNode in THIS batch) are treated
// as Visible with their recorded label — their create gate already passed
// and they are not yet in self.ids (not committed). This fixes the
// MERGE+ON CREATE SET case where InsertNode + SetProp arrive together:
// the SetProp must not see the node as Absent.
let node_status = |key: &str| -> NodeAuthzStatus {
if let Some(label) = batch_created.get(key) {
return NodeAuthzStatus::Visible(label.clone());
}
match self.ids.get(key) {
None => NodeAuthzStatus::Absent,
Some(id) if !authz.mask.contains_id(id) => NodeAuthzStatus::Hidden,
Some(id) => {
let label = self
.labels
.get(id as usize)
.and_then(|&sym| {
if sym == u32::MAX {
None
} else {
self.syms.resolve(sym).map(str::to_string)
}
})
.unwrap_or_default();
NodeAuthzStatus::Visible(label)
}
}
};
// Helper: is an InsertEdgeUpsert endpoint visible?
// A same-batch placeholder counts as visible if its label passed
// the create-class gate (spec "upsert placeholder-counts-as-visible").
let upsert_ep_visible = |ep_key: &str, placeholder_label: &str| -> bool {
// In store and visible?
if let Some(id) = self.ids.get(ep_key) {
return authz.mask.contains_id(id);
}
// Created by an earlier op in this batch?
if let Some(created_label) = batch_created.get(ep_key) {
return authz.scope.create_labels.contains(created_label);
}
// Will be created by THIS InsertEdgeUpsert: placeholder_label
// must pass the create-class gate.
authz
.scope
.create_labels
.contains(&placeholder_label.to_string())
};
match op {
// RenameNode / CreateRule / DeleteRule: defense-in-depth gate.
// These ops are never routed to role-scoped paths by the HTTP layer,
// but we 403 them here to close any future bypass route.
BatchOp::RenameNode { .. } | BatchOp::CreateRule(_) | BatchOp::DeleteRule { .. } => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: this endpoint is not permitted".into(),
});
}
// ── CREATE-class: InsertNode ─────────────────────────────────────
//
// Decision table row 1 (scope-before-lookup): check label in
// create_labels BEFORE any key lookup. This is the structural
// closure of the §6.2 timing-oracle item — the denial fires even
// when the store is EMPTY (see test_create_scope_denied_empty_store).
BatchOp::InsertNode { label, key, props } => {
if !authz.scope.create_labels.contains(label) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: label '{}' not in write scope (create_labels)",
label
),
});
}
// A role bound to namespaces may only create inside them. The
// never-widen rule is about what a write makes visible to *any*
// party, not only to the writer: a node this role could never
// read back is a write into somebody else's tenancy. Also a
// scope check, so it runs before the key lookup — it discloses
// nothing about the store. Covers Cypher `CREATE` and the node
// `MERGE` creates, both of which arrive as this op.
// Resolved before the role lookup so a props list naming `ns`
// twice is refused for every role, scoped or not: it is the same
// malformed write the seam refuses, and leaving it to the seam
// would mean the gate had already read one of the two.
let target = Self::created_namespace(key, props)?;
if let Some(def) = self.role_def_for(&authz.role) {
if !def.sees_namespace(target) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: namespace '{target}' not in the role's \
namespaces"
),
});
}
}
// Row 2/3: key lookup.
match self.ids.get(key.as_str()) {
Some(id) if authz.mask.contains_id(id) => {
// Visible: DuplicateKey — let MutPreview handle this.
}
Some(_) => {
// Hidden: indistinguishable from absent to the role.
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: target node not visible".into(),
});
}
None => {
// Absent: proceed (create).
}
}
}
// ── UPDATE-class: SetProp, RemoveProp ────────────────────────────
BatchOp::SetProp { key, .. } | BatchOp::RemoveProp { key, .. } => {
if batch_created.contains_key(key.as_str()) {
// Batch-created node: create gate already passed this batch.
// Updating it in the same batch is always allowed, regardless
// of update_labels (ruling §3.5: "writer just created it").
} else {
let label = match node_status(key) {
NodeAuthzStatus::Visible(lbl) => lbl,
_ => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: target node not visible".into(),
});
}
};
if !authz.scope.update_labels.contains(&label) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: label '{}' not in write scope (update_labels)",
label
),
});
}
}
}
// ── DELETE-class: DeleteNode ─────────────────────────────────────
BatchOp::DeleteNode { key } => {
let label = match node_status(key) {
NodeAuthzStatus::Visible(lbl) => lbl,
_ => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: target node not visible".into(),
});
}
};
if !authz.scope.delete_labels.contains(&label) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: label '{}' not in write scope (delete_labels)",
label
),
});
}
}
// ── DELETE-class: DeleteEdge ─────────────────────────────────────
//
// Derived-edge rejection runs BEFORE the delete_edge_types scope
// check (spec §3.5: "existing derived-edge rejection precedes
// delete_edge_types check").
BatchOp::DeleteEdge {
edge_type,
src_key,
dst_key,
} => {
// Check provenance ownership BEFORE scope (spec §3.5 ordering).
if let (Some(src_id), Some(dst_id), Some(et_sym)) = (
self.ids.get(src_key.as_str()),
self.ids.get(dst_key.as_str()),
self.syms.get(edge_type.as_str()),
) {
if self.engine.is_owned(et_sym, src_id, dst_id) {
return Err(GraphError::RuleOwned {
detail: format!(
"edge {edge_type} {src_key}→{dst_key} is rule-owned; \
delete or change the owning rule"
),
});
}
// Also check would_derive via MutPreview (empty overlay, pre-batch).
let preview = MutPreview::new(self);
if preview.would_derive(edge_type, src_key, dst_key) {
return Err(GraphError::RuleOwned {
detail: format!(
"edge {edge_type} {src_key}→{dst_key} is rule-owned; \
delete or change the owning rule, or a live rule would \
re-derive it"
),
});
}
}
// Scope check (AFTER derived-edge check, BEFORE endpoint visibility).
if !authz.scope.delete_edge_types.contains(edge_type) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: edge type '{}' not in write scope (delete_edge_types)",
edge_type
),
});
}
// Both endpoints must be visible.
for ep_key in [src_key.as_str(), dst_key.as_str()] {
match self.ids.get(ep_key) {
None => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: edge endpoint not visible".into(),
});
}
Some(id) if !authz.mask.contains_id(id) => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: edge endpoint not visible".into(),
});
}
_ => {}
}
}
}
// ── EDGE-CREATE: InsertEdge ──────────────────────────────────────
//
// Scope check BEFORE endpoint lookup (preserves timing symmetry).
BatchOp::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
if !authz.scope.create_edge_types.contains(edge_type) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: edge type '{}' not in write scope (create_edge_types)",
edge_type
),
});
}
// Both endpoints must be visible. A node created by an earlier
// InsertNode in the same batch (tracked in batch_created) counts
// as visible if its label passed the create-class gate.
for ep_key in [src_key.as_str(), dst_key.as_str()] {
if batch_created.contains_key(ep_key) {
// Created earlier this batch — already scope-checked.
continue;
}
match self.ids.get(ep_key) {
None => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: edge endpoint not visible".into(),
});
}
Some(id) if !authz.mask.contains_id(id) => {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: edge endpoint not visible".into(),
});
}
_ => {}
}
}
}
// ── EDGE-CREATE: InsertEdgeUpsert ────────────────────────────────
//
// Scope check first; then endpoint visibility using same-batch
// placeholder awareness (spec: "a placeholder endpoint the SAME
// batch creates counts as visible if its label passed the
// create-class gate").
BatchOp::InsertEdgeUpsert {
edge_type,
src_key,
dst_key,
placeholder_label,
} => {
if !authz.scope.create_edge_types.contains(edge_type) {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: edge type '{}' not in write scope (create_edge_types)",
edge_type
),
});
}
// Check placeholder label against create_labels (create-class gate).
// This ensures the auto-created endpoints are scope-allowed.
for ep_key in [src_key.as_str(), dst_key.as_str()] {
if !upsert_ep_visible(ep_key, placeholder_label) {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: edge endpoint not visible".into(),
});
}
}
// A placeholder is created with no props, so it lands in the
// default namespace. A role that cannot read `default` must not
// create one there, for the same reason it may not create a node
// there outright.
//
// The refusal is byte-identical to the hidden-endpoint one above,
// and deliberately so: this arm fires only for an endpoint that
// does **not** exist, and the one above only for an endpoint that
// does. Two different strings would make the pair an existence
// oracle — ask for an upsert and read off whether the key is
// taken. Hidden ≡ absent is the rule everywhere else in this
// table and it holds here too.
if let Some(def) = self.role_def_for(&authz.role) {
if !def.sees_namespace(NS_DEFAULT) {
for ep_key in [src_key.as_str(), dst_key.as_str()] {
if self.ids.get(ep_key).is_none() && !batch_created.contains_key(ep_key)
{
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: edge endpoint not visible".into(),
});
}
}
}
}
}
}
Ok(())
}
/// Write `roles` to `roles.json` atomically and update the in-memory list.
///
/// Called by `apply_schema` when roles change. Never called on unchanged
/// re-apply — this preserves byte-identical idempotency.
pub(crate) fn commit_roles(&mut self, roles: Vec<RoleDef>) -> Result<()> {
let file = RolesFile::new_versioned(roles.clone());
let bytes = serde_json::to_vec(&file).map_err(|e| GraphError::Corrupt {
detail: format!("roles serialization: {e}"),
})?;
self.fs
.write_atomic(FileId::Roles, &bytes)
.map_err(GraphError::Io)?;
self.roles = Some(roles);
// Rewriting the sidecar is not a commit, so `commit_seq` does not move
// and a memoised mask would still match its version. Install a fresh
// cache instead of clearing the shared one: a reader snapshot frozen
// against the old definitions keeps the old `Arc` to itself and can
// never publish an answer this handle would read back.
self.role_masks = Arc::new(crate::mask::RoleMaskCache::new());
// Refresh the MVCC frozen overlay so that reader() immediately sees the
// updated role definitions without waiting for the next K-commit fold.
self.fold_now();
Ok(())
}
fn view(&self) -> GraphView<'_> {
GraphView {
ids: &self.ids,
syms: &self.syms,
labels: &self.labels,
props: self.props_view(),
topo: self.topo_view(),
edge_props: self.edge_props_view(),
mask: None,
prop_index: Some(&self.prop_index),
}
}
fn view_masked<'a>(&'a self, mask: &'a crate::mask::NodeMask) -> GraphView<'a> {
GraphView {
ids: &self.ids,
syms: &self.syms,
labels: &self.labels,
props: self.props_view(),
topo: self.topo_view(),
edge_props: self.edge_props_view(),
mask: Some(&mask.visible),
prop_index: Some(&self.prop_index),
}
}
/// Execute a read-only Cypher query with a node visibility mask.
///
/// Only nodes whose key is in `mask` are accessible: label scans, key
/// lookups, and neighbor expansions all respect the mask. Edges where
/// either endpoint is hidden are silently dropped.
///
/// Returns `Err` with a "masked queries are read-only" message when
/// `cypher` is a write statement (CREATE / MERGE / MATCH…SET / DELETE).
pub fn query_masked(
&self,
cypher: &str,
params: &std::collections::BTreeMap<String, Value>,
mask: &crate::mask::NodeMask,
) -> Result<ResultSet> {
// Reject write statements up front.
let tokens = lex(cypher).map_err(|e| GraphError::QueryError {
detail: format!("lex: {e}"),
})?;
if is_write_tokens(&tokens) {
return Err(GraphError::MaskedReadOnly);
}
let union = parse_read(&tokens).map_err(|e| GraphError::QueryError {
detail: format!("parse: {e}"),
})?;
// Each UNION part executes against the same masked view, so the mask
// applies uniformly across the chain.
execute_union(&self.view_masked(mask), &union, &Params(params)).map_err(|e| {
GraphError::QueryError {
detail: format!("execute: {e}"),
}
})
}
pub fn node_ref(&self, key: &str) -> Option<NodeRef<'_, F>> {
let id = self.ids.get(key)?;
Some(NodeRef { db: self, id })
}
/// BFS neighborhood expansion restricted to visible nodes in `mask`.
///
/// Hidden nodes are never used as traversal intermediaries in either
/// [`MaskMode::Omit`] or [`MaskMode::Stub`] — a visible node reachable
/// only through a hidden node will not appear in results.
///
/// In [`MaskMode::Stub`] mode, hidden nodes that are direct neighbours of
/// a visited visible node are appended to the result as stub rows
/// (`label` column is `null`, same key+depth columns as visible rows).
/// They are NOT added to the BFS frontier.
///
/// Returns `None` when `key` does not exist (caller should 404).
///
/// **SECURITY**: role-token callers always pass an Omit-mode mask, so
/// stub rows are never produced on the role path.
pub fn neighborhood_masked(
&self,
key: &str,
depth: u32,
edge_types: Option<&[&str]>,
dir: Dir,
mask: &crate::mask::NodeMask,
) -> Option<ResultSet> {
let start_id = self.ids.get(key)?;
let view = self.view_masked(mask);
let resolved: Option<Vec<u32>> = edge_types.map(|names| {
names
.iter()
.filter_map(|name| view.syms.get(name))
.collect()
});
let nb = neighborhood(&view, start_id, depth, resolved.as_deref(), dir);
let mut rs = ResultSet::new(vec!["key".into(), "label".into(), "depth".into()]);
// Collect visible BFS results (start_id at depth 0, BFS nodes after).
let mut visited: Vec<(u32, u32)> = Vec::with_capacity(nb.nodes.len() + 1);
visited.push((start_id, 0));
for (nid, d) in &nb.nodes {
let k = view.key_of(*nid);
let label = view
.label_of(*nid)
.expect("real nodes always have a label; u32::MAX sentinel cannot occur");
rs.push_row(vec![
Some(Value::Str(k.to_string())),
Some(Value::Str(label.to_string())),
Some(Value::Int(*d as i64)),
]);
visited.push((*nid, *d));
}
// Stub mode: add hidden direct neighbours of each visited node as stubs.
// Hidden nodes are edge-endpoints only — they are not added to the BFS
// frontier, so the BFS never expands through them.
if mask.mode() == crate::mask::MaskMode::Stub {
let raw_view = self.view();
let mut seen: std::collections::HashSet<u32> =
visited.iter().map(|(id, _)| *id).collect();
for (node_id, node_depth) in &visited {
if *node_depth >= depth {
continue;
}
for e in expand(&raw_view, *node_id, resolved.as_deref(), dir) {
let nbr = if e.src == *node_id { e.dst } else { e.src };
if !mask.contains_id(nbr) && seen.insert(nbr) {
if let Some(k) = self.ids.key_of(nbr) {
rs.push_row(vec![
Some(Value::Str(k.to_string())),
None,
Some(Value::Int((*node_depth + 1) as i64)),
]);
}
}
}
}
}
Some(rs)
}
/// Live node's key, label, and columnar props. Unknown or tombstoned → `None`.
pub fn node_info(&self, key: &str) -> Option<NodeInfo> {
let n = self.node_ref(key)?;
Some(NodeInfo {
key: n.key().to_string(),
label: n.label().to_string(),
props: n.props(),
})
}
/// Look up a node with mask awareness.
///
/// | Key state | Omit mode | Stub mode |
/// |-------------------|-----------------|------------------------|
/// | does not exist | `None` (→ 404) | `None` (→ 404) |
/// | exists, visible | `Some(Visible)` | `Some(Visible)` |
/// | exists, hidden | `None` (→ 404) | `Some(Restricted)` |
///
/// **SECURITY**: only call from client-mask (full-token) paths.
/// Role-token paths must use [`node_info`] after an explicit visibility check.
pub fn node_info_masked(
&self,
key: &str,
mask: &crate::mask::NodeMask,
) -> Option<MaskedNodeResult> {
let id = self.ids.get(key)?;
if mask.contains_id(id) {
Some(MaskedNodeResult::Visible(self.node_info(key)?))
} else {
match mask.mode() {
crate::mask::MaskMode::Stub => Some(MaskedNodeResult::Restricted),
crate::mask::MaskMode::Omit => None,
}
}
}
/// Get edges for `key` with mask-aware hidden-endpoint handling.
///
/// - Omit mode: edges to hidden endpoints are excluded (same as role-path filtering).
/// - Stub mode: edges to hidden endpoints are included; `src_restricted`/`dst_restricted`
/// is `true` for each hidden endpoint.
///
/// Unknown key → [`GraphError::KeyNotFound`].
///
/// **SECURITY**: only call from client-mask (full-token) paths.
pub fn node_edges_masked(
&self,
key: &str,
mask: &crate::mask::NodeMask,
) -> Result<Vec<MaskedEdge>> {
self.ensure_v8_base_sections_loaded();
let id = self
.ids
.get(key)
.ok_or_else(|| GraphError::KeyNotFound { key: key.into() })?;
let derived: BTreeSet<(u32, u32, u32)> = self
.engine
.provenance_touching(id)
.map(|(_rule, etype, src, dst)| (etype, src, dst))
.collect();
let mut edges = Vec::new();
let tv = self.topo_view();
for etype in tv.etypes() {
// etype comes from the archived CSR (access_unchecked, no eager CRC).
// A bit-flip in the large TOPOLOGY section can produce an etype id
// that is not in the interner. Return Corrupt rather than panic.
let edge_type = self
.syms
.resolve(etype)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("v8: topology etype {etype} not in interner"),
})?
.to_string();
for dir in [Direction::Out, Direction::In] {
for &nbr in tv.neighbors(etype, dir, id).as_ref() {
let nbr_restricted = !mask.contains_id(nbr);
if nbr_restricted && mask.mode() == crate::mask::MaskMode::Omit {
continue;
}
let nbr_key = self
.ids
.key_of(nbr)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("topology id {nbr} has no key"),
})?
.to_string();
let (src_id, dst_id, src_key, dst_key, src_restricted, dst_restricted) =
match dir {
Direction::Out => {
(id, nbr, key.to_string(), nbr_key, false, nbr_restricted)
}
Direction::In => {
(nbr, id, nbr_key, key.to_string(), nbr_restricted, false)
}
};
edges.push(MaskedEdge {
edge_type: edge_type.clone(),
src_key,
src_restricted,
dst_key,
dst_restricted,
derived: derived.contains(&(etype, src_id, dst_id)),
});
}
}
}
edges.sort_by(|a, b| {
a.edge_type
.cmp(&b.edge_type)
.then(a.src_key.cmp(&b.src_key))
.then(a.dst_key.cmp(&b.dst_key))
});
edges.dedup_by(|a, b| {
a.edge_type == b.edge_type && a.src_key == b.src_key && a.dst_key == b.dst_key
});
Ok(edges)
}
/// Every directed edge incident on `key`, both directions, every etype.
///
/// Walk is `topology.etypes()` × `{Out, In}` × `neighbors()`. `derived` is
/// membership in [`RuleEngine::provenance_touching`] (O(degree) via the
/// Plan-8 `by_node` index). Sorted by `(edge_type, src_key, dst_key)`.
/// Unknown key → [`GraphError::KeyNotFound`].
pub fn node_edges(&self, key: &str) -> Result<Vec<EdgeInfo>> {
self.ensure_v8_base_sections_loaded();
let id = self
.ids
.get(key)
.ok_or_else(|| GraphError::KeyNotFound { key: key.into() })?;
let derived: BTreeSet<(u32, u32, u32)> = self
.engine
.provenance_touching(id)
.map(|(_rule, etype, src, dst)| (etype, src, dst))
.collect();
let mut edges = Vec::new();
let tv = self.topo_view();
for etype in tv.etypes() {
// Same guard as node_edges_masked: etype from unchecked-CRC CSR.
let edge_type = self
.syms
.resolve(etype)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("v8: topology etype {etype} not in interner"),
})?
.to_string();
for dir in [Direction::Out, Direction::In] {
for &nbr in tv.neighbors(etype, dir, id).as_ref() {
let (src, dst, src_key, dst_key) = match dir {
Direction::Out => (
id,
nbr,
key.to_string(),
self.ids
.key_of(nbr)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("topology id {nbr} has no key"),
})?
.to_string(),
),
Direction::In => (
nbr,
id,
self.ids
.key_of(nbr)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("topology id {nbr} has no key"),
})?
.to_string(),
key.to_string(),
),
};
edges.push(EdgeInfo {
edge_type: edge_type.clone(),
src_key,
dst_key,
derived: derived.contains(&(etype, src, dst)),
});
}
}
}
edges.sort_by(|a, b| {
a.edge_type
.cmp(&b.edge_type)
.then(a.src_key.cmp(&b.src_key))
.then(a.dst_key.cmp(&b.dst_key))
});
// Self-loops appear in both Out and In; sort makes the pair adjacent
// (sort key matches PartialEq for this case) so one pass drops the dup.
edges.dedup();
Ok(edges)
}
// ── Backup ────────────────────────────────────────────────────────────────
/// Copy this store to `dest` as a consistent, verified snapshot.
///
/// Copies every durable file in the database directory — `snapshot.bin`,
/// `wal.bin`, all `wal.<N>.archive` files, `wal.floor`, `wal.genesis`, and
/// `roles.json` — into a freshly created `dest` directory using OS-level
/// `copy` calls (no large in-process buffers).
///
/// # Consistency guarantee
///
/// The guarantee is **process-local**: the caller holds `&self`, which
/// prevents any concurrent writer in the **same process** from modifying
/// the files during the copy. Running `mushroomdb backup` against a
/// directory that is **concurrently being written by another process** (e.g.
/// `mushroomdb serve`) is **unsafe** — the copy can be torn. The post-copy
/// `verified: true` result reduces but does not eliminate the risk of a
/// silent corrupt backup (CRC catches many bit-flips; it cannot catch a
/// consistent mid-write snapshot).
///
/// **The safe path for a live-served store is `POST /backup` on the HTTP
/// server.** That handler acquires the read lock on the shared database
/// before calling this method, which is the correct cross-process
/// synchronisation point because the server is the single process writing
/// the files.
///
/// After copying, opens the destination read-only and runs the CRC section
/// verifier (`verify_snapshot`) to confirm byte-for-byte integrity.
/// `BackupReport::verified` reflects whether both checks passed.
///
/// Returns `Err` when `self` is not backed by a `RealFs` (e.g. `SimFs`).
pub fn backup_to(&self, dest: &std::path::Path) -> Result<BackupReport> {
// Derive source directory from snapshot_path (RealFs only).
let src_dir = match self.fs.snapshot_path() {
Some(p) => p.parent().map(|d| d.to_path_buf()).ok_or_else(|| {
GraphError::Io(std::io::Error::other("snapshot has no parent dir"))
})?,
None => {
return Err(GraphError::Io(std::io::Error::other(
"backup_to requires a real filesystem (RealFs)",
)))
}
};
std::fs::create_dir_all(dest)?;
let mut files: Vec<String> = Vec::new();
let mut bytes: u64 = 0;
// Helper: copy src_dir/name → dest/name if the file exists.
let mut try_copy = |name: &str| -> std::io::Result<()> {
let src_path = src_dir.join(name);
if src_path.exists() {
let n = std::fs::copy(&src_path, dest.join(name))?;
bytes += n;
files.push(name.to_string());
}
Ok(())
};
try_copy("snapshot.bin")?;
try_copy("snapshot.bin.bak")?;
try_copy("wal.bin")?;
try_copy("wal.floor")?;
try_copy("wal.genesis")?;
try_copy("roles.json")?;
// Copy WAL archives.
let archives = self.fs.list_archives()?;
for n in &archives {
let name = format!("wal.{n}.archive");
let n_bytes = std::fs::copy(src_dir.join(&name), dest.join(&name))?;
bytes += n_bytes;
files.push(name);
}
files.sort();
// Post-copy verification: open dest and run CRC checks.
let snap_in_dest = dest.join("snapshot.bin").exists();
let crc_ok = if snap_in_dest {
crate::verify_snapshot(dest)
.map(|results| results.iter().all(|(_, _, _, r)| r.is_ok()))
.unwrap_or(false)
} else {
true // WAL-only store: nothing to CRC-check in snapshot
};
let opens_ok = GraphDb::<core_storage::fs::RealFs>::open(dest).is_ok();
let verified = crc_ok && opens_ok;
Ok(BackupReport {
files,
bytes,
verified,
})
}
// ── Export helpers ────────────────────────────────────────────────────────
/// All live nodes, sorted by key (deterministic).
///
/// Reads base + WAL overlay. Tombstoned nodes are excluded.
pub fn all_nodes_for_export(&self) -> Vec<NodeInfo> {
self.ensure_v8_base_sections_loaded();
let pv = self.props_view();
let mut nodes = Vec::new();
for id in 0..self.ids.len() as u32 {
let Some(key) = self.ids.key_of(id) else {
continue;
};
let Some(&sym) = self.labels.get(id as usize) else {
continue;
};
if sym == u32::MAX {
continue; // tombstoned
}
let Some(label) = self.syms.resolve(sym) else {
continue;
};
let mut props = BTreeMap::new();
for field in pv.field_names() {
if let Some(vr) = pv.get(id, &field) {
props.insert(field, vr.into_value());
}
}
nodes.push(NodeInfo {
key: key.to_string(),
label: label.to_string(),
props,
});
}
nodes.sort_by(|a, b| a.key.cmp(&b.key));
nodes
}
/// All directed edges, sorted by `(edge_type, src, dst)`. Each edge appears once.
///
/// Derived edges carry `derived: true` and the creating rule's name in `rule`.
/// Manual edges carry `derived: false` and `rule: None`.
/// `weight` is the creating rule's `weight_prop` value read off the edge
/// (numeric only), mirroring the convention used by [`GraphDb::explain`]
/// and [`GraphDb::weighted_edges`]. Deterministic across runs on the same
/// store state.
pub fn all_edges_for_export(&self) -> Vec<ExportEdge> {
self.ensure_v8_base_sections_loaded();
// Build (etype_sym, src_id, dst_id) → rule_name for O(1) derivation lookup.
let mut prov: HashMap<(u32, u32, u32), String> = HashMap::new();
for (rule_name, triples) in self.engine.provenance() {
for &(etype, src, dst) in triples {
prov.insert((etype, src, dst), rule_name.clone());
}
}
// rule_name → weight_prop, for O(1) lookup per derived edge.
let weight_props: HashMap<&str, Option<&str>> = self
.engine
.rules()
.map(|r| (r.name.as_str(), r.weight_prop.as_deref()))
.collect();
let tv = self.topo_view();
let ep = self.edge_props_view();
let mut edges = Vec::new();
for id in 0..self.ids.len() as u32 {
let Some(key) = self.ids.key_of(id) else {
continue;
};
let Some(&lsym) = self.labels.get(id as usize) else {
continue;
};
if lsym == u32::MAX {
continue; // tombstoned
}
for etype_sym in tv.etypes() {
// etype from archived CSR (access_unchecked, no eager CRC).
// Skip edges whose etype is not in the interner; this can only
// occur with a corrupt large TOPOLOGY section (bit-flip on an
// etype field in the archived data). The function returns Vec,
// not Result, so we continue rather than propagate.
let Some(edge_type) = self.syms.resolve(etype_sym) else {
continue;
};
let edge_type = edge_type.to_string();
for &nbr in tv.neighbors(etype_sym, Direction::Out, id).as_ref() {
let Some(dst_key) = self.ids.key_of(nbr) else {
continue; // skip corrupt entries
};
let prov_key = (etype_sym, id, nbr);
let rule = prov.get(&prov_key).cloned();
let derived = rule.is_some();
let weight = rule
.as_deref()
.and_then(|rn| weight_props.get(rn).copied().flatten())
.and_then(|prop| match ep.get(etype_sym, id, nbr, prop) {
Some(Value::Float(f)) => Some(f),
Some(Value::Int(i)) => Some(i as f64),
_ => None,
});
edges.push(ExportEdge {
edge_type: edge_type.clone(),
src: key.to_string(),
dst: dst_key.to_string(),
derived,
rule,
weight,
});
}
}
}
edges.sort_by(|a, b| {
a.edge_type
.cmp(&b.edge_type)
.then(a.src.cmp(&b.src))
.then(a.dst.cmp(&b.dst))
});
edges
}
/// What each edge type *is*, without building one record per edge.
///
/// [`all_edges_for_export`](Self::all_edges_for_export) answers the same
/// question by materialising every edge — three `String`s apiece, a
/// provenance `HashMap` over every derived edge, and a final sort. That is
/// the right shape for an export, and the wrong one for a summary: on a
/// store with 1.3 M derived edges it allocates hundreds of megabytes to
/// produce nine lines. This walks the topology instead, summing neighbour
/// slice lengths and collecting *label symbols* rather than label strings,
/// so the per-edge cost is an integer add and a set insert on a set with
/// as many members as the store has labels.
///
/// The rule names come off the rule *definitions*, which each declare the
/// `edge_type` they derive, so naming them costs one pass over the rules
/// rather than one provenance lookup per edge. That is also why `rules`
/// is a list: two rules may derive the same type — the association store
/// derives `INDUSTRY_ALIGNMENT` from both a talent→company and a
/// talent→job rule — and naming only one of them would be a half-truth.
/// A type with no rules is one written by hand.
///
/// `sample` is the first edge of the type in the store's own id order,
/// which is insertion order: deterministic for a given store, and not the
/// same as key order, which cannot be had without resolving a key per
/// edge. Sorted by `edge_type`.
pub fn edge_type_census(&self) -> Vec<EdgeTypeCensus> {
self.ensure_v8_base_sections_loaded();
let mut rules_by_type: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
for r in self.engine.rules() {
rules_by_type
.entry(r.edge_type.as_str())
.or_default()
.insert(r.name.as_str());
}
let tv = self.topo_view();
let node_count = self.ids.len() as u32;
let mut out = Vec::new();
for etype_sym in tv.etypes() {
// An etype the interner cannot resolve means a corrupt TOPOLOGY
// section; skip it rather than name it, as `all_edges_for_export`
// does for the same reason.
let Some(edge_type) = self.syms.resolve(etype_sym) else {
continue;
};
let mut edges: u64 = 0;
let mut src_syms: BTreeSet<u32> = BTreeSet::new();
let mut dst_syms: BTreeSet<u32> = BTreeSet::new();
let mut sample: Option<(u32, u32)> = None;
for id in 0..node_count {
let Some(&lsym) = self.labels.get(id as usize) else {
continue;
};
if lsym == u32::MAX {
continue; // tombstoned
}
let nbrs = tv.neighbors(etype_sym, Direction::Out, id);
let nbrs = nbrs.as_ref();
if nbrs.is_empty() {
continue;
}
edges += nbrs.len() as u64;
src_syms.insert(lsym);
for &nbr in nbrs {
if let Some(&dsym) = self.labels.get(nbr as usize) {
if dsym != u32::MAX {
dst_syms.insert(dsym);
}
}
}
if sample.is_none() {
sample = Some((id, nbrs[0]));
}
}
let resolve = |syms: &BTreeSet<u32>| -> Vec<String> {
syms.iter()
.filter_map(|&s| self.syms.resolve(s))
.map(ToString::to_string)
.collect()
};
out.push(EdgeTypeCensus {
edge_type: edge_type.to_string(),
edges,
src_labels: resolve(&src_syms),
dst_labels: resolve(&dst_syms),
rules: rules_by_type
.get(edge_type)
.map(|rs| rs.iter().map(ToString::to_string).collect())
.unwrap_or_default(),
sample: sample.and_then(|(s, d)| {
Some((
self.ids.key_of(s)?.to_string(),
self.ids.key_of(d)?.to_string(),
))
}),
});
}
out.sort_by(|a, b| a.edge_type.cmp(&b.edge_type));
out
}
/// All directed edges of `edge_type`, with the raw value of `weight_prop`
/// on each edge when given.
///
/// `weight` is `Some(f)` only when `weight_prop` is set and the edge
/// carries that property with a numeric (`Int`/`Float`) value; otherwise
/// `None` — callers that want a default weight (e.g. `1.0` for missing
/// props) apply it themselves, matching the convention used internally
/// by [`GraphDb::pagerank`], [`GraphDb::connected_components`],
/// [`GraphDb::degree_centrality`], and [`GraphDb::communities`].
///
/// Sorted by `(src, dst)` for determinism. Reads the unified topology
/// (manual + rule-derived edges). An unknown `edge_type` returns an
/// empty vec.
pub fn weighted_edges(
&self,
edge_type: &str,
weight_prop: Option<&str>,
) -> Vec<(String, String, Option<f64>)> {
let Some(etype_sym) = self.syms.get(edge_type) else {
return Vec::new();
};
let tv = self.topo_view();
let ep = self.edge_props_view();
let mut out = Vec::new();
for id in 0..self.ids.len() as u32 {
let Some(key) = self.ids.key_of(id) else {
continue;
};
let Some(&sym) = self.labels.get(id as usize) else {
continue;
};
if sym == u32::MAX {
continue; // tombstoned
}
for &nbr in tv.neighbors(etype_sym, Direction::Out, id).as_ref() {
let Some(dst_key) = self.ids.key_of(nbr) else {
continue;
};
let weight = weight_prop.and_then(|prop| match ep.get(etype_sym, id, nbr, prop) {
Some(Value::Float(f)) => Some(f),
Some(Value::Int(i)) => Some(i as f64),
_ => None,
});
out.push((key.to_string(), dst_key.to_string(), weight));
}
}
out.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
out
}
pub fn nodes_with_label(&self, label: &str) -> Vec<NodeRef<'_, F>> {
self.view()
.nodes_with_label(label)
.into_iter()
.map(|id| NodeRef { db: self, id })
.collect()
}
pub fn find_nodes(&self, label: &str, filter: &Filter) -> Vec<NodeRef<'_, F>> {
let view = self.view();
view.nodes_with_label(label)
.into_iter()
.filter(|&id| {
eval_filter(filter, &|field| {
view.prop(id, field).map(|vr| vr.into_value())
})
})
.map(|id| NodeRef { db: self, id })
.collect()
}
/// Returns `true` if any approximate (HNSW) VectorSimilar rule covers
/// `field`. Use as a capability probe: when `true`, `find_similar_vector`
/// with `label = None` will use the native ANN path rather than the O(n)
/// brute-force scan.
pub fn has_vector_rule(&self, field: &str) -> bool {
self.engine.hnsw_has_rule(field)
}
/// How many HNSW graphs this handle has built from scratch since it was
/// opened (one per side of an approximate rule).
///
/// An open that restored every graph from the snapshot reports `0`.
/// Exposed for tests that assert the open path reuses the persisted index
/// rather than rebuilding it; not part of the stable surface.
#[doc(hidden)]
pub fn hnsw_build_count(&self) -> u64 {
self.engine.hnsw_build_count()
}
/// How many rules this handle still holds a lazily-decoded HNSW graph for.
///
/// Zero before the first ANN query on a clean open, and again once the
/// live indexes own the graphs. See [`core_rules::RuleEngine::lazy_hnsw_len`].
/// Exposed for tests that assert the lazy copies are released; not part of
/// the stable surface.
#[doc(hidden)]
pub fn lazy_hnsw_len(&self) -> usize {
self.engine.lazy_hnsw_len()
}
/// Find nodes whose `field` vector is most similar to `q` (cosine
/// similarity), returning up to `k` results with similarity ≥ `min`,
/// sorted descending.
///
/// When `label` is `None` the search spans all labels (via
/// `hnsw_search_any_dst` or a full brute-force scan); when `label` is
/// `Some(lbl)` it restricts to nodes with that label.
///
/// Uses the HNSW index when one is available (fast path); otherwise falls
/// back to an O(n) brute-force scan.
///
/// **The index supplies candidates, never scores.** Its own distances are
/// `f32` (accurate to ~1e-6, so an exact duplicate scores 0.9999999), so
/// every candidate is re-scored from the `f64` property vectors by
/// [`exact_vector_similarity`] before `min`, the ordering and the reported
/// score are decided. `k + VECTOR_RESCORE_MARGIN` candidates are fetched so
/// the re-ordering cannot drop a true top-`k` member; see that constant for
/// the rule. The score a caller receives is therefore the same number the
/// brute-force path would have produced, to `f64` precision, and `min = 1.0`
/// finds an exact duplicate.
pub fn find_similar_vector(
&self,
field: &str,
label: Option<&str>,
q: &[f64],
k: usize,
min: f64,
) -> Vec<(String, f64)> {
self.find_similar_vector_filtered(field, label, q, k, min, None, None, false)
.expect("find_similar_vector_filtered is infallible without where_")
}
/// Like [`find_similar_vector`] but restricts results to nodes visible in
/// `mask`. Hidden nodes never appear in results; the mask is applied
/// **before** k-truncation so a caller still receives up to `k` visible
/// hits.
///
/// # HNSW path (widening beam)
///
/// When an HNSW index covers the request, the beam starts at an over-fetch
/// of `k × n / |visible|` (plus the rescore margin) when the mask's
/// selectivity is known from the index length, otherwise at `k` plus that
/// margin. If fewer than `k` visible candidates remain after the mask and
/// `min` filter, the beam doubles — the same ×2 loop exact `VectorSimilar`
/// rules use, capped at `ef_max()` (`EF_MAX` = 4,096). Reaching the cap,
/// or a beam that comes back short of its own width, falls through to the
/// exhaustive masked scan rather than returning a short result.
///
/// Every surviving candidate is re-scored from the `f64` property vectors,
/// exactly as [`find_similar_vector`] does and for the same reason.
///
/// # Brute-force path
///
/// When no HNSW index covers the request, or the beam cannot admit `k`
/// hits, the function builds a masked [`GraphView`] so that `nodes_all` /
/// `nodes_with_label` return only visible nodes, guaranteeing exact `k`
/// results (or all visible nodes if fewer than `k` exist).
pub fn find_similar_vector_masked(
&self,
field: &str,
label: Option<&str>,
q: &[f64],
k: usize,
min: f64,
mask: &crate::mask::NodeMask,
) -> Vec<(String, f64)> {
self.find_similar_vector_filtered(field, label, q, k, min, Some(mask), None, false)
.expect("find_similar_vector_filtered is infallible without where_")
}
/// Exact or ANN kNN with optional key-list `mask` and property `where_`.
///
/// `where_` present and failing [`PropPredicate::validate_named`] `"where"`
/// → `QueryError`. `exact=true` or `where_=Some` skip HNSW and GEMM-brute
/// the candidate set (`label ∩ mask ∩ holds(where)`). `mask` alone still
/// uses HNSW when an index covers the field.
#[allow(clippy::too_many_arguments)]
pub fn find_similar_vector_filtered(
&self,
field: &str,
label: Option<&str>,
q: &[f64],
k: usize,
min: f64,
mask: Option<&crate::mask::NodeMask>,
where_: Option<&PropPredicate>,
exact: bool,
) -> Result<Vec<(String, f64)>> {
if let Some(pred) = where_ {
pred.validate_named("where")
.map_err(|detail| GraphError::QueryError { detail })?;
}
// Ensure any HNSW blobs retained from the snapshot are deserialized
// before the first ANN query on a clean-open (no-WAL) path. The
// section read has to come first: on a clean open nothing else has
// called it, so without it `retained_hnsw_blobs` is empty,
// `ensure_hnsw_loaded` caches an empty map in its `OnceLock`, and every
// approximate query on the handle runs brute force — correct results,
// silently off the index. Both calls are idempotent and cheap once hot.
self.ensure_v8_base_sections_loaded();
self.engine.ensure_hnsw_loaded();
let norm: f64 = q.iter().map(|x| x * x).sum::<f64>().sqrt();
if norm == 0.0 {
return Ok(vec![]);
}
if let Some(m) = mask {
if k == 0 || m.is_empty() {
return Ok(vec![]);
}
}
let q_unit: Vec<f64> = q.iter().map(|x| x / norm).collect();
// `where` implies exact: a predicate must not ride a silent ANN.
let skip_hnsw = exact || where_.is_some();
if !skip_hnsw {
if let Some(mask) = mask {
if let Some(out) =
self.find_similar_hnsw_masked(field, label, &q_unit, k, min, mask)
{
return Ok(out);
}
} else if let Some(out) = self.find_similar_hnsw(field, label, &q_unit, k, min) {
return Ok(out);
}
}
let view = match mask {
Some(m) => self.view_masked(m),
None => self.view(),
};
let candidate_ids = Self::vector_candidates(&view, label, where_);
Ok(self.brute_vector_hits(&view, candidate_ids, field, &q_unit, k, min))
}
/// Unmasked HNSW path. `None` when no populated index covers the request.
fn find_similar_hnsw(
&self,
field: &str,
label: Option<&str>,
q_unit: &[f64],
k: usize,
min: f64,
) -> Option<Vec<(String, f64)>> {
// Try HNSW fast path.
// `None` label searches across all VectorSimilar rules covering `field`
// (merging their results); `Some(lbl)` restricts to rules whose
// dst_label matches. Returns `None` when no populated HNSW index
// covers the request — the O(n) brute-force fallback handles that case.
let over_k = k.saturating_add(VECTOR_RESCORE_MARGIN);
let hits = match label {
Some(lbl) => self.engine.hnsw_search_dst(field, lbl, q_unit, over_k)?,
None => self.engine.hnsw_search_any_dst(field, q_unit, over_k)?,
};
// Candidates only: the index's `f32` similarity is discarded and
// each hit is re-scored against the `f64` vectors.
let view = self.view();
let mut out: Vec<(String, f64)> = hits
.into_iter()
.filter_map(|(id, _)| {
let sim = exact_vector_similarity(&view, id, field, q_unit)?;
if sim < min {
return None;
}
Some((self.ids.key_of(id)?.to_string(), sim))
})
.collect();
out.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.0.cmp(&b.0))
});
out.truncate(k);
Some(out)
}
/// Masked HNSW widening beam. `None` when no index covers the request or
/// the beam cannot admit `k` visible hits (caller falls through to brute).
fn find_similar_hnsw_masked(
&self,
field: &str,
label: Option<&str>,
q_unit: &[f64],
k: usize,
min: f64,
mask: &crate::mask::NodeMask,
) -> Option<Vec<(String, f64)>> {
let index_len = match label {
Some(lbl) => self.engine.hnsw_dst_len(field, lbl, q_unit.len()),
None => self.engine.hnsw_any_dst_len(field, q_unit.len()),
};
let n = index_len?;
// Same ceiling the exact-rule widening loop in `hnsw_candidates`
// consults — including the `with_ef_max` test hook.
let cap = ef_max();
let visible = mask.len();
let mut ef = k.saturating_add(VECTOR_RESCORE_MARGIN);
if visible > 0 && n > 0 {
let over = k
.saturating_mul(n)
.div_ceil(visible)
.saturating_add(VECTOR_RESCORE_MARGIN);
ef = ef.max(over);
}
loop {
let hits = match label {
Some(lbl) => self
.engine
.hnsw_search_dst_with_ef(field, lbl, q_unit, ef, ef),
None => self
.engine
.hnsw_search_any_dst_with_ef(field, q_unit, ef, ef),
};
let hits = hits?;
let full = hits.len() == ef;
let mut out = self.score_masked_hnsw_hits(&hits, field, q_unit, min, mask);
if out.len() >= k {
out.truncate(k);
return Some(out);
}
// Short of its width (frontier exhausted) or at the ceiling:
// a wider beam reaches nothing new, so the scan answers.
if !full || ef >= cap {
return None;
}
ef = ef.saturating_mul(2);
}
}
/// `label ∩ mask ∩ holds(where)`. Index fast path when `label` is `Some`
/// and `(label, where.field)` is enabled; otherwise scan with `visible()`.
fn vector_candidates(
view: &GraphView<'_>,
label: Option<&str>,
where_: Option<&PropPredicate>,
) -> Vec<u32> {
if let (Some(lbl), Some(pred)) = (label, where_) {
let indexed = view
.prop_index
.is_some_and(|idx| idx.is_enabled(lbl, &pred.field));
if indexed {
match (&pred.eq, &pred.in_) {
(Some(eq), None) => {
if let Some(ids) = view.nodes_with_prop(lbl, &pred.field, eq) {
return ids;
}
}
(None, Some(allowed)) => {
let mut seen = HashSet::new();
let mut out = Vec::new();
for v in allowed {
if let Some(ids) = view.nodes_with_prop(lbl, &pred.field, v) {
for id in ids {
if seen.insert(id) {
out.push(id);
}
}
}
}
return out;
}
_ => {}
}
}
}
let mut ids: Vec<u32> = match label {
Some(lbl) => view
.nodes_with_label(lbl)
.into_iter()
.filter(|&id| view.visible(id))
.collect(),
None => view.nodes_all(),
};
if let Some(pred) = where_ {
ids.retain(|&id| match view.prop(id, &pred.field) {
None => pred.holds(None),
Some(vr) => pred.holds(Some(vr.as_value())),
});
}
ids
}
/// Exact brute kNN: pack candidates at `q_unit`'s dim, GEMV, keep
/// `score >= min`, sort `(sim desc, key asc)`, truncate to `k`.
fn brute_vector_hits(
&self,
view: &GraphView<'_>,
candidate_ids: impl IntoIterator<Item = u32>,
field: &str,
q_unit: &[f64],
k: usize,
min: f64,
) -> Vec<(String, f64)> {
let rows: Vec<(u32, std::borrow::Cow<'_, [f64]>)> = candidate_ids
.into_iter()
.filter_map(|id| crate::exact_knn::vector_f64(view, id, field).map(|v| (id, v)))
.collect();
let packed =
crate::exact_knn::pack(rows.iter().map(|(id, v)| (*id, v.as_ref())), q_unit.len());
let scores = crate::exact_knn::gemv(&packed, q_unit);
let mut scored: Vec<(String, f64)> = packed
.ids
.iter()
.zip(scores.iter())
.filter_map(|(&id, &sim)| {
if sim < min {
return None;
}
let key = self.ids.key_of(id)?.to_string();
Some((key, sim))
})
.collect();
scored.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.0.cmp(&b.0))
});
scored.truncate(k);
scored
}
/// Exact cosine top-k for each key in `keys`, scored only against `keys`.
///
/// `min` is cosine similarity in [-1, 1], inclusive (`score >= min`), the
/// same unit and inequality as `find_similar_vector`. Self-matches are
/// excluded. Unknown keys, keys with no `field`, zero-norm or wrong-dim
/// embeddings are omitted as both query and candidate. Duplicate keys are
/// collapsed, first-seen order. Empty `keys` → empty `Ok(vec![])`. Never
/// uses HNSW. `n > PAIRWISE_MAX_N` → `QueryError`.
#[allow(clippy::type_complexity)]
pub fn pairwise_similar(
&self,
keys: &[&str],
field: &str,
k: usize,
min: f64,
) -> Result<Vec<(String, Vec<(String, f64)>)>> {
let mut seen = HashSet::new();
let mut unique_ids = Vec::new();
for key in keys {
let Some(id) = self.ids.get(key) else {
continue;
};
if seen.insert(id) {
unique_ids.push(id);
}
}
let max_n = crate::exact_knn::pairwise_max_n();
if unique_ids.len() > max_n {
return Err(GraphError::QueryError {
detail: format!(
"pairwise_similar: n={} exceeds PAIRWISE_MAX_N ({max_n})",
unique_ids.len()
),
});
}
if unique_ids.is_empty() {
return Ok(Vec::new());
}
let view = self.view();
let mut rows: Vec<(u32, std::borrow::Cow<'_, [f64]>)> = Vec::new();
let mut counts: HashMap<usize, usize> = HashMap::new();
for id in unique_ids {
let Some(v) = crate::exact_knn::vector_f64(&view, id, field) else {
continue;
};
let norm: f64 = v.iter().map(|x| x * x).sum::<f64>().sqrt();
if norm == 0.0 {
continue;
}
*counts.entry(v.len()).or_default() += 1;
rows.push((id, v));
}
if rows.is_empty() {
return Ok(Vec::new());
}
let dim = counts
.into_iter()
.max_by_key(|&(d, c)| (c, d))
.map(|(d, _)| d)
.expect("rows non-empty");
let packed = crate::exact_knn::pack(rows.iter().map(|(id, v)| (*id, v.as_ref())), dim);
let n = packed.ids.len();
if n == 0 {
return Ok(Vec::new());
}
let src_keys: Vec<String> = packed
.ids
.iter()
.map(|&id| self.ids.key_of(id).unwrap_or("").to_string())
.collect();
let mut out = Vec::with_capacity(n);
if n <= crate::exact_knn::pairwise_gram_max() {
let sims = crate::exact_knn::gram(&packed);
for i in 0..n {
out.push(Self::topk_from_row(
&src_keys,
i,
&sims[i * n..(i + 1) * n],
k,
min,
));
}
} else {
for i in 0..n {
let row = &packed.data[i * packed.dim..(i + 1) * packed.dim];
let scores = crate::exact_knn::gemv(&packed, row);
out.push(Self::topk_from_row(&src_keys, i, &scores, k, min));
}
}
Ok(out)
}
/// Neighbours of packed row `i`: drop self, keep `score >= min`, sort
/// `(sim desc, key asc)`, truncate to `k`. Packed srcs with no survivors
/// still appear as `(src, [])`.
fn topk_from_row(
src_keys: &[String],
i: usize,
scores: &[f64],
k: usize,
min: f64,
) -> (String, Vec<(String, f64)>) {
let mut neigh: Vec<(String, f64)> = scores
.iter()
.enumerate()
.filter_map(|(j, &sim)| {
if i == j || sim < min {
return None;
}
Some((src_keys[j].clone(), sim))
})
.collect();
neigh.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.0.cmp(&b.0))
});
neigh.truncate(k);
(src_keys[i].clone(), neigh)
}
/// Re-score HNSW candidates from the `f64` vectors, drop hidden / below-`min`
/// hits, order by score then key. The index's own `f32` similarity is discarded.
fn score_masked_hnsw_hits(
&self,
hits: &[(u32, f64)],
field: &str,
q_unit: &[f64],
min: f64,
mask: &crate::mask::NodeMask,
) -> Vec<(String, f64)> {
let view = self.view_masked(mask);
let mut out: Vec<(String, f64)> = hits
.iter()
.copied()
.filter(|&(id, _)| mask.visible.contains(&id))
.filter_map(|(id, _)| {
let sim = exact_vector_similarity(&view, id, field, q_unit)?;
if sim < min {
return None;
}
Some((self.ids.key_of(id)?.to_string(), sim))
})
.collect();
out.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.0.cmp(&b.0))
});
out
}
/// Read a single property from an edge.
///
/// Returns `None` when the edge does not exist, the field is absent, or any
/// of the string keys cannot be resolved to interned ids. Only edge props
/// written by rules (weight fields) are accessible without a `set_edge_prop`
/// binding; topology-only edges (no props set) return `None` for every field.
pub fn get_edge_prop(
&self,
edge_type: &str,
src_key: &str,
dst_key: &str,
field: &str,
) -> Option<Value> {
let etype = self.syms.get(edge_type)?;
let src = self.ids.get(src_key)?;
let dst = self.ids.get(dst_key)?;
self.edge_props_view().get(etype, src, dst, field)
}
/// Lex → parse → plan → execute `cypher` over a read-only view.
/// Every pipeline `Err(String)` becomes `GraphError::QueryError` with a
/// stage prefix (`lex:` / `parse:` / `plan:` / `execute:`).
pub fn query(&self, cypher: &str, params: &BTreeMap<String, Value>) -> Result<ResultSet> {
let tokens = lex(cypher).map_err(|e| GraphError::QueryError {
detail: format!("lex: {e}"),
})?;
let union = parse_read(&tokens).map_err(|e| GraphError::QueryError {
detail: format!("parse: {e}"),
})?;
let t0 = std::time::Instant::now();
let result = execute_union(&self.view(), &union, &Params(params)).map_err(|e| {
GraphError::QueryError {
detail: format!("execute: {e}"),
}
});
let elapsed_ms = t0.elapsed().as_millis() as u64;
let threshold = self.slow_query_threshold_ms;
if threshold > 0 && elapsed_ms >= threshold {
eprintln!("[mushroomdb] slow query ({elapsed_ms}ms): {cypher}");
let entry = SlowQueryEntry {
ms: elapsed_ms,
query: cypher.to_string(),
at_commit: self.commit_seq,
};
if let Ok(mut log) = self.slow_queries.lock() {
if log.entries.len() == SLOW_QUERY_RING_CAP {
log.entries.pop_front();
}
log.entries.push_back(entry);
log.total += 1;
}
}
result
}
/// Convenience entry-point that accepts a slice of `(name, value)` pairs
/// instead of a pre-built `BTreeMap`. Equivalent to building the map and
/// calling [`GraphDb::query`].
pub fn query_with_params(&self, cypher: &str, params: &[(&str, Value)]) -> Result<ResultSet> {
let map: BTreeMap<String, Value> = params
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect();
self.query(cypher, &map)
}
/// Execute a Cypher write statement (CREATE / MATCH…SET / MATCH…DELETE / MERGE).
///
/// All mutations flow through the same `insert_node` / `set_prop` /
/// `delete_edge` / `insert_edge` path as the Rust API so the rule engine
/// fires and the WAL captures everything with one fsync per statement.
///
/// Returns a one-row [`ResultSet`] with columns `created`, `properties_set`,
/// and `deleted` matching the write-result contract.
///
/// **Mutation routing**: mutations are collected into a single
/// [`BatchBuilder`] and committed atomically (one WAL `Batch` frame, one
/// fsync). The MATCH phase for SET/DELETE uses a read-only `execute` call
/// over `self.view()` — the borrow is dropped before the batch is opened.
///
/// **Limitations (v1)**:
/// - SET RHS must be a literal, `$param`, or arithmetic; bare property copy → named error.
/// - `DETACH DELETE n` → calls `delete_node` for each matched node (removes all edges).
/// - Bare `DELETE n` → error if n has any incident edges; succeeds for isolated nodes.
/// - MERGE supports `ON CREATE SET` / `ON MATCH SET` in the same write batch.
/// - Deleting a derived edge → named error "cannot delete derived edge".
pub fn query_write(
&mut self,
cypher: &str,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
let tokens = lex(cypher).map_err(|e| GraphError::QueryError {
detail: format!("lex: {e}"),
})?;
let stmt = parse_write(&tokens).map_err(|e| GraphError::QueryError {
detail: format!("parse: {e}"),
})?;
self.exec_write_stmt(stmt, params)
}
fn exec_write_stmt(
&mut self,
stmt: WriteStatement,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
match stmt {
WriteStatement::Create(s) => self.exec_create(s, params),
WriteStatement::MatchSet(s) => self.exec_match_set(s, params),
WriteStatement::MatchDelete(s) => self.exec_match_delete(s, params),
WriteStatement::MatchDeleteNode(s) => self.exec_match_delete_node(s, params),
WriteStatement::Merge(s) => self.exec_merge(s, params),
}
}
fn exec_create(
&mut self,
stmt: core_query::cypher::CreateStmt,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
// Extract the node key from props: require a string-valued `id` field.
let mut var_to_key: BTreeMap<String, String> = BTreeMap::new();
for node in &stmt.nodes {
let var = node.var.as_deref().unwrap_or("_cn0");
let key = node
.props
.iter()
.find(|(f, _)| f == "id")
.and_then(|(_, v)| {
if let Value::Str(s) = v {
Some(s.clone())
} else {
None
}
})
.ok_or_else(|| GraphError::QueryError {
detail: format!(
"CREATE node ({}:{}) requires a string 'id' property",
var, node.label
),
})?;
var_to_key.insert(var.to_string(), key);
}
let mut batch = self.batch();
let mut created: usize = 0;
for node in &stmt.nodes {
let var = node.var.as_deref().unwrap_or("_cn0");
let key = &var_to_key[var];
batch.insert_node(&node.label, key, node.props.clone());
created += 1;
}
for edge in &stmt.edges {
let src_key = var_to_key
.get(&edge.src_var)
.ok_or_else(|| GraphError::QueryError {
detail: format!("CREATE edge src variable '{}' is not bound", edge.src_var),
})?;
let dst_key = var_to_key
.get(&edge.dst_var)
.ok_or_else(|| GraphError::QueryError {
detail: format!("CREATE edge dst variable '{}' is not bound", edge.dst_var),
})?;
batch.insert_edge(&edge.etype, src_key, dst_key);
}
batch.commit()?;
// Optional RETURN clause: project created bindings as a read result.
if let Some(returns) = stmt.returns {
// Each created node is looked up by its key via a separate MATCH pattern.
// Multiple single-node patterns cross-join to produce 1 output row with
// all variables bound (each pattern returns exactly 1 row).
let patterns: Vec<Pattern> = stmt
.nodes
.iter()
.map(|node| {
let var = node.var.as_deref().unwrap_or("_cn0");
let key = var_to_key[var].clone();
Pattern {
start: NodePat {
var: Some(var.to_string()),
label: Some(node.label.clone()),
props: vec![("id".to_string(), Operand::Lit(Value::Str(key)))],
},
chain: vec![],
shortest: false,
}
})
.collect();
let q = Query {
matches: patterns,
optional_clauses: vec![],
where_expr: None,
unwinds: vec![],
post_unwind_where: None,
stages: vec![],
returns,
distinct: false,
order_by: vec![],
skip: None,
limit: None,
};
let ops = plan(&q).map_err(|e| GraphError::QueryError {
detail: format!("plan: {e}"),
})?;
return execute(&self.view(), &ops, &Params(params)).map_err(|e| {
GraphError::QueryError {
detail: format!("execute: {e}"),
}
});
}
let mut rs = write_result_set();
rs.push_row(vec![
Some(Value::Int(created as i64)),
Some(Value::Int(0)),
Some(Value::Int(0)),
]);
Ok(rs)
}
fn exec_match_set(
&mut self,
stmt: core_query::cypher::MatchSetStmt,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
let project_returns = stmt.returns.clone();
// Collect unique node vars targeted by SET clauses, plus RETURN bindings
// so the post-write projection can look them up by key.
let mut set_vars: Vec<String> = Vec::new();
for s in &stmt.sets {
if !set_vars.contains(&s.var) {
set_vars.push(s.var.clone());
}
}
let rel_vars = pattern_rel_vars(&stmt.matches);
let mut lookup_vars = set_vars.clone();
for v in pattern_node_vars(&stmt.matches) {
add_var(&mut lookup_vars, &v);
}
if let Some(ref returns) = project_returns {
for v in ret_node_vars(returns) {
if !rel_vars.iter().any(|r| r == &v) {
add_var(&mut lookup_vars, &v);
}
}
}
// Synthesize a read query: MATCH … WHERE … RETURN <lookup_vars>, <set_values…>
// SET values are projected as ScalarExpr items so that arithmetic expressions
// (e.g. `SET n.score = n.score * 1.5`) are evaluated in the matched-row context.
let mut set_returns: Vec<RetItem> = lookup_vars
.iter()
.map(|v| RetItem {
value: RetVal::Var(v.clone()),
alias: None,
})
.collect();
// One computed column per SET clause; alias is `__sv_<i>`.
let set_val_cols: Vec<String> = stmt
.sets
.iter()
.enumerate()
.map(|(i, _)| format!("__sv_{i}"))
.collect();
for (sc, col) in stmt.sets.iter().zip(&set_val_cols) {
set_returns.push(RetItem {
value: RetVal::ScalarExpr(sc.value.clone()),
alias: Some(col.clone()),
});
}
// Capture relationship types while r is bound; SET does not change them.
for r in &rel_vars {
set_returns.push(RetItem {
value: RetVal::FuncCall {
name: "type".into(),
args: vec![Operand::Var(r.clone())],
},
alias: Some(rel_type_alias(r)),
});
}
let read_q = Query {
matches: stmt.matches.clone(),
optional_clauses: vec![],
where_expr: stmt.where_expr.clone(),
unwinds: vec![],
post_unwind_where: None,
stages: vec![],
returns: set_returns,
distinct: false,
order_by: vec![],
skip: None,
limit: None,
};
let ops = plan(&read_q).map_err(|e| GraphError::QueryError {
detail: format!("plan: {e}"),
})?;
// MATCH phase is read-only; borrow ends before batch opens.
//
// When a role-scoped write is in flight, run the MATCH read through
// view_masked so hidden nodes are invisible → hidden ≡ absent ≡
// zero-rows (no SetProp ops generated, no existence-oracle 403).
// Full-authority writes (pending_write_authz=None) keep view().
let match_rs = {
let mask_opt = self.pending_write_authz.as_ref().map(|a| a.mask.clone());
if let Some(ref mask) = mask_opt {
execute(&self.view_masked(mask), &ops, &Params(params))
} else {
execute(&self.view(), &ops, &Params(params))
}
}
.map_err(|e| GraphError::QueryError {
detail: format!("execute: {e}"),
})?;
// Collect (key, field, value) for each matched row × each SET clause.
let mut set_ops: Vec<(String, String, Value)> = Vec::new();
for row_i in 0..match_rs.len() {
for (sc, col) in stmt.sets.iter().zip(&set_val_cols) {
let key = match match_rs.get(row_i, &sc.var) {
Some(Value::Str(k)) => k.clone(),
_ => {
return Err(GraphError::QueryError {
detail: format!(
"SET variable '{}' did not resolve to a node key",
sc.var
),
})
}
};
// The SET value was already evaluated by the executor.
let value = match match_rs.get(row_i, col) {
Some(v) => v.clone(),
None => {
return Err(GraphError::QueryError {
detail: format!(
"SET value for {}.{} evaluated to null",
sc.var, sc.field
),
})
}
};
set_ops.push((key, sc.field.clone(), value));
}
}
// Apply as one atomic batch.
let props_set = set_ops.len();
let mut batch = self.batch();
for (key, field, value) in set_ops {
batch.set_prop(&key, &field, value);
}
batch.commit()?;
if let Some(returns) = project_returns {
return project_set_return_rows(self, &rel_vars, &match_rs, &returns, params);
}
let mut rs = write_result_set();
rs.push_row(vec![
Some(Value::Int(0)),
Some(Value::Int(props_set as i64)),
Some(Value::Int(0)),
]);
Ok(rs)
}
fn exec_match_delete(
&mut self,
stmt: core_query::cypher::MatchDeleteStmt,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
// Collect unique node vars needed to identify edge endpoints.
let mut node_vars: Vec<String> = Vec::new();
for ed in &stmt.deletes {
if !node_vars.contains(&ed.src_var) {
node_vars.push(ed.src_var.clone());
}
if !node_vars.contains(&ed.dst_var) {
node_vars.push(ed.dst_var.clone());
}
}
// Synthesize read query.
let returns: Vec<RetItem> = node_vars
.iter()
.map(|v| RetItem {
value: RetVal::Var(v.clone()),
alias: None,
})
.collect();
let read_q = Query {
matches: stmt.matches,
optional_clauses: vec![],
where_expr: stmt.where_expr,
unwinds: vec![],
post_unwind_where: None,
stages: vec![],
returns,
distinct: false,
order_by: vec![],
skip: None,
limit: None,
};
let ops = plan(&read_q).map_err(|e| GraphError::QueryError {
detail: format!("plan: {e}"),
})?;
// Role-scoped writes: mask the MATCH read phase so hidden nodes are
// invisible → hidden ≡ absent ≡ zero-rows (spec §3.1, hidden ≡ absent).
let match_rs = {
let mask_opt = self.pending_write_authz.as_ref().map(|a| a.mask.clone());
if let Some(ref mask) = mask_opt {
execute(&self.view_masked(mask), &ops, &Params(params))
} else {
execute(&self.view(), &ops, &Params(params))
}
}
.map_err(|e| GraphError::QueryError {
detail: format!("execute: {e}"),
})?;
// Collect (etype, src_key, dst_key) for each row × each delete target.
let mut del_ops: Vec<(String, String, String)> = Vec::new();
for row_i in 0..match_rs.len() {
for ed in &stmt.deletes {
let src_key = match match_rs.get(row_i, &ed.src_var) {
Some(Value::Str(k)) => k.clone(),
_ => {
return Err(GraphError::QueryError {
detail: format!(
"DELETE src variable '{}' did not resolve to a node key",
ed.src_var
),
})
}
};
let dst_key = match match_rs.get(row_i, &ed.dst_var) {
Some(Value::Str(k)) => k.clone(),
_ => {
return Err(GraphError::QueryError {
detail: format!(
"DELETE dst variable '{}' did not resolve to a node key",
ed.dst_var
),
})
}
};
del_ops.push((ed.etype.clone(), src_key, dst_key));
}
}
// Apply as one atomic batch.
let deleted = del_ops.len();
let mut batch = self.batch();
for (etype, src_key, dst_key) in del_ops {
batch.delete_edge(&etype, &src_key, &dst_key);
}
batch.commit().map_err(|e| match e {
GraphError::RuleOwned { .. } => GraphError::QueryError {
detail: "cannot delete derived edge; retract via the rule or change the property"
.to_string(),
},
other => other,
})?;
let mut rs = write_result_set();
rs.push_row(vec![
Some(Value::Int(0)),
Some(Value::Int(0)),
Some(Value::Int(deleted as i64)),
]);
Ok(rs)
}
/// Execute `MATCH … [DETACH] DELETE <node_var> [, …]`.
///
/// Collects the matching node keys via an ephemeral read query, then calls
/// `delete_node` on each one. When `stmt.detach` is `false` (bare DELETE)
/// the executor first checks that the node has no incident edges; if any
/// remain it returns a named error matching openCypher semantics.
fn exec_match_delete_node(
&mut self,
stmt: MatchDeleteNodeStmt,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
// Build a read query returning only the node keys we need.
let returns: Vec<RetItem> = stmt
.node_vars
.iter()
.map(|v| RetItem {
value: RetVal::Var(v.clone()),
alias: None,
})
.collect();
let read_q = Query {
matches: stmt.matches,
optional_clauses: vec![],
where_expr: stmt.where_expr,
unwinds: vec![],
post_unwind_where: None,
stages: vec![],
returns,
distinct: false,
order_by: vec![],
skip: None,
limit: None,
};
let ops = plan(&read_q).map_err(|e| GraphError::QueryError {
detail: format!("plan: {e}"),
})?;
// Role-scoped writes: mask the MATCH read phase so hidden nodes are
// invisible → hidden ≡ absent ≡ zero-rows (spec §3.1, hidden ≡ absent).
let match_rs = {
let mask_opt = self.pending_write_authz.as_ref().map(|a| a.mask.clone());
if let Some(ref mask) = mask_opt {
execute(&self.view_masked(mask), &ops, &Params(params))
} else {
execute(&self.view(), &ops, &Params(params))
}
}
.map_err(|e| GraphError::QueryError {
detail: format!("execute: {e}"),
})?;
// Collect unique node keys to delete (deduplicate across rows × vars).
let mut keys: Vec<String> = Vec::new();
for row_i in 0..match_rs.len() {
for var in &stmt.node_vars {
if let Some(Value::Str(k)) = match_rs.get(row_i, var) {
if !keys.contains(k) {
keys.push(k.clone());
}
}
}
}
if !stmt.detach {
// openCypher bare DELETE: error if any matched node has incident edges.
for key in &keys {
if let Some(id) = self.ids.get(key) {
let tv = self.topo_view();
let has_edges = tv.etypes().any(|et| {
!tv.neighbors(et, Direction::Out, id).is_empty()
|| !tv.neighbors(et, Direction::In, id).is_empty()
});
if has_edges {
return Err(GraphError::QueryError {
detail: format!(
"Cannot delete node `{key}` because it still has incident edges. \
Use DETACH DELETE to remove the node and all its edges."
),
});
}
}
}
}
let mut nodes_deleted = 0i64;
let mut edges_deleted = 0i64;
for key in keys {
match self.delete_node(&key) {
Ok(report) => {
nodes_deleted += 1;
edges_deleted += (report.manual_edges + report.derived_edges) as i64;
}
Err(GraphError::KeyNotFound { .. }) => {
// Node may have been deleted by an earlier iteration (e.g., via
// multiple MATCH rows for the same node). Safe to skip.
}
Err(e) => return Err(e),
}
}
let mut rs = write_result_set();
rs.push_row(vec![
Some(Value::Int(0)),
Some(Value::Int(0)),
Some(Value::Int(nodes_deleted + edges_deleted)),
]);
Ok(rs)
}
/// Props the MERGE create arm inserts: the identifying key, plus `ns` when
/// the pattern named one, or the executing role's sole namespace when it
/// did not. A role bound to two or more namespaces cannot choose, and is
/// refused with [`MERGE_CREATE_NEEDS_ONE_NAMESPACE`]. The authorizer still
/// refuses a named `ns` the role cannot write.
fn merge_create_props(
&self,
key_field: &str,
key_value: &Value,
named_ns: Option<&Value>,
) -> Result<Vec<(String, Value)>> {
let mut props = vec![(key_field.to_string(), key_value.clone())];
if let Some(ns) = named_ns {
props.push((NS_PROP.to_string(), ns.clone()));
return Ok(props);
}
if let Some(ns) = self.merge_create_stamp_ns()? {
props.push((NS_PROP.to_string(), Value::Str(ns)));
}
Ok(props)
}
/// The namespace a role-scoped MERGE create stamps when the pattern does
/// not name `ns`. `None` = unscoped / full authority, so the node lands in
/// `default`.
fn merge_create_stamp_ns(&self) -> Result<Option<String>> {
let Some(authz) = self.pending_write_authz.as_ref() else {
return Ok(None);
};
let Some(def) = self.role_def_for(&authz.role) else {
return Ok(None);
};
match def.namespaces.as_deref() {
Some([only]) => Ok(Some(only.clone())),
Some(_) => Err(GraphError::RoleWriteDenied {
reason: MERGE_CREATE_NEEDS_ONE_NAMESPACE.to_string(),
}),
None => Ok(None),
}
}
fn exec_merge(
&mut self,
stmt: core_query::cypher::MergeStmt,
params: &BTreeMap<String, Value>,
) -> Result<ResultSet> {
// MERGE: check if a node with the given key already exists.
let key = match &stmt.key_value {
Value::Str(s) => s.clone(),
_ => {
return Err(GraphError::QueryError {
detail: format!(
"MERGE key value must be a string (got {:?})",
stmt.key_value
),
})
}
};
if let Some(var) = stmt.var.as_deref() {
for sc in stmt.on_create.iter().chain(&stmt.on_match) {
if sc.var != var {
return Err(GraphError::QueryError {
detail: format!(
"SET variable '{}' does not match MERGE variable '{var}'",
sc.var
),
});
}
}
}
// ── MERGE authz pre-check (when role-scoped) ─────────────────────────
//
// MERGE scope precondition: check create OR update scope for the
// declared label BEFORE calling `has_node` (timing-oracle closure,
// spec §6.2 "MERGE visibility oracle" item: hidden ≡ absent for
// unscoped roles — the scope denial fires without touching the key store).
//
// Clone to avoid holding a borrow on `self.pending_write_authz` while
// also calling `self.ids.get(key)`.
let merge_existed: bool = if let Some(authz) = self.pending_write_authz.clone() {
let has_create = authz.scope.create_labels.contains(&stmt.label);
let has_update = authz.scope.update_labels.contains(&stmt.label);
if !has_create && !has_update {
// Scope-before-lookup: 403 without has_node call (timing oracle
// closure — see test_merge_unscoped_no_key_lookup).
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: label '{}' not in write scope (create_labels)",
stmt.label
),
});
}
// Key lookup under mask.
match self.ids.get(key.as_str()) {
Some(id) if authz.mask.contains_id(id) => {
// Visible: must have update scope to proceed to match arm.
if !has_update {
return Err(GraphError::RoleWriteDenied {
reason: format!(
"role-bound token: label '{}' not in write scope (update_labels)",
stmt.label
),
});
}
true // existed = true → match arm
}
Some(_) => {
// Hidden: same error as absent to the role (spec §3.1/§3.3).
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: target node not visible".into(),
});
}
None => {
// Absent: must have create scope to proceed to the create arm.
//
// Update-only roles (create_labels empty, update_labels set):
// return the SAME "not visible" error as the hidden-key branch
// so hidden ≡ absent — no distinguishing oracle (spec §6.1
// "confirm existence of hidden nodes: No").
//
// Create-scoped roles (has_create=true): absent → create arm
// as before. The accepted structural key-existence disclosure
// (§THREAT-MODEL) applies only when the role holds create scope.
if !has_create {
return Err(GraphError::RoleWriteDenied {
reason: "role-bound token: target node not visible".into(),
});
}
false // existed = false → create arm
}
}
} else {
// Full authority: use the existing non-masked has_node check.
self.has_node(&key)
};
let existed = merge_existed;
let create_props = if existed {
None
} else {
Some(self.merge_create_props(&stmt.key_field, &stmt.key_value, stmt.ns.as_ref())?)
};
let mut created = 0i64;
if create_props.is_some() || !stmt.on_match.is_empty() {
let mut batch = self.batch();
if let Some(props) = create_props {
batch.insert_node(&stmt.label, &key, props);
for sc in &stmt.on_create {
let value = resolve_merge_set_value(&sc.value, params)?;
batch.set_prop(&key, &sc.field, value);
}
created = 1;
} else {
for sc in &stmt.on_match {
let value = resolve_merge_set_value(&sc.value, params)?;
batch.set_prop(&key, &sc.field, value);
}
}
batch.commit()?;
}
// Refresh the role mask so the just-created node is visible to this
// statement's RETURN (read-after-write). Safe: create_labels ⊆ read labels
// (apply_schema subset rule), so the new node's label is already in the
// role's read scope — this never widens beyond the role's declared labels.
if !existed {
if let Some(role) = self.pending_write_authz.as_ref().map(|a| a.role.clone()) {
let new_mask = self.mask_for_role(&role)?;
if let Some(a) = self.pending_write_authz.as_mut() {
a.mask = new_mask;
}
}
}
// Optional RETURN clause: project the node (created or matched) as a read result.
if let Some(returns) = stmt.returns {
let var = stmt.var.as_deref().unwrap_or("_mn0");
let q = Query {
matches: vec![Pattern {
start: NodePat {
var: Some(var.to_string()),
label: Some(stmt.label.clone()),
props: vec![("id".to_string(), Operand::Lit(stmt.key_value.clone()))],
},
chain: vec![],
shortest: false,
}],
optional_clauses: vec![],
where_expr: None,
unwinds: vec![],
post_unwind_where: None,
stages: vec![],
returns,
distinct: false,
order_by: vec![],
skip: None,
limit: None,
};
let ops = plan(&q).map_err(|e| GraphError::QueryError {
detail: format!("plan: {e}"),
})?;
// Use view_masked when a role-scoped write is in flight so the
// post-merge projection is consistent with the masked read phase.
let mask_opt = self.pending_write_authz.as_ref().map(|a| a.mask.clone());
return (if let Some(ref mask) = mask_opt {
execute(&self.view_masked(mask), &ops, &Params(params))
} else {
execute(&self.view(), &ops, &Params(params))
})
.map_err(|e| GraphError::QueryError {
detail: format!("execute: {e}"),
});
}
let mut rs = write_result_set();
rs.push_row(vec![
Some(Value::Int(created)),
Some(Value::Int(0)),
Some(Value::Int(0)),
]);
Ok(rs)
}
/// Return all rule-owned edges between `key_a` and `key_b` (either direction),
/// annotated with rule name, edge type, direction, and weight.
/// Results are sorted by (rule, edge_type).
/// Returns `Err(KeyNotFound)` if either key is unknown.
pub fn explain(&self, key_a: &str, key_b: &str) -> Result<Vec<Explanation>> {
self.ensure_v8_base_sections_loaded();
let id_a = self
.ids
.get(key_a)
.ok_or_else(|| GraphError::KeyNotFound { key: key_a.into() })?;
let id_b = self
.ids
.get(key_b)
.ok_or_else(|| GraphError::KeyNotFound { key: key_b.into() })?;
let mut results = Vec::new();
// Walk the smaller incident set so explain is O(min(deg(a), deg(b)))
// rather than O(total provenance).
let scan = if self.engine.provenance_touching_len(id_a)
<= self.engine.provenance_touching_len(id_b)
{
id_a
} else {
id_b
};
for (rule_name, etype, src, dst) in self.engine.provenance_touching(scan) {
if !((src == id_a && dst == id_b) || (src == id_b && dst == id_a)) {
continue;
}
let Some(rule_def) = self.engine.rules().find(|r| r.name == rule_name) else {
continue;
};
let edge_type = match self.syms.resolve(etype) {
Some(s) => s.to_string(),
None => continue,
};
// Provenance (src, dst) ids come from the archived PROVENANCE section
// (large, no eager CRC). A corrupt section can produce ids that are
// out of range; return Corrupt rather than panic.
let src_key = self
.ids
.key_of(src)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("v8: provenance src id {src} not in id table"),
})?
.to_string();
let dst_key = self
.ids
.key_of(dst)
.ok_or_else(|| GraphError::Corrupt {
detail: format!("v8: provenance dst id {dst} not in id table"),
})?
.to_string();
let stored = rule_def.weight_prop.as_deref().and_then(|prop| {
self.edge_props_view()
.get(etype, src, dst, prop)
.and_then(|v| {
if let Value::Float(f) = v {
Some(f)
} else {
None
}
})
});
// Rules that store no weight (KeyMatch/FieldEqual defaults, auto-FK)
// still have a score: recompute it from the predicate so explain
// never reports "no score" for an edge the engine scored. Via-hop
// rules score over their via set, not over (src, dst), so leave
// those None rather than report a number the rule did not produce.
let weight = stored.or_else(|| {
if rule_def.via_edge.is_some() {
return None;
}
let props_view = build_props_view(&self.props, &self.base);
let src_get = |field: &str| props_view.get(src, field).map(|vr| vr.into_value());
let dst_get = |field: &str| props_view.get(dst, field).map(|vr| vr.into_value());
let src_view = NodeView {
key: &src_key,
props: &src_get,
};
let dst_view = NodeView {
key: &dst_key,
props: &dst_get,
};
evaluate(&rule_def.predicate, &src_view, &dst_view)
});
results.push(Explanation {
rule: rule_name.to_string(),
edge_type,
src_key,
dst_key,
weight,
predicate: PredicateSummary {
approximate: rule_def.approximate,
..PredicateSummary::from(&rule_def.predicate)
},
via_edge: rule_def.via_edge.clone(),
});
}
results.sort_by(|a, b| a.rule.cmp(&b.rule).then(a.edge_type.cmp(&b.edge_type)));
Ok(results)
}
pub fn neighbors(&self, key: &str, edge_type: &str, dir: Direction) -> Result<Vec<String>> {
let id = self
.ids
.get(key)
.ok_or_else(|| GraphError::KeyNotFound { key: key.into() })?;
let Some(sym) = self.syms.get(edge_type) else {
return Ok(Vec::new());
};
self.topo_view()
.neighbors(sym, dir, id)
.iter()
.map(|&n| {
self.ids
.key_of(n)
.map(|k| k.to_string())
.ok_or_else(|| GraphError::Corrupt {
detail: format!("topology id {n} has no key"),
})
})
.collect::<Result<Vec<_>>>()
}
/// Unique directed degree of `key`. Unknown key → [`GraphError::KeyNotFound`].
/// Unknown `edge_type` → 0. [`crate::algo::AlgoDir::Both`] is out + in (sum).
pub fn degree(
&self,
key: &str,
edge_type: Option<&str>,
direction: crate::algo::AlgoDir,
) -> Result<u64> {
let id = self
.ids
.get(key)
.ok_or_else(|| GraphError::KeyNotFound { key: key.into() })?;
let topo = self.topo_view();
Ok(Self::unique_directed_degree(
&topo, &self.syms, id, edge_type, direction,
))
}
/// Unique directed degree for a subset or a label scan.
///
/// Unknown keys in `keys` are omitted (mask-like). `keys = Some(&[])` →
/// empty `Ok(vec![])`. `limit` is applied after sorting degree desc, key
/// asc, and only when `Some`. Invalid `where_` → `QueryError`.
#[allow(clippy::too_many_arguments)]
pub fn degrees(
&self,
keys: Option<&[String]>,
label: Option<&str>,
where_: Option<&PropPredicate>,
edge_type: Option<&str>,
direction: crate::algo::AlgoDir,
limit: Option<usize>,
) -> Result<Vec<(String, u64)>> {
if let Some(pred) = where_ {
pred.validate_named("where")
.map_err(|detail| GraphError::QueryError { detail })?;
}
if matches!(keys, Some(ks) if ks.is_empty()) {
return Ok(Vec::new());
}
let view = self.view();
let ids: Vec<u32> = match keys {
Some(ks) => {
let mut seen = HashSet::new();
let mut out = Vec::new();
for k in ks {
let Some(id) = view.ids.get(k) else {
continue;
};
if !seen.insert(id) {
continue;
}
if let Some(pred) = where_ {
let holds = match view.prop(id, &pred.field) {
None => pred.holds(None),
Some(vr) => pred.holds(Some(vr.as_value())),
};
if !holds {
continue;
}
}
out.push(id);
}
out
}
None => Self::vector_candidates(&view, label, where_),
};
let mut out: Vec<(String, u64)> = ids
.into_iter()
.filter_map(|id| {
let key = self.ids.key_of(id)?.to_string();
let deg =
Self::unique_directed_degree(&view.topo, view.syms, id, edge_type, direction);
Some((key, deg))
})
.collect();
out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
if let Some(lim) = limit {
out.truncate(lim);
}
Ok(out)
}
/// Unique neighbour count for `id` across `edge_type` (or all types) and
/// `direction`. Unknown `edge_type` → 0. `Both` sums out + in.
fn unique_directed_degree(
topo: &TopologyView<'_>,
syms: &Interner,
id: u32,
edge_type: Option<&str>,
direction: crate::algo::AlgoDir,
) -> u64 {
let dirs: &[Direction] = match direction {
crate::algo::AlgoDir::Out => &[Direction::Out],
crate::algo::AlgoDir::In => &[Direction::In],
crate::algo::AlgoDir::Both => &[Direction::Out, Direction::In],
};
match edge_type {
Some(name) => {
let Some(et) = syms.get(name) else {
return 0;
};
dirs.iter().map(|&d| topo.degree(et, d, id) as u64).sum()
}
None => topo
.etypes()
.map(|et| {
dirs.iter()
.map(|&d| topo.degree(et, d, id) as u64)
.sum::<u64>()
})
.sum(),
}
}
/// Return the last-change commit sequence for `key`, or `None` if the node
/// does not exist or has never been mutated since the last V5-V7 snapshot
/// (horizon-bounded for legacy stores).
///
/// The returned sequence is a monotonically increasing counter that starts
/// at 1 for the first commit after `open` and increments with every
/// successful write. WAL replay at open also assigns sequences (1..N for N
/// replayed frames), so sequences are consistent across snapshot+WAL cycles.
///
/// For V5-V7 stores opened without a V8 snapshot, nodes that were present
/// in the snapshot but not touched by any WAL frame will return `None`
/// (horizon-bounded: CAS against such nodes is only safe after the first
/// V8 snapshot or after the node is next mutated).
pub fn last_changed(&self, key: &str) -> Option<u64> {
let id = self.ids.get(key)?;
self.last_change.get(&id).copied()
}
/// The current commit sequence (number of successful commits since open,
/// including WAL replay frames). Useful for recording a baseline before
/// a read-modify-write cycle.
pub fn commit_seq(&self) -> u64 {
self.commit_seq
}
/// Check that all `preconds` are satisfied against the current db state.
/// Returns `Err(GraphError::CasConflict)` on the first failing precondition.
pub(crate) fn check_preconditions(&self, preconds: &[Precondition]) -> Result<()> {
for precond in preconds {
match precond {
Precondition::NodeUnchangedSince { key, expected } => {
// Missing entry means the node predates the WAL window or
// does not exist; treat as 0 (before any commit).
let actual = self.last_changed(key).unwrap_or_default();
if actual != *expected {
return Err(GraphError::CasConflict {
key: key.clone(),
expected: *expected,
actual,
});
}
}
Precondition::NodeAbsent { key } => {
// Node must not exist (not live).
if self.ids.get(key).is_some() {
let actual = self.last_changed(key).unwrap_or(0);
return Err(GraphError::CasConflict {
key: key.clone(),
expected: u64::MAX,
actual,
});
}
}
}
}
Ok(())
}
/// Apply a batch of mutations with compare-and-set preconditions.
///
/// All preconditions are checked atomically before any operation is applied.
/// If any precondition fails, the entire batch is rejected with
/// [`GraphError::CasConflict`] and no WAL frame is written.
///
/// # Returns
/// `(nodes_inserted, edges_inserted)` on success, same as [`write_batch`].
///
/// # Errors
/// - [`GraphError::CasConflict`] if any precondition is not satisfied.
/// - Any error that [`write_batch`] would return for the ops themselves.
pub fn write_batch_cas(
&mut self,
preconds: Vec<Precondition>,
ops: Vec<BatchOp>,
) -> Result<(usize, usize)> {
self.check_preconditions(&preconds)?;
self.commit_logged_batch(ops, None, None)
}
/// Update the per-node last-change map for a WAL record at commit `seq`.
///
/// Called after a successful apply to record which nodes were touched.
/// For replay, called with the WAL-frame's replayed seq.
///
/// Touch definition (see [`Precondition`] doc):
/// - InsertNode / InsertNodeId / SetProp / SetPropId / RemoveProp → the node.
/// - InsertEdge / InsertEdgeId / DeleteEdge → both src and dst.
/// - DeleteNode → node tombstoned; last_changed() returns None so no update needed.
/// - DerivedEdge markers, Intern, rule/view records → no-ops.
/// - Batch → recurse into inner records.
fn update_last_change_from_rec(&mut self, rec: &WalRecord, seq: u64) {
match rec {
WalRecord::InsertNode { key, .. }
| WalRecord::SetProp { key, .. }
| WalRecord::RemoveProp { key, .. } => {
if let Some(id) = self.ids.get(key) {
self.last_change.insert(id, seq);
}
}
WalRecord::InsertNodeId { key, .. } => {
if let Some(id) = self.ids.get(key) {
self.last_change.insert(id, seq);
}
}
WalRecord::SetPropId { id, .. } => {
self.last_change.insert(*id, seq);
}
WalRecord::InsertEdge {
src_key, dst_key, ..
}
| WalRecord::DeleteEdge {
src_key, dst_key, ..
} => {
if let Some(src_id) = self.ids.get(src_key) {
self.last_change.insert(src_id, seq);
}
if let Some(dst_id) = self.ids.get(dst_key) {
self.last_change.insert(dst_id, seq);
}
}
WalRecord::InsertEdgeId { src, dst, .. } => {
self.last_change.insert(*src, seq);
self.last_change.insert(*dst, seq);
}
// DeleteNode: node is tombstoned; last_changed(key) returns None for
// deleted keys (ids.get() returns None post-tombstone), so no update needed.
// History markers: state no-ops; the underlying mutation already
// touched the relevant nodes' last_change entries.
WalRecord::DeleteNode { .. }
| WalRecord::DerivedEdgeAdded { .. }
| WalRecord::DerivedEdgeRetracted { .. }
| WalRecord::Intern { .. }
| WalRecord::CreateRule { .. }
| WalRecord::DeleteRule { .. }
| WalRecord::RebuildRule { .. }
| WalRecord::CreateView { .. }
| WalRecord::DeleteView { .. }
| WalRecord::EnableFulltext { .. }
| WalRecord::DisableFulltext { .. }
| WalRecord::EnableIndex { .. }
| WalRecord::DisableIndex { .. } => {}
// RenameNode: node id is stable; update last_change via the new key.
// Called after apply(), so ids already reflects new_key.
WalRecord::RenameNode { new_key, .. } => {
if let Some(id) = self.ids.get(new_key) {
self.last_change.insert(id, seq);
}
}
WalRecord::Batch(inner) => {
for inner_rec in inner {
self.update_last_change_from_rec(inner_rec, seq);
}
}
}
}
pub fn node_count(&self) -> usize {
self.ids.len()
}
/// Configure archive retention: keep the `N` newest WAL archives at each
/// [`snapshot_with`] call when `archive_wal: true`.
///
/// `Some(N)` where N > 0 → prune oldest archives keeping the newest N.
/// `Some(0)` or `None` → unlimited (no pruning).
///
/// Pruning only ever happens inside [`snapshot_with`]; this method only
/// stores the policy. Archives below the retention limit are deleted
/// oldest-first. The horizon floor is updated so that
/// [`was_linked`] / history APIs return `CommitOutOfRange` for commits
/// in pruned archives rather than silently returning wrong data.
pub fn set_wal_archive_retention(&mut self, keep: Option<u32>) {
self.wal_archive_retention = keep;
}
/// Delete any WAL archives that are fully below the current horizon floor.
///
/// Orphaned archives arise when the floor is written first during retention
/// pruning and then a crash interrupts the archive-delete sequence. The
/// opening cleanup ensures no subsequent read path sees stale data.
///
/// Under the monotonic naming scheme, the archive name N equals the
/// cumulative end-frame index of the archive in global commit space (i.e.
/// the archive covers global frames `[prev_n, N)`). An archive is
/// fully orphaned when `N <= wal_horizon_floor`: all of its frames fall
/// below the floor and have already been counted in it.
fn cleanup_orphaned_archives(&mut self) -> Result<()> {
if self.wal_horizon_floor == 0 {
// Floor at 0 means no pruning has ever occurred; nothing to clean.
return Ok(());
}
let archive_ns = self.fs.list_archives()?;
for n in archive_ns {
if n <= self.wal_horizon_floor {
// Archive N ends at global frame N; all its frames are below
// the floor (floor already accounts for them) → orphaned.
self.fs.delete_archive(n).map_err(GraphError::Io)?;
} else {
// Archives are sorted ascending; first one above floor stops scan.
break;
}
}
Ok(())
}
/// Collect all WAL frames from surviving archives (oldest-first) then the
/// live WAL into one flat list, and return the total along with the number
/// of archive frames at the front of the list.
///
/// Commit indices into the returned list are LOCAL (0 = first frame of
/// oldest surviving archive). To obtain the GLOBAL index add
/// `self.wal_horizon_floor`.
fn all_frames(&self) -> Result<(Vec<WalRecord>, u64)> {
let archive_ns = self.fs.list_archives()?;
let mut all: Vec<WalRecord> = Vec::new();
for n in archive_ns {
let bytes = self.fs.read_archive(n)?;
let (frames, _) = decode_all(&bytes);
all.extend(frames);
}
let archive_count = all.len() as u64;
let live_bytes = self.fs.read(FileId::Wal)?;
let (live_frames, _) = decode_all(&live_bytes);
all.extend(live_frames);
Ok((all, archive_count))
}
/// Return the total number of committed WAL frames visible in the current
/// horizon window, including frames in surviving WAL archives.
///
/// This is the exclusive upper bound for valid `at_commit` indices in
/// `was_linked`. Valid indices are `wal_horizon_floor()..wal_total_commits()`.
///
/// Returns the horizon floor when all surviving history is empty.
pub fn wal_total_commits(&self) -> Result<u64> {
let (frames, _) = self.all_frames()?;
Ok(self.wal_horizon_floor + frames.len() as u64)
}
/// The global frame index of the first commit reachable through surviving
/// archives (0 when no archives have been pruned).
pub fn wal_horizon_floor(&self) -> u64 {
self.wal_horizon_floor
}
/// Return the per-node change history for `key` by scanning the on-disk WAL.
///
/// ## Horizon
///
/// History reaches back only to the last WAL-truncating snapshot, exactly like `open_at`.
/// Snapshots written with `keep_wal: true` preserve deeper history. This is the honest,
/// zero-cost contract; a durable history log is out of scope.
///
/// ## Derived edges
///
/// Rule-created (derived) edges are **not** in the WAL and therefore do not appear in
/// history. Only edges written directly by the application are recorded.
///
/// ## Deleted nodes
///
/// For nodes that have been deleted, dense-id records (SetPropId, InsertEdgeId) that
/// predate the deletion may not resolve (the id is tombstoned in the live map). The
/// string-keyed `DeleteNode` record still matches and produces a `NodeDeleted` entry.
/// Prop/edge history of a deleted node may therefore be partially unresolvable.
///
/// ## Dense-id edge entries and tombstoned partners
///
/// Edge entries from dense-id WAL records (`InsertEdgeId`) are omitted when the partner
/// endpoint's dense id is tombstoned. As a result, a live node's history can contain an
/// `EdgeRemoved` (string-keyed, always resolves) without a corresponding `EdgeAdded`.
/// Build commit-bounded alias intervals for `queried_key`.
///
/// Returns a list of `(key, valid_from_inclusive, valid_until_exclusive)` tuples.
/// A record written under `key` at commit `c` matches the queried identity iff
/// `c >= valid_from && (valid_until.is_none() || c < valid_until)`.
///
/// Each alias entry carries both a lower and an upper bound so that key-reuse
/// after a rename is handled correctly: if "a" is renamed to "b" at commit 5,
/// then a NEW node is created as "a" at commit 7 and renamed to "c" at commit 10,
/// querying "c" must NOT surface identity-1's events (commits 0–4 under "a");
/// only identity-2's events (commits 7–9 under "a") are in scope.
///
/// Only **forward aliasing**: querying the *new* key surfaces events written
/// under the *old* key. The reverse direction is not supported.
fn build_key_alias_intervals(
&self,
frames: &[core_storage::wal::WalRecord],
queried_key: &str,
) -> Vec<(String, u64, Option<u64>)> {
use core_storage::wal::WalRecord;
// Pre-pass: build reverse_rename and key_starts maps.
let mut reverse_rename: HashMap<String, (String, u64)> = HashMap::new();
let mut key_starts: HashMap<String, Vec<u64>> = HashMap::new();
for (local_i, frame) in frames.iter().enumerate() {
let commit = self.wal_horizon_floor + local_i as u64;
let records: &[WalRecord] = match frame {
WalRecord::Batch(inner) => inner.as_slice(),
single => std::slice::from_ref(single),
};
for rec in records {
match rec {
WalRecord::InsertNode { key, .. } | WalRecord::InsertNodeId { key, .. } => {
key_starts.entry(key.clone()).or_default().push(commit);
}
WalRecord::RenameNode { old_key, new_key } => {
// new_key came into existence at this commit.
key_starts.entry(new_key.clone()).or_default().push(commit);
// Record the reverse rename: new_key was introduced by renaming old_key.
reverse_rename.insert(new_key.clone(), (old_key.clone(), commit));
}
_ => {}
}
}
}
// Build alias intervals by following the reverse rename chain.
let mut result: Vec<(String, u64, Option<u64>)> = Vec::new();
let mut current_key = queried_key.to_string();
let mut current_valid_until: Option<u64> = None;
loop {
// valid_from: the most recent commit where current_key was assigned to this
// identity. For aliases (valid_until = Some(vu)), find the last start event
// for the key strictly before vu — this is where the alias's occupancy by
// this identity began, correctly excluding prior identities that reused the key.
let valid_from = if let Some(vu) = current_valid_until {
key_starts
.get(¤t_key)
.and_then(|starts| starts.iter().rev().find(|&&s| s < vu).copied())
.unwrap_or(self.wal_horizon_floor)
} else {
// Queried key — no upper bound; may have been introduced at any commit.
self.wal_horizon_floor
};
result.push((current_key.clone(), valid_from, current_valid_until));
match reverse_rename.get(¤t_key) {
Some((old_key, rename_commit)) => {
current_valid_until = Some(*rename_commit);
current_key = old_key.clone();
}
None => break,
}
}
result
}
/// Returns true if `record_key` matches any alias interval that covers `commit`.
fn aliases_match(
intervals: &[(String, u64, Option<u64>)],
record_key: &str,
commit: u64,
) -> bool {
intervals
.iter()
.any(|(k, vf, vu)| k == record_key && commit >= *vf && vu.is_none_or(|u| commit < u))
}
/// Return the change history of node `key` by scanning the on-disk WAL.
///
/// ## Horizon
///
/// History reaches back only as far as the retained WAL. The returned
/// [`HistoryResult`](crate::history::HistoryResult) carries `total_commits`
/// (the exclusive upper bound for valid commit indices) and `horizon` (the
/// oldest commit still reachable). When `horizon > 0`, older events were
/// pruned and are not in `items`.
pub fn node_history(
&self,
key: &str,
) -> Result<crate::history::HistoryResult<crate::history::HistoryEntry>> {
use crate::history::{HistoryChange, HistoryEntry, HistoryResult};
use core_storage::wal::WalRecord;
let (frames, _) = self.all_frames()?;
let total_commits = self.wal_horizon_floor + frames.len() as u64;
// Resolve commit-bounded alias intervals for `key` (handles renames in the WAL).
let alias_intervals = self.build_key_alias_intervals(&frames, key);
let mut out: Vec<HistoryEntry> = Vec::new();
for (local_i, frame) in frames.iter().enumerate() {
let commit = self.wal_horizon_floor + local_i as u64;
// Collect the inner records to process — Batch is one commit, single records are one commit.
let records: &[WalRecord] = match frame {
WalRecord::Batch(inner) => inner.as_slice(),
single => std::slice::from_ref(single),
};
for rec in records {
let change = match rec {
WalRecord::InsertNode { label, key: k, .. }
if Self::aliases_match(&alias_intervals, k, commit) =>
{
Some(HistoryChange::NodeInserted {
label: label.clone(),
})
}
WalRecord::InsertNodeId { label, key: k, .. }
if Self::aliases_match(&alias_intervals, k, commit) =>
{
let label_str = match self.syms.resolve(*label) {
Some(s) => s.to_string(),
None => continue,
};
Some(HistoryChange::NodeInserted { label: label_str })
}
WalRecord::SetProp {
key: k,
field,
value,
} if Self::aliases_match(&alias_intervals, k, commit) => {
Some(HistoryChange::PropSet {
field: field.clone(),
value: value.clone(),
})
}
WalRecord::SetPropId { id, field, value } => {
// Use key_of_historical (not key_of) so a node's prop_set
// events remain visible after the node is later deleted:
// key_of returns None for a tombstoned id, which would
// silently drop every PropSet between insert and delete.
// Mirrors the InsertEdgeId arm below and edge_history's
// own id-keyed arms.
match self.ids.key_of_historical(*id) {
// key_of_historical returns the last-known (possibly
// post-rename, possibly post-delete) key; compare to queried key.
Some(resolved) if resolved == key => {
let field_str = match self.syms.resolve(*field) {
Some(s) => s.to_string(),
None => continue,
};
Some(HistoryChange::PropSet {
field: field_str,
value: value.clone(),
})
}
_ => None,
}
}
WalRecord::RemoveProp { key: k, field }
if Self::aliases_match(&alias_intervals, k, commit) =>
{
Some(HistoryChange::PropRemoved {
field: field.clone(),
})
}
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
if Self::aliases_match(&alias_intervals, src_key, commit) {
Some(HistoryChange::EdgeAdded {
edge_type: edge_type.clone(),
other: dst_key.clone(),
outgoing: true,
})
} else if Self::aliases_match(&alias_intervals, dst_key, commit) {
Some(HistoryChange::EdgeAdded {
edge_type: edge_type.clone(),
other: src_key.clone(),
outgoing: false,
})
} else {
None
}
}
WalRecord::InsertEdgeId { etype, src, dst } => {
let etype_str = match self.syms.resolve(*etype) {
Some(s) => s.to_string(),
None => continue,
};
// key_of_historical (not key_of): an edge added before
// either endpoint was later deleted must still resolve —
// see the SetPropId arm above and edge_history's
// InsertEdgeId arm, which use the same lookup for the
// same reason.
let src_key = self.ids.key_of_historical(*src);
let dst_key = self.ids.key_of_historical(*dst);
if src_key == Some(key) {
let other = match dst_key {
Some(s) => s.to_string(),
None => continue,
};
Some(HistoryChange::EdgeAdded {
edge_type: etype_str,
other,
outgoing: true,
})
} else if dst_key == Some(key) {
let other = match src_key {
Some(s) => s.to_string(),
None => continue,
};
Some(HistoryChange::EdgeAdded {
edge_type: etype_str,
other,
outgoing: false,
})
} else {
None
}
}
WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
} => {
if Self::aliases_match(&alias_intervals, src_key, commit) {
Some(HistoryChange::EdgeRemoved {
edge_type: edge_type.clone(),
other: dst_key.clone(),
outgoing: true,
})
} else if Self::aliases_match(&alias_intervals, dst_key, commit) {
Some(HistoryChange::EdgeRemoved {
edge_type: edge_type.clone(),
other: src_key.clone(),
outgoing: false,
})
} else {
None
}
}
WalRecord::DeleteNode { key: k }
if Self::aliases_match(&alias_intervals, k, commit) =>
{
Some(HistoryChange::NodeDeleted)
}
// Skip: rule/view/fulltext/intern metadata; Batch wrapper handled above.
_ => None,
};
if let Some(change) = change {
out.push(HistoryEntry { commit, change });
}
}
}
Ok(HistoryResult {
items: out,
total_commits,
horizon: self.wal_horizon_floor,
})
}
/// Return the per-edge change history between nodes `a` and `b` by scanning
/// the on-disk WAL.
///
/// ## Horizon
///
/// History reaches back only to the last WAL-truncating snapshot, exactly
/// like `node_history` and `open_at`. The returned [`HistoryResult`] carries
/// `total_commits` (= number of WAL frames), which is the exclusive upper
/// bound for valid commit indices.
///
/// ## Derived edges
///
/// Rule-derived edges appear via `DerivedEdgeAdded` / `DerivedEdgeRetracted`
/// WAL markers written by `log_then_apply_with` after each rule-firing
/// mutation. The `rule` field of those events carries the rule name.
///
/// ## DeleteNode
///
/// When a node is deleted, its manual incident edges are swept inline without
/// individual `DeleteEdge` WAL records. `edge_history` detects `DeleteNode`
/// events for either endpoint and synthesises `Retracted(rule:None)` events
/// for each manual edge that was active at that point. Derived edges active at
/// the time of deletion are handled by the `DerivedEdgeRetracted` marker that
/// the engine appends immediately after the `DeleteNode` record; those events
/// carry correct rule attribution and are emitted by the marker arm, not the
/// synthetic sweep.
///
/// ## Masks
///
/// Like `node_history`, this method has no mask parameter and returns WAL
/// history regardless of any role mask. For masked history semantics, apply
/// the mask at the caller level.
pub fn edge_history(
&self,
a: &str,
b: &str,
) -> Result<crate::history::HistoryResult<crate::history::EdgeHistoryEvent>> {
use crate::history::{EdgeEvent, EdgeHistoryEvent, HistoryResult};
use core_storage::wal::WalRecord;
let (frames, _) = self.all_frames()?;
let total_commits = self.wal_horizon_floor + frames.len() as u64;
// Resolve all historical names for a and b (handles RenameNode in the WAL).
// Intervals are commit-bounded so recycled keys don't contaminate histories.
let alias_a = self.build_key_alias_intervals(&frames, a);
let alias_b = self.build_key_alias_intervals(&frames, b);
// Active edges between a and b tracked as (edge_type, src_key, dst_key, is_derived).
// The is_derived flag is used by the DeleteNode sweep: manual edges are
// swept with a synthetic Retracted(rule:None); derived edges are skipped
// because the engine writes a DerivedEdgeRetracted marker immediately after
// the DeleteNode record, which carries the correct rule attribution.
let mut active: Vec<(String, String, String, bool)> = Vec::new();
let mut out: Vec<EdgeHistoryEvent> = Vec::new();
for (local_i, frame) in frames.iter().enumerate() {
let commit = self.wal_horizon_floor + local_i as u64;
let records: &[WalRecord] = match frame {
WalRecord::Batch(inner) => inner.as_slice(),
single => std::slice::from_ref(single),
};
for rec in records {
match rec {
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
active.push((
edge_type.clone(),
src_key.clone(),
dst_key.clone(),
false,
));
out.push(EdgeHistoryEvent {
edge_type: edge_type.clone(),
commit,
event: EdgeEvent::Added,
rule: None,
});
}
}
WalRecord::InsertEdgeId { etype, src, dst } => {
let etype_str = match self.syms.resolve(*etype) {
Some(s) => s.to_string(),
None => continue,
};
// Use key_of_historical so tombstoned nodes (deleted
// later in the WAL) still resolve during the scan.
let src_key = self.ids.key_of_historical(*src);
let dst_key = self.ids.key_of_historical(*dst);
let is_ab = src_key == Some(a) && dst_key == Some(b);
let is_ba = src_key == Some(b) && dst_key == Some(a);
if is_ab || is_ba {
let src_str = src_key.unwrap().to_string();
let dst_str = dst_key.unwrap().to_string();
active.push((etype_str.clone(), src_str, dst_str, false));
out.push(EdgeHistoryEvent {
edge_type: etype_str,
commit,
event: EdgeEvent::Added,
rule: None,
});
}
}
WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
// Remove the first matching active entry (flag ignored).
if let Some(pos) = active.iter().position(|(et, s, d, _)| {
et == edge_type && s == src_key && d == dst_key
}) {
active.remove(pos);
}
out.push(EdgeHistoryEvent {
edge_type: edge_type.clone(),
commit,
event: EdgeEvent::Retracted,
rule: None,
});
}
}
WalRecord::DeleteNode { key: k }
if Self::aliases_match(&alias_a, k, commit)
|| Self::aliases_match(&alias_b, k, commit) =>
{
// Sweep: implicitly retract only MANUAL active edges.
// Derived active edges are skipped here because the rule
// engine appends a DerivedEdgeRetracted marker immediately
// after this DeleteNode record; that marker produces the
// single correctly-attributed Retracted event. Derived
// entries are dropped from `active` (the marker arm's
// idempotent retain finds nothing to remove).
for (et, _, _, is_derived) in active.drain(..) {
if !is_derived {
out.push(EdgeHistoryEvent {
edge_type: et,
commit,
event: EdgeEvent::Retracted,
rule: None,
});
}
// Derived: drop silently; marker carries the Retracted event.
}
}
WalRecord::DerivedEdgeAdded {
rule,
edge_type: et,
src_key,
dst_key,
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
active.push((et.clone(), src_key.clone(), dst_key.clone(), true));
out.push(EdgeHistoryEvent {
edge_type: et.clone(),
commit,
event: EdgeEvent::Added,
rule: Some(rule.clone()),
});
}
}
WalRecord::DerivedEdgeRetracted {
rule,
edge_type: et,
src_key,
dst_key,
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
// Push unconditionally: a derived edge whose Added marker
// predates the history horizon has no `active` entry, but
// the retraction is still a real in-window event.
// Remove from active idempotently if present.
active.retain(|(aet, s, d, _)| {
!(aet == et && s == src_key && d == dst_key)
});
out.push(EdgeHistoryEvent {
edge_type: et.clone(),
commit,
event: EdgeEvent::Retracted,
rule: Some(rule.clone()),
});
}
}
// All other records (InsertNode, SetProp, CreateRule, etc.)
// do not affect edges between a and b.
_ => {}
}
}
}
Ok(HistoryResult {
items: out,
total_commits,
horizon: self.wal_horizon_floor,
})
}
/// Return `true` iff an edge of `edge_type` existed between `a` and `b`
/// (in either direction) at the WAL commit `at_commit`.
///
/// ## Horizon
///
/// Valid commit indices are `0..total_commits` where `total_commits` is the
/// number of WAL frames. An `at_commit >= total_commits` is outside the
/// visible horizon and returns [`GraphError::CommitOutOfRange`].
///
/// ## Derived edges
///
/// Rule-derived edges are tracked via `DerivedEdgeAdded` / `DerivedEdgeRetracted`
/// WAL markers appended at firing time (Task 1). `was_linked` reads these markers
/// and therefore includes derived edges in its point-in-time evaluation,
/// matching `edge_history`'s fidelity.
pub fn was_linked(&self, a: &str, b: &str, edge_type: &str, at_commit: u64) -> Result<bool> {
use core_storage::wal::WalRecord;
let (frames, _) = self.all_frames()?;
let total_commits = self.wal_horizon_floor + frames.len() as u64;
// Horizon floor: commits in pruned archives are unreachable.
if at_commit < self.wal_horizon_floor {
return Err(GraphError::CommitOutOfRange {
commit: at_commit,
total: total_commits,
floor: self.wal_horizon_floor,
});
}
if at_commit >= total_commits {
return Err(GraphError::CommitOutOfRange {
commit: at_commit,
total: total_commits,
floor: self.wal_horizon_floor,
});
}
// Resolve all historical names for a and b (handles RenameNode in the WAL).
// Intervals are commit-bounded so recycled keys don't contaminate point-in-time reads.
let alias_a = self.build_key_alias_intervals(&frames, a);
let alias_b = self.build_key_alias_intervals(&frames, b);
// Local index into surviving frames (0 = first frame of oldest archive).
let local_commit = at_commit - self.wal_horizon_floor;
// Replay local frames 0..=local_commit, tracking active edges.
let mut active: BTreeSet<(String, String, String)> = BTreeSet::new();
for (local_i, frame) in frames.iter().enumerate().take((local_commit + 1) as usize) {
let commit = self.wal_horizon_floor + local_i as u64;
let records: &[WalRecord] = match frame {
WalRecord::Batch(inner) => inner.as_slice(),
single => std::slice::from_ref(single),
};
for rec in records {
match rec {
WalRecord::InsertEdge {
edge_type: et,
src_key,
dst_key,
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
active.insert((et.clone(), src_key.clone(), dst_key.clone()));
}
}
WalRecord::InsertEdgeId { etype, src, dst } => {
let etype_str = match self.syms.resolve(*etype) {
Some(s) => s.to_string(),
None => continue,
};
// Use key_of_historical so tombstoned nodes resolve.
let src_key = self.ids.key_of_historical(*src);
let dst_key = self.ids.key_of_historical(*dst);
let is_ab = src_key == Some(a) && dst_key == Some(b);
let is_ba = src_key == Some(b) && dst_key == Some(a);
if is_ab || is_ba {
active.insert((
etype_str,
src_key.unwrap().to_string(),
dst_key.unwrap().to_string(),
));
}
}
WalRecord::DeleteEdge {
edge_type: et,
src_key,
dst_key,
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
active.remove(&(et.clone(), src_key.clone(), dst_key.clone()));
}
}
WalRecord::DeleteNode { key: k }
if Self::aliases_match(&alias_a, k, commit)
|| Self::aliases_match(&alias_b, k, commit) =>
{
// All edges touching the deleted node are gone.
active.retain(|(_, s, d)| s != k && d != k);
}
WalRecord::DerivedEdgeAdded {
edge_type: et,
src_key,
dst_key,
..
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
active.insert((et.clone(), src_key.clone(), dst_key.clone()));
}
}
WalRecord::DerivedEdgeRetracted {
edge_type: et,
src_key,
dst_key,
..
} => {
let is_ab = Self::aliases_match(&alias_a, src_key, commit)
&& Self::aliases_match(&alias_b, dst_key, commit);
let is_ba = Self::aliases_match(&alias_b, src_key, commit)
&& Self::aliases_match(&alias_a, dst_key, commit);
if is_ab || is_ba {
active.remove(&(et.clone(), src_key.clone(), dst_key.clone()));
}
}
_ => {}
}
}
}
Ok(active.iter().any(|(et, _, _)| et == edge_type))
}
/// Every edge incident to `key` — either endpoint — that existed at WAL
/// commit `commit`, from ONE scan of the WAL.
///
/// This is the bulk form of [`was_linked`](GraphDb::was_linked): answering
/// "what did K's relationships look like at commit C" with one call instead
/// of one [`edge_history`](GraphDb::edge_history) per candidate partner.
/// The two agree edge for edge.
///
/// Results are sorted by `(edge_type, src_key, dst_key)`.
///
/// ## Horizon
///
/// Valid commit indices are `wal_horizon_floor()..wal_total_commits()`;
/// anything outside is [`GraphError::CommitOutOfRange`], exactly like
/// `was_linked`. An unknown key is not an error — it simply had no edges.
///
/// ## Derived edges
///
/// `DerivedEdgeAdded` / `DerivedEdgeRetracted` markers carry rule
/// attribution, so a rule-owned edge comes back with `derived: true` and
/// `rule: Some(name)`.
///
/// ## Renames
///
/// `key` is matched through the same commit-bounded alias intervals
/// `edge_history` uses, so querying a node's *current* key surfaces edges
/// written under an earlier name. Endpoint keys in the result are reported
/// under the name the node carries today, so they can be fed straight back
/// into `node_info`, `explain` or another `edges_at`.
///
/// ## Masks
///
/// Like `edge_history` and `node_history`, this reads the WAL regardless of
/// any role mask. Apply masking at the caller level.
pub fn edges_at(&self, key: &str, commit: u64) -> Result<Vec<EdgeAt>> {
use core_storage::wal::WalRecord;
let (frames, _) = self.all_frames()?;
let total_commits = self.wal_horizon_floor + frames.len() as u64;
// Horizon floor: commits in pruned archives are unreachable.
if commit < self.wal_horizon_floor || commit >= total_commits {
return Err(GraphError::CommitOutOfRange {
commit,
total: total_commits,
floor: self.wal_horizon_floor,
});
}
// Commit-bounded historical names of `key` (handles RenameNode).
let alias = self.build_key_alias_intervals(&frames, key);
// Forward rename chain, for reporting endpoints under their current
// names: old key → [(commit, new key)] in ascending commit order.
// Built over the whole WAL, not just the prefix up to `commit`, because
// a rename after `commit` still changes what the node is called today.
let mut renames: HashMap<String, Vec<(u64, String)>> = HashMap::new();
for (local_i, frame) in frames.iter().enumerate() {
let c = self.wal_horizon_floor + local_i as u64;
let records: &[WalRecord] = match frame {
WalRecord::Batch(inner) => inner.as_slice(),
single => std::slice::from_ref(single),
};
for rec in records {
if let WalRecord::RenameNode { old_key, new_key } = rec {
renames
.entry(old_key.clone())
.or_default()
.push((c, new_key.clone()));
}
}
}
// The name a node written as `k` at commit `from` carries today.
// Follows the first rename at or after `from`, then keeps going. The
// iteration cap bounds a rename cycle inside a single batch.
let canon = |k: &str, from: u64| -> String {
if renames.is_empty() {
return k.to_string();
}
let mut cur = k.to_string();
let mut at = from;
for _ in 0..64 {
match renames
.get(&cur)
.and_then(|v| v.iter().find(|(c, _)| *c >= at))
{
Some((c, new)) => {
at = *c;
cur = new.clone();
}
None => break,
}
}
cur
};
let local_commit = commit - self.wal_horizon_floor;
// (edge_type, src_key, dst_key) → (derived, rule)
let mut active: BTreeMap<(String, String, String), (bool, Option<String>)> =
BTreeMap::new();
for (local_i, frame) in frames.iter().enumerate().take((local_commit + 1) as usize) {
let c = self.wal_horizon_floor + local_i as u64;
let records: &[WalRecord] = match frame {
WalRecord::Batch(inner) => inner.as_slice(),
single => std::slice::from_ref(single),
};
for rec in records {
match rec {
WalRecord::InsertEdge {
edge_type,
src_key,
dst_key,
} => {
if Self::aliases_match(&alias, src_key, c)
|| Self::aliases_match(&alias, dst_key, c)
{
active.insert(
(edge_type.clone(), canon(src_key, c), canon(dst_key, c)),
(false, None),
);
}
}
WalRecord::InsertEdgeId { etype, src, dst } => {
let Some(etype_str) = self.syms.resolve(*etype) else {
continue;
};
// `key_of_historical` resolves tombstoned ids too, and
// already returns the node's current key — no rename
// canonicalisation needed on this arm.
let (Some(src_key), Some(dst_key)) = (
self.ids.key_of_historical(*src),
self.ids.key_of_historical(*dst),
) else {
continue;
};
if src_key == key || dst_key == key {
active.insert(
(
etype_str.to_string(),
src_key.to_string(),
dst_key.to_string(),
),
(false, None),
);
}
}
WalRecord::DeleteEdge {
edge_type,
src_key,
dst_key,
} => {
if Self::aliases_match(&alias, src_key, c)
|| Self::aliases_match(&alias, dst_key, c)
{
active.remove(&(
edge_type.clone(),
canon(src_key, c),
canon(dst_key, c),
));
}
}
WalRecord::DeleteNode { key: k } => {
if active.is_empty() {
continue;
}
if Self::aliases_match(&alias, k, c) {
// Our node is gone; every incident edge goes with it.
active.clear();
} else {
// A partner is gone; its edges to us go with it.
let ck = canon(k, c);
active.retain(|(_, s, d), _| *s != ck && *d != ck);
}
}
WalRecord::DerivedEdgeAdded {
rule,
edge_type,
src_key,
dst_key,
} => {
if Self::aliases_match(&alias, src_key, c)
|| Self::aliases_match(&alias, dst_key, c)
{
active.insert(
(edge_type.clone(), canon(src_key, c), canon(dst_key, c)),
(true, Some(rule.clone())),
);
}
}
WalRecord::DerivedEdgeRetracted {
edge_type,
src_key,
dst_key,
..
} => {
if Self::aliases_match(&alias, src_key, c)
|| Self::aliases_match(&alias, dst_key, c)
{
active.remove(&(
edge_type.clone(),
canon(src_key, c),
canon(dst_key, c),
));
}
}
// InsertNode, SetProp, CreateRule, … do not move edges.
_ => {}
}
}
}
// BTreeMap iteration is already (edge_type, src, dst) order.
Ok(active
.into_iter()
.map(|((edge_type, src_key, dst_key), (derived, rule))| EdgeAt {
edge_type,
src_key,
dst_key,
derived,
rule,
})
.collect())
}
/// The derived edges that would be retracted and derived if `key.field`
/// were set to `value` — computed WITHOUT writing anything.
///
/// Nothing is committed and nothing on `self` is mutated: the rule engine's
/// provenance, its candidate indexes, the topology and the property columns
/// are all cloned first, the change is applied to the clone, and the real
/// per-node re-derivation (`RuleEngine::on_node_changed` — the same call
/// `set_prop` makes during apply) runs against it. The derived-edge deltas
/// it emits are the answer, so rule semantics — predicates, top-k,
/// via-hops, chaining, weights — are the engine's, not a re-implementation.
///
/// Works on a read-only handle.
///
/// **While a rule's vector index is still building** (`RuleStats::building`)
/// the clone carries no pending-build state, so this reports the edges that
/// rule would derive — which the live store will not derive until its
/// backfill runs. Right about the end state, early about the timing.
///
/// Returns `Err(KeyNotFound)` for an unknown or tombstoned key and
/// `Err(ViewPropReadOnly)` for a field a view owns — matching
/// [`set_prop`](GraphDb::set_prop)'s validation. A change with no effect
/// (the node already holds `value`, or no rule watches `field`) returns
/// empty lists.
///
/// ## Cost
///
/// One clone of the property columns, the topology overlay, the symbol
/// interner, the edge properties and the provenance map, plus one candidate
/// re-index (O(nodes × rules)). That is much cheaper than copying the store
/// directory, but it is not free — this is an interactive "what if", not a
/// hot path.
pub fn what_if_set_prop(&self, key: &str, field: &str, value: Value) -> Result<WhatIf> {
// The engine's provenance, HNSW and IVF state live in the mmap'd base
// until something asks for them. On a store opened cold from a snapshot
// this is the first ask, and without it the clone below starts from an
// empty provenance map: nothing to retract, so `lost` comes back empty.
self.ensure_v8_base_sections_loaded();
let empty = WhatIf {
lost: Vec::new(),
gained: Vec::new(),
};
if let Some(view_name) = self.view_store.view_for_prop(field) {
return Err(GraphError::ViewPropReadOnly {
view_name: view_name.to_string(),
});
}
MutPreview::new(self).check_live_key(key)?;
let id = self
.ids
.get(key)
.ok_or_else(|| GraphError::KeyNotFound { key: key.into() })?;
let rules: Vec<RuleDef> = self.engine.rules().cloned().collect();
if rules.is_empty() {
return Ok(empty);
}
// No rule watches this field → no derivation can change.
if !rules.iter().any(|r| r.watched_fields().contains(field)) {
return Ok(empty);
}
let old_value = build_props_view(&self.props, &self.base)
.get(id, field)
.map(|vr| vr.into_value());
if old_value.as_ref() == Some(&value) {
return Ok(empty);
}
// --- Clone every piece of state the re-derivation writes to. ---
let mut props = self.props.clone();
let mut topo = self.topo.clone();
let mut syms = self.syms.clone();
let mut edge_props = self.edge_props.clone();
let mut tripped: BTreeMap<String, bool> = BTreeMap::new();
let mut fires: BTreeMap<String, u64> = BTreeMap::new();
for r in &rules {
tripped.insert(r.name.clone(), self.engine.is_tripped(&r.name));
fires.insert(r.name.clone(), self.engine.fire_count(&r.name));
}
// `provenance()` decodes retained snapshot bytes on first use; the
// engine clone needs the real map, not an empty one.
let provenance = self.engine.provenance().clone();
let mut engine = core_rules::RuleEngine::from_persist(rules, provenance, tripped, fires);
// Build the candidate indexes from the state BEFORE the change, exactly
// as apply() sees them: `on_node_changed` withdraws the node under its
// old value and refiles it under the new one, so the index must not
// already reflect the change.
engine.reindex_all_load_state(
&self.ids,
&syms,
&self.labels,
build_props_view(&self.props, &self.base),
self.engine.export_ivf_state(),
self.engine.export_hnsw_state_passthrough(),
);
engine.set_emit_deltas(true);
// --- Apply the hypothetical change and re-derive. ---
props.set(id, field, value);
{
let mut gm = make_graph_mut(
&self.ids,
&mut syms,
&self.labels,
build_props_view(&props, &self.base),
&mut topo,
&self.base,
&mut edge_props,
);
engine.on_node_changed(id, Some((field, old_value)), &mut gm);
}
let mut lost: BTreeSet<EdgeAt> = BTreeSet::new();
let mut gained: BTreeSet<EdgeAt> = BTreeSet::new();
for d in engine.drain_deltas() {
let edge = EdgeAt {
edge_type: d.edge_type,
src_key: d.src_key,
dst_key: d.dst_key,
derived: true,
rule: Some(d.rule),
};
if d.fired {
gained.insert(edge);
} else {
lost.insert(edge);
}
}
// An edge retracted and re-derived within the same re-derivation (top-k
// churn) is not a change the caller would see.
let churn: Vec<EdgeAt> = lost.intersection(&gained).cloned().collect();
for e in churn {
lost.remove(&e);
gained.remove(&e);
}
Ok(WhatIf {
lost: lost.into_iter().collect(),
gained: gained.into_iter().collect(),
})
}
pub fn edge_count(&self) -> u64 {
self.topo_view().edge_count()
}
/// Live/tombstone/edge counts plus per-rule provenance size, trip latch,
/// and fire counter (includes rebuild evaluations). Rules are sorted by name.
pub fn stats(&self) -> Stats {
self.ensure_v8_base_sections_loaded();
let building = self.engine.builds_in_progress();
let rules: Vec<RuleStats> = self
.engine
.rules()
.map(|r| RuleStats {
name: r.name.clone(),
edges: self
.engine
.provenance()
.get(&r.name)
.map(|s| s.len() as u64)
.unwrap_or(0),
tripped: self.engine.is_tripped(&r.name),
fires: self.engine.fire_count(&r.name),
approximate: r.approximate,
building: building.iter().find(|b| b.rule == r.name).cloned(),
})
.collect();
Stats {
nodes_live: self.ids.live_len(),
nodes_tombstoned: self.ids.len() - self.ids.live_len(),
edges: self.topo_view().edge_count(),
rules,
chain_truncations: self.engine.chain_truncations(),
history_floor: self.wal_horizon_floor,
namespaces: self.namespace_stats(),
}
}
/// On-disk size of the WAL file in bytes.
///
/// Reads file metadata without loading WAL contents. Returns `Err` for
/// in-memory (`SimFs`) databases where no WAL file exists on disk.
pub fn wal_size_bytes(&self) -> std::io::Result<u64> {
let path = self.fs.wal_path().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::Unsupported,
"wal_path not available for this Fs implementation",
)
})?;
Ok(std::fs::metadata(path)?.len())
}
/// Set the slow-query threshold. Queries whose execution time equals or
/// exceeds `ms` milliseconds are logged. Pass `0` to disable.
///
/// Use this setter in tests — the environment variable
/// `MUSHROOMDB_SLOW_QUERY_MS` is process-global and races parallel test
/// threads.
pub fn set_slow_query_threshold_ms(&mut self, ms: u64) {
self.slow_query_threshold_ms = ms;
}
/// Snapshot of the slow-query ring buffer and lifetime counter.
pub fn slow_query_snapshot(&self) -> SlowQuerySnapshot {
let log = self.slow_queries.lock().unwrap_or_else(|e| e.into_inner());
SlowQuerySnapshot {
threshold_ms: self.slow_query_threshold_ms,
count: log.total,
last: log.entries.iter().cloned().collect(),
}
}
/// Instant the database was opened. Used by consumers (e.g. `/metrics`)
/// to compute uptime.
pub fn started_at(&self) -> std::time::Instant {
self.started_at
}
/// On-disk snapshot format version this binary writes and reads.
pub fn format_version() -> u16 {
core_storage::snapshot::VERSION
}
/// Test-support: total bytes appended (SimFs only usage).
pub fn fs_total_appended(&self) -> usize
where
F: FsIntrospect,
{
self.fs.total_appended()
}
/// Test-support: successful `Fs::sync` calls (SimFs / counting fs).
pub fn fs_sync_count(&self) -> usize
where
F: FsIntrospect,
{
self.fs.sync_count()
}
/// Consume the db, returning its fs (for crash simulation).
pub fn into_fs(self) -> F {
self.fs
}
pub fn snapshot(&mut self) -> Result<()> {
self.snapshot_with(SnapshotOptions::default())
}
/// Snapshot with explicit options.
///
/// # `keep_wal`
///
/// When `keep_wal` is `false` (the default, same as [`snapshot`]):
/// - The WAL is replaced with a minimal baseline containing one
/// `EnableFulltext` record per active declaration. All pre-snapshot
/// history is discarded; `open_at` can only reach post-snapshot commits.
///
/// When `keep_wal` is `true`:
/// - The WAL is left intact. All pre-snapshot commits remain reachable
/// via `open_at`. The existing WAL already contains the original
/// `EnableFulltext` records, so no baseline re-write is needed; the
/// recovery guards in `apply()` silently skip any duplicate records on
/// replay.
/// - Crash window: a crash after the snapshot write but before the next
/// WAL write leaves the full pre-snapshot WAL intact. On reopen the
/// snapshot is loaded and the WAL replayed idempotently over it — safe
/// because every `apply()` arm is idempotent when replayed over an
/// already-current snapshot.
pub fn snapshot_with(&mut self, opts: SnapshotOptions) -> Result<()> {
if self.read_only {
return Err(GraphError::ReadOnly);
}
// A snapshot rewrites `wal.bin` through a tmp+rename, so a peer that is
// appending ends up holding a descriptor on an unlinked inode and loses
// commits it believes durable. Snapshotting therefore requires the
// cross-process write lock, exactly as appending does. Unlike the WAL
// append path this does not go through `log_then_apply_with`, so both
// guards are repeated here.
if self.degraded {
return Err(GraphError::Io(std::io::Error::other(
"database degraded after group-commit fsync failure; reopen required",
)));
}
if self.lock_denied {
return Err(GraphError::Busy { holder: None });
}
// Capture whether snapshot.bin already existed BEFORE this snapshot write.
// Used by the archive path's conservative genesis-chain check: if a prior
// snapshot exists but wal.truncated does not, we cannot distinguish a
// legacy store (may have been truncated in an older code version) from a
// new store that only used keep_wal=true. Conservative: refuse genesis in
// both cases. Must be sampled here, before the snapshot write below.
let had_prior_snapshot = self.fs.snapshot_path().map(|p| p.exists()).unwrap_or(false);
self.ensure_v8_base_sections_loaded();
// Ensure provenance is decoded before to_persist() clones it.
self.engine.ensure_provenance_loaded_mut();
let (rule_defs_typed, provenance, rule_tripped, rule_fires) = self.engine.to_persist();
let rule_defs = rule_defs_typed
.iter()
.map(|r| bincode::serialize(r).expect("RuleDef serialize cannot fail"))
.collect();
// Collect HNSW state and IVF state. When indexes are not yet
// populated (clean open, no mutation since open), pass the retained
// raw bytes through directly so that migrate/snapshot does not
// silently discard fitted approximate-rule indexes.
let hnsw_state = self.engine.export_hnsw_state_passthrough();
let ivf_bytes = if !self.engine.indexes_populated() {
// Pass retained IVF bytes through unchanged (no re-encode).
self.engine.retained_ivf_bytes_clone().unwrap_or_default()
} else {
// Indexes live: encode from current state.
let raw_ivf = self.engine.export_ivf_state();
let ivf_state_map: BTreeMap<String, core_storage::snapshot::PerRuleIvfState> = raw_ivf
.into_iter()
.map(|(name, ((sc, sa, sd), (dc, da, dd)))| {
(
name,
core_storage::snapshot::PerRuleIvfState {
src: core_storage::snapshot::SideIvfState {
centroids: sc,
clusters: sa,
drift: sd,
},
dst: core_storage::snapshot::SideIvfState {
centroids: dc,
clusters: da,
drift: dd,
},
},
)
})
.collect();
if ivf_state_map.is_empty() {
Vec::new()
} else {
bincode::serialize(&ivf_state_map).expect("IVF state serialize cannot fail")
}
};
let view_defs: Vec<Vec<u8>> = self
.view_store
.views()
.map(|v| bincode::serialize(v).expect("ViewDef serialize cannot fail"))
.collect();
if self.base.is_some() {
// V8 merge-snapshot path: encode base+overlay into a new V8 snapshot,
// write it atomically, remap it as the new base, then clear the overlay.
let meta = V8Meta {
labels: self.labels.clone(),
edge_props: self.edge_props.clone(),
rule_defs,
provenance,
rule_tripped,
rule_fires,
ivf_bytes,
view_defs,
wal_truncated: !opts.keep_wal,
hnsw: hnsw_state,
last_change: self.last_change.clone(),
};
let mut buf: Vec<u8> = Vec::new();
{
// Clone the Arc so the old base stays alive while we encode.
// The borrow of archived_csr (into old_base's mmap) is released
// at the end of this block, before we replace self.base.
let old_base = self.base.clone().expect("is_some checked above");
let archived_csr = old_base.topology().map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: topology section: {e:?}"),
})?;
let archived_cols = old_base.columns().map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: columns section: {e:?}"),
})?;
// `None` when the base predates V9 — the migration path: its
// string columns still carry their own tables and this snapshot
// is the rewrite that collapses them into section 12.
let archived_strings =
old_base
.string_table()
.transpose()
.map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: strings section: {e:?}"),
})?;
let archived_edge_props =
old_base
.edge_props_section()
.map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: edge_props section: {e:?}"),
})?;
let edge_props_raw =
old_base
.edge_props_raw_bytes()
.map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: edge_props raw bytes: {e:?}"),
})?;
let prov_raw =
old_base
.provenance_raw_bytes()
.map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: provenance raw bytes: {e:?}"),
})?;
encode_v8(
Some(archived_csr),
Some(archived_cols),
archived_strings,
Some((archived_edge_props, edge_props_raw)),
Some(prov_raw),
&self.topo,
&self.props,
&self.ids,
&self.syms,
&meta,
&mut buf,
)?;
}
self.fs.write_atomic(FileId::Snapshot, &buf)?;
// Remap the freshly-written snapshot as the new base.
// C2: use file mmap on RealFs; fall back to from_bytes on SimFs.
let new_base = if let Some(snap_path) = self.fs.snapshot_path() {
core_storage::v8::MappedBase::map(&snap_path)
} else {
core_storage::v8::MappedBase::from_bytes(buf)
}
.map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: remap new base: {e:?}"),
})?;
self.base = Some(Arc::new(new_base));
// Clear the overlay and prop tombstones — all data is now in the new base.
self.topo = Topology::new();
self.props = core_storage::columns::ColumnStore::new();
} else {
// Legacy path (V5–V7 stores without a V8 base).
//
// Memory-diet path: build V8Meta directly from &self — no SnapshotState
// clone and no encode_v8_from_state intermediate clones. The big
// structures (self.topo, self.props) are borrowed, not cloned.
// self.edge_props is moved (not cloned) because we immediately clear it
// when we remap the new V8 snapshot as self.base (see below).
//
// Eliminates from peak RSS vs. the old SnapshotState path:
// • self.topo.clone() (~topology HashMap footprint)
// • self.props.clone() (~column-store footprint)
// • encode_v8_from_state V8Meta secondary clones (labels, edge_props, …)
let meta = V8Meta {
labels: self.labels.clone(),
wal_truncated: !opts.keep_wal,
// Move edge_props out so the large overlay is freed when meta
// drops at end of this block (self.edge_props is now empty; reads
// after base assignment go through the mmap'd base section).
edge_props: std::mem::take(&mut self.edge_props),
rule_defs,
provenance,
rule_tripped,
rule_fires,
ivf_bytes,
view_defs,
hnsw: hnsw_state,
last_change: self.last_change.clone(),
};
let mut buf = Vec::new();
encode_v8(
None,
None,
None,
None,
None,
&self.topo,
&self.props,
&self.ids,
&self.syms,
&meta,
&mut buf,
)?;
// meta (and the moved edge_props inside it) is no longer needed;
// drop it before the write to keep the peak window narrow.
drop(meta);
self.fs.write_atomic(FileId::Snapshot, &buf)?;
// Remap the freshly-written V8 snapshot as self.base.
// On RealFs: drop the encode buffer before mmap to recover ~1.9 GiB.
// On SimFs (tests): pass buf to from_bytes.
let new_base = if let Some(snap_path) = self.fs.snapshot_path() {
drop(buf);
core_storage::v8::MappedBase::map(&snap_path)
} else {
core_storage::v8::MappedBase::from_bytes(buf)
}
.map_err(|e| GraphError::Corrupt {
detail: format!("v8 snapshot: remap new base (legacy path): {e:?}"),
})?;
self.base = Some(Arc::new(new_base));
// Free the large heap-allocated decoded state — all data is now in the
// mmap'd base. Mirrors the V8 merge-snapshot path (see above).
// self.edge_props was already moved into meta and is effectively empty.
self.topo = Topology::new();
self.props = core_storage::columns::ColumnStore::new();
}
if opts.archive_wal {
// History-preserving snapshot (Task 4):
// 1. Snapshot already written above (write_atomic → fsynced).
// 2. Rename WAL → wal.<commit_seq>.archive (atomic, same fs).
// Crash window B: crash here leaves archive present, WAL
// absent. Reopen: snapshot loaded (full state), no WAL
// replay. Archive is NOT replayed into live state — it is
// pre-snapshot by construction. Safe.
// 3. Optionally write genesis marker (first archive only, no
// prior WAL truncation).
// 4. Prune old archives (retention), update horizon floor.
// Pruning invalidates the genesis chain; delete marker.
// 5. Write new minimal baseline WAL (write_atomic).
// Crash window C: crash here leaves new archive plus no live
// WAL. Same as window B — handled above.
//
// Sample existing archives BEFORE the rename so we can detect
// whether this is the first archive.
let existing_archives = self.fs.list_archives()?;
let is_first_archive = existing_archives.is_empty();
// Compute a globally-monotonic archive name: the name equals the
// cumulative end-frame index of the archive in global commit space.
//
// Using `commit_seq` directly is UNSOUND across sessions: on reopen
// commit_seq is seeded from max(last_change), which underestimates
// the WAL depth when trailing commits (e.g. insert_edge) do not
// update last_change. A session-2 archive could then receive a name
// ≤ the session-1 archive, causing incorrect sort order or collision.
//
// Instead: read and decode the live WAL here (before the rename) to
// get its exact frame count, then add it to the last known global
// end-frame index (the name of the most recent existing archive, or
// wal_horizon_floor if no archives exist). This is O(WAL size) but
// snapshot is already serialising the full graph state, so the cost
// is dominated.
let live_wal_bytes_for_name = self.fs.read(FileId::Wal)?;
let (live_frames_for_name, _) = decode_all(&live_wal_bytes_for_name);
let archive_n = existing_archives
.last()
.copied()
.unwrap_or(self.wal_horizon_floor)
+ live_frames_for_name.len() as u64;
self.fs.archive_wal(archive_n)?;
// Genesis marker: written once when the first archive is taken
// from a store that has never undergone a WAL-truncating snapshot.
// When present, `open_at` may replay archive-resident commits from
// empty state (the archive chain covers from global index 0).
//
// Two conditions must ALL hold:
// 1. This is the first archive (existing_archives was empty).
// 2. No snapshot.bin existed before this operation (had_prior_snapshot=false).
// A WAL-truncating snapshot (keep_wal=false) always writes snapshot.bin
// before truncating the WAL, so if any prior truncating snapshot was taken
// — even in a previous session — snapshot.bin is present and this condition
// is false. This subsumes the cross-session truncation case without
// requiring a separate wal.truncated sidecar file.
// For legacy stores (snapshot.bin written by an older code version that
// may have truncated the WAL), the same conservative refusal applies:
// we cannot prove the chain is complete, so we refuse genesis (cost =
// no as-of-through-archives; never silent wrong data).
// On SimFs (snapshot_path() == None) had_prior_snapshot is always false,
// so SimFs always passes this check.
if is_first_archive && !had_prior_snapshot {
self.fs.write_genesis_marker()?;
self.archive_genesis_chain = true;
}
// Retention pruning: keep newest `keep` archives; delete oldest.
// Pruning is the ONLY deletion site for archives.
//
// Crash-safety ordering (C1 fix):
// 1. Count frames in surplus archives (reads only — no mutation).
// 2. Advance and PERSIST the horizon floor FIRST via write-then-
// rename (atomic). A crash after this point leaves orphaned
// archives on disk, but the floor is correct. The opening
// cleanup sweep (`cleanup_orphaned_archives`) removes them on
// the next open, so the store is always safe to reopen.
// 3. Delete the genesis marker (floor > 0 already blocks open_at
// via the conjunctive gate; marker cleanup is belt-and-suspenders).
// 4. Delete surplus archives. A crash between any two deletes
// leaves the floor committed and orphaned archives cleaned at
// next open — never a stale floor with a missing archive prefix.
if let Some(keep) = self.wal_archive_retention {
if keep > 0 {
let archives = self.fs.list_archives()?;
// archives is sorted ascending (oldest first)
if archives.len() as u32 > keep {
let surplus = archives.len() - keep as usize;
// Step 1: count pruned frames (reads, no mutation).
let mut pruned_frames = 0u64;
for &n in &archives[..surplus] {
let bytes = self.fs.read_archive(n)?;
let (frames, _) = decode_all(&bytes);
pruned_frames += frames.len() as u64;
}
// Step 2: advance and persist floor FIRST.
self.wal_horizon_floor += pruned_frames;
self.fs.write_horizon_floor(self.wal_horizon_floor)?;
// Step 3: delete genesis marker (floor > 0 already
// blocks open_at; this is belt-and-suspenders cleanup).
if pruned_frames > 0 && self.archive_genesis_chain {
self.fs.delete_genesis_marker()?;
self.archive_genesis_chain = false;
}
// Step 4: delete surplus archives. Crash here →
// orphaned archives; cleaned at next open.
for &n in &archives[..surplus] {
self.fs.delete_archive(n)?;
}
}
}
}
// Write new minimal baseline WAL (mirrors the keep_wal=false path).
let mut baseline_wal: Vec<u8> = Vec::new();
for (label, field) in self.fulltext.enabled_pairs() {
let rec = WalRecord::EnableFulltext {
label: label.clone(),
field: field.clone(),
};
baseline_wal.extend_from_slice(&encode_record(&rec));
}
for (label, field) in self.prop_index.enabled_pairs() {
let rec = WalRecord::EnableIndex {
label: label.clone(),
field: field.clone(),
};
baseline_wal.extend_from_slice(&encode_record(&rec));
}
self.fs.write_atomic(FileId::Wal, &baseline_wal)?;
} else if opts.keep_wal {
// keep_wal=true: WAL is left untouched. The existing WAL already
// contains the EnableFulltext records from the original enable calls;
// replay is idempotent (guards in apply() skip already-live entries).
// No baseline re-write is needed or safe here — the full WAL history
// must remain intact for open_at to reach pre-snapshot commits.
} else {
// keep_wal=false (default): truncate by replacing the WAL with a
// minimal baseline of one EnableFulltext record per active pair.
//
// Crash-ordering: write_atomic is atomic.
// • Crash before snapshot write → WAL unchanged. Safe.
// • Crash after snapshot write but before this WAL write → full
// pre-snapshot WAL still present; open_with replays idempotently.
// • Crash after both writes → normal post-snapshot state.
//
// Genesis chain: a WAL-truncating snapshot breaks the archive chain
// for any archives taken AFTER this point (their WAL slices would
// not start at genesis). Delete any existing genesis marker so that
// open_at refuses archive-resident commits. Future sessions are
// covered by had_prior_snapshot: snapshot.bin written here persists
// across sessions and prevents a later archiving session from
// incorrectly claiming a complete genesis chain.
if self.archive_genesis_chain {
self.fs.delete_genesis_marker()?;
self.archive_genesis_chain = false;
}
let mut baseline_wal: Vec<u8> = Vec::new();
for (label, field) in self.fulltext.enabled_pairs() {
let rec = WalRecord::EnableFulltext {
label: label.clone(),
field: field.clone(),
};
baseline_wal.extend_from_slice(&encode_record(&rec));
}
for (label, field) in self.prop_index.enabled_pairs() {
let rec = WalRecord::EnableIndex {
label: label.clone(),
field: field.clone(),
};
baseline_wal.extend_from_slice(&encode_record(&rec));
}
self.fs.write_atomic(FileId::Wal, &baseline_wal)?;
}
// After snapshot the overlay may have changed (V8 merge path clears
// self.topo and self.props). Refresh the MVCC fold so future readers
// see the post-snapshot state rather than stale overlay data.
self.fold_now();
// We wrote the snapshot and (unless keep_wal) replaced the WAL, so both
// markers this handle uses to detect other processes' work must be
// re-taken from disk. Skipping this would make our own snapshot look
// like a peer's on the next staleness check and force a needless
// reload.
self.wal_consumed = self.fs.wal_len().map_err(GraphError::Io)?;
self.snapshot_ident = self.fs.snapshot_ident().map_err(GraphError::Io)?;
Ok(())
}
}
/// Queued mutation for a [`BatchBuilder`] or [`GraphDb::commit_group`].
///
/// The `submit_batch` / `commit_group` APIs accept `Vec<BatchOp>` so that
/// callers can build a set of mutations without holding `&mut GraphDb` and
/// hand them off to the group-committing writer for durable, batched I/O.
pub enum BatchOp {
InsertNode {
label: String,
key: String,
props: Vec<(String, Value)>,
},
InsertEdge {
edge_type: String,
src_key: String,
dst_key: String,
},
SetProp {
key: String,
field: String,
value: Value,
},
RemoveProp {
key: String,
field: String,
},
DeleteEdge {
edge_type: String,
src_key: String,
dst_key: String,
},
DeleteNode {
key: String,
},
CreateRule(RuleDef),
DeleteRule {
name: String,
},
/// Rename a node's key. Validated: old must exist, new must not.
RenameNode {
old_key: String,
new_key: String,
},
/// Insert an edge, auto-creating any missing endpoint as a plain node with
/// `placeholder_label` and no props. Rules fire and last-change is updated
/// for each created endpoint (normal InsertNode semantics in the batch frame).
InsertEdgeUpsert {
edge_type: String,
src_key: String,
dst_key: String,
placeholder_label: String,
},
}
/// Three-way node visibility status used by `check_single_op_authz`.
enum NodeAuthzStatus {
/// Node exists in the store and is in the role's read mask.
Visible(String), // carries the node's label
/// Node exists in the store but is NOT in the role's read mask.
Hidden,
/// Node does not exist in the store.
Absent,
}
/// Overlay of ops already accepted earlier in the same batch. Never written
/// back to the database — validation only.
#[derive(Default)]
struct Overlay {
extra_keys: BTreeSet<String>,
deleted_keys: BTreeSet<String>,
extra_props: BTreeMap<(String, String), Value>,
removed_props: BTreeSet<(String, String)>,
extra_edges: BTreeSet<(String, String, String)>,
deleted_edges: BTreeSet<(String, String, String)>,
extra_rules: BTreeSet<String>,
deleted_rules: BTreeSet<String>,
/// `rule name → (via_edge, edge_type)` for every via-hop rule accepted
/// earlier in this batch. Feeds the rule-chain cycle check, which otherwise
/// sees only the rules already committed to the engine. Keyed by name so a
/// later `DeleteRule` in the same batch drops the arc with the rule.
extra_rule_arcs: BTreeMap<String, (String, String)>,
}
/// Read-only view of live db state plus a batch overlay. Shared by single-op
/// public methods (empty overlay) and `commit_batch`.
struct MutPreview<'a, F: Fs> {
db: &'a GraphDb<F>,
overlay: Overlay,
}
/// Shortest path from `start` to `target` following `arcs` (`from → to`), or
/// `None` if `target` is unreachable.
///
/// Used for rule-chain cycle detection, where an arc is "a rule hops over
/// `from` and writes `to`". Breadth-first over BTree-ordered adjacency, so the
/// reported path is stable for a given rule set, and iterative so a pathological
/// rule graph cannot overflow the stack.
fn find_cycle_through(arcs: &[(String, String)], start: &str, target: &str) -> Option<Vec<String>> {
let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
for (from, to) in arcs {
adj.entry(from.as_str()).or_default().insert(to.as_str());
}
let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
let mut visited: BTreeSet<&str> = BTreeSet::new();
let mut queue: std::collections::VecDeque<&str> = std::collections::VecDeque::new();
visited.insert(start);
queue.push_back(start);
while let Some(node) = queue.pop_front() {
if node == target {
let mut path = vec![node.to_string()];
let mut cur = node;
while let Some(&p) = parent.get(cur) {
path.push(p.to_string());
cur = p;
}
path.reverse();
return Some(path);
}
for &next in adj.get(node).into_iter().flatten() {
if visited.insert(next) {
parent.insert(next, node);
queue.push_back(next);
}
}
}
None
}
impl<'a, F: Fs> MutPreview<'a, F> {
fn new(db: &'a GraphDb<F>) -> Self {
Self {
db,
overlay: Overlay::default(),
}
}
fn has_key(&self, key: &str) -> bool {
if self.overlay.extra_keys.contains(key) {
return true;
}
if self.overlay.deleted_keys.contains(key) {
return false;
}
self.db.ids.get(key).is_some()
}
fn has_prop(&self, key: &str, field: &str) -> bool {
if !self.has_key(key) {
return false;
}
let k = (key.to_string(), field.to_string());
if self.overlay.removed_props.contains(&k) {
return false;
}
if self.overlay.extra_props.contains_key(&k) {
return true;
}
// Fresh identity (first insert in this batch, or delete+reinsert):
// ignore props still sitting on the soon-to-be-tombstoned slot.
if self.overlay.extra_keys.contains(key) {
return false;
}
self.db.get_prop(key, field).is_some()
}
fn has_edge(&self, edge_type: &str, src_key: &str, dst_key: &str) -> bool {
let k = (
edge_type.to_string(),
src_key.to_string(),
dst_key.to_string(),
);
if self.overlay.deleted_edges.contains(&k) {
return false;
}
if self.overlay.extra_edges.contains(&k) {
return true;
}
// A key created in this batch (including reinsert) has no db edges.
if self.overlay.extra_keys.contains(src_key) || self.overlay.extra_keys.contains(dst_key) {
return false;
}
if self.overlay.deleted_keys.contains(src_key)
|| self.overlay.deleted_keys.contains(dst_key)
{
return false;
}
let Some(src) = self.db.ids.get(src_key) else {
return false;
};
let Some(dst) = self.db.ids.get(dst_key) else {
return false;
};
let Some(sym) = self.db.syms.get(edge_type) else {
return false;
};
self.db
.topo_view()
.neighbors(sym, Direction::Out, src)
.binary_search(&dst)
.is_ok()
}
fn has_rule(&self, name: &str) -> bool {
if self.overlay.extra_rules.contains(name) {
return true;
}
if self.overlay.deleted_rules.contains(name) {
return false;
}
self.db.engine.rules().any(|r| r.name == name)
}
fn is_rule_owned(&self, edge_type: &str, src_key: &str, dst_key: &str) -> bool {
if self.overlay.extra_keys.contains(src_key) || self.overlay.extra_keys.contains(dst_key) {
return false;
}
if self.overlay.deleted_keys.contains(src_key)
|| self.overlay.deleted_keys.contains(dst_key)
{
return false;
}
let Some(src) = self.db.ids.get(src_key) else {
return false;
};
let Some(dst) = self.db.ids.get(dst_key) else {
return false;
};
let Some(et) = self.db.syms.get(edge_type) else {
return false;
};
// extra_rules is deliberately not consulted: a CreateRule earlier in
// this batch has not fired, so it contributes no provenance. That is
// the documented rule-window gap (see GraphDb::batch).
if self.overlay.deleted_rules.is_empty() {
return self.db.engine.is_owned(et, src, dst);
}
for (rule, triples) in self.db.engine.provenance() {
if self.overlay.deleted_rules.contains(rule) {
continue;
}
if triples.contains(&(et, src, dst)) {
return true;
}
}
false
}
fn check_insert_node(&self, key: &str) -> Result<()> {
if self.has_key(key) {
Err(GraphError::DuplicateKey { key: key.into() })
} else {
Ok(())
}
}
fn check_live_key(&self, key: &str) -> Result<()> {
if self.has_key(key) {
Ok(())
} else {
Err(GraphError::KeyNotFound { key: key.into() })
}
}
fn prepare_insert_edge(&self, edge_type: &str, src_key: &str, dst_key: &str) -> Result<bool> {
for k in [src_key, dst_key] {
if !self.has_key(k) {
return Err(GraphError::KeyNotFound { key: k.into() });
}
}
if self.is_rule_owned(edge_type, src_key, dst_key) {
return Err(GraphError::RuleOwned {
detail: format!("edge {edge_type} {src_key}→{dst_key} is rule-owned"),
});
}
// A user-written edge stays inside one namespace. Derived edges do not
// come through here — the engine adds them directly — and the rule
// scoping check is what keeps those pure.
let src_ns = self.namespace_in_batch(src_key);
let dst_ns = self.namespace_in_batch(dst_key);
if src_ns != dst_ns {
return Err(GraphError::CrossNamespace {
src: src_key.to_string(),
src_ns,
dst: dst_key.to_string(),
dst_ns,
});
}
Ok(!self.has_edge(edge_type, src_key, dst_key))
}
fn prepare_remove_prop(&self, key: &str, field: &str) -> Result<bool> {
self.check_live_key(key)?;
// Removing `ns` is changing the namespace — to `default`, the namespace
// an absent property names. It goes through this one choke-point and NOT
// through `rewrite_wal_dense` (a `RemoveProp` needs no dense rewrite), so
// the immutability rule has to be stated here as well. Without it the
// node silently lands in `default` on the next open: the cross-namespace
// edge guard is defeated and a default-bound role reads a tenant's node.
if field == NS_PROP {
let from = self.namespace_in_batch(key);
if from != NS_DEFAULT {
return Err(GraphError::NamespaceImmutable {
key: key.to_string(),
from,
to: NS_DEFAULT.to_string(),
});
}
// Already in `default`: the removal changes no namespace. It is the
// no-op `set_prop` to the current namespace is, not an error.
return Ok(false);
}
Ok(self.has_prop(key, field))
}
fn prepare_delete_edge(&self, edge_type: &str, src_key: &str, dst_key: &str) -> Result<bool> {
for k in [src_key, dst_key] {
if !self.has_key(k) {
return Err(GraphError::KeyNotFound { key: k.into() });
}
}
// Provenance-owned OR a live rule would derive this pair. User-first
// edges that a later rule matches are not in `owned`, but deleting
// them would leave a hole `rebuild_rule` immediately fills.
if self.is_rule_owned(edge_type, src_key, dst_key) {
return Err(GraphError::RuleOwned {
detail: format!(
"edge {edge_type} {src_key}→{dst_key} is rule-owned; \
delete or change the owning rule"
),
});
}
if self.would_derive(edge_type, src_key, dst_key) {
return Err(GraphError::RuleOwned {
detail: format!(
"edge {edge_type} {src_key}→{dst_key} is rule-owned; \
delete or change the owning rule, or a live rule would re-derive it"
),
});
}
Ok(self.has_edge(edge_type, src_key, dst_key))
}
/// True if any live rule (minus overlay-deleted names) would derive
/// `(edge_type, src, dst)` from current overlay-visible props/labels.
/// CreateRule names in `extra_rules` are ignored — same documented
/// same-batch rule-window as [`Self::is_rule_owned`].
fn would_derive(&self, edge_type: &str, src_key: &str, dst_key: &str) -> bool {
if src_key == dst_key {
return false;
}
let Some(src_label) = self.label_of(src_key) else {
return false;
};
let Some(dst_label) = self.label_of(dst_key) else {
return false;
};
for rule in self.db.engine.rules() {
if self.overlay.deleted_rules.contains(&rule.name) {
continue;
}
if rule.edge_type != edge_type {
continue;
}
if rule.src_label != src_label || rule.dst_label != dst_label {
continue;
}
let src_props = |f: &str| self.prop_value(src_key, f);
let dst_props = |f: &str| self.prop_value(dst_key, f);
let src_view = NodeView {
key: src_key,
props: &src_props,
};
let dst_view = NodeView {
key: dst_key,
props: &dst_props,
};
if evaluate(&rule.predicate, &src_view, &dst_view).is_some() {
return true;
}
}
false
}
fn label_of(&self, key: &str) -> Option<String> {
if self.overlay.deleted_keys.contains(key) {
return None;
}
// Fresh identities created in this batch have no stored label in the
// overlay; they cannot be provenance-owned yet either.
let id = self.db.ids.get(key)?;
let sym = self.db.labels.get(id as usize).copied()?;
if sym == u32::MAX {
return None;
}
self.db.syms.resolve(sym).map(str::to_string)
}
/// The namespace `key` is in as this batch sees it — including a node
/// inserted earlier in the same batch, which the store does not have yet.
fn namespace_in_batch(&self, key: &str) -> String {
namespace_of_value(self.prop_value(key, NS_PROP).as_ref()).to_string()
}
fn prop_value(&self, key: &str, field: &str) -> Option<Value> {
if !self.has_key(key) {
return None;
}
let k = (key.to_string(), field.to_string());
if self.overlay.removed_props.contains(&k) {
return None;
}
if let Some(v) = self.overlay.extra_props.get(&k) {
return Some(v.clone());
}
if self.overlay.extra_keys.contains(key) {
return None;
}
self.db.get_prop(key, field)
}
fn check_create_rule(&self, def: &RuleDef) -> Result<()> {
def.validate()
.map_err(|e| GraphError::RuleInvalid { detail: e })?;
if self.has_rule(&def.name) {
return Err(GraphError::RuleInvalid {
detail: format!("rule {:?} already exists", def.name),
});
}
// Rule-chain cycle rejection. Derived edges feed via-hop rules, so a
// rule set forms a graph whose arcs are "hops over `via_edge`, writes
// `edge_type`". A cycle in that graph is a rule set that would re-fire
// itself forever; the engine's depth cap would silently truncate it
// instead, leaving an arbitrary partial result. Reject it here, the one
// place that sees the whole rule set.
//
// Rules accepted earlier in the same batch count too: the overlay
// carries their arcs, so a cycle cannot be assembled one op at a time.
if let Some(via) = def.via_edge.as_deref() {
if via == def.edge_type {
return Err(GraphError::RuleInvalid {
detail: format!("rule chain cycle: {} -> {}", via, def.edge_type),
});
}
let mut arcs: Vec<(String, String)> = self
.db
.engine
.rules()
.filter(|r| !self.overlay.deleted_rules.contains(&r.name))
.filter_map(|r| r.via_edge.clone().map(|v| (v, r.edge_type.clone())))
.collect();
arcs.extend(self.overlay.extra_rule_arcs.values().cloned());
arcs.push((via.to_string(), def.edge_type.clone()));
if let Some(path) = find_cycle_through(&arcs, &def.edge_type, via) {
return Err(GraphError::RuleInvalid {
detail: format!("rule chain cycle: {} -> {}", via, path.join(" -> ")),
});
}
}
Ok(())
}
fn check_delete_rule(&self, name: &str) -> Result<()> {
if self.has_rule(name) {
Ok(())
} else {
Err(GraphError::RuleNotFound { name: name.into() })
}
}
fn note_insert_node(&mut self, key: &str, props: &[(String, Value)]) {
self.overlay.deleted_keys.remove(key);
self.overlay.extra_keys.insert(key.to_string());
self.overlay.extra_props.retain(|(k, _), _| k != key);
self.overlay.removed_props.retain(|(k, _)| k != key);
for (field, value) in props {
self.overlay
.extra_props
.insert((key.to_string(), field.clone()), value.clone());
}
}
fn note_insert_edge(&mut self, edge_type: &str, src_key: &str, dst_key: &str) {
let k = (
edge_type.to_string(),
src_key.to_string(),
dst_key.to_string(),
);
self.overlay.deleted_edges.remove(&k);
self.overlay.extra_edges.insert(k);
}
fn note_set_prop(&mut self, key: &str, field: &str, value: &Value) {
let k = (key.to_string(), field.to_string());
self.overlay.removed_props.remove(&k);
self.overlay.extra_props.insert(k, value.clone());
}
fn note_remove_prop(&mut self, key: &str, field: &str) {
let k = (key.to_string(), field.to_string());
self.overlay.extra_props.remove(&k);
self.overlay.removed_props.insert(k);
}
fn note_delete_edge(&mut self, edge_type: &str, src_key: &str, dst_key: &str) {
let k = (
edge_type.to_string(),
src_key.to_string(),
dst_key.to_string(),
);
self.overlay.extra_edges.remove(&k);
self.overlay.deleted_edges.insert(k);
}
fn note_delete_node(&mut self, key: &str) {
self.overlay.extra_keys.remove(key);
self.overlay.deleted_keys.insert(key.to_string());
self.overlay.extra_props.retain(|(k, _), _| k != key);
self.overlay.removed_props.retain(|(k, _)| k != key);
self.overlay
.extra_edges
.retain(|(_, s, d)| s != key && d != key);
self.overlay
.deleted_edges
.retain(|(_, s, d)| s != key && d != key);
}
fn note_create_rule(&mut self, def: &RuleDef) {
self.overlay.deleted_rules.remove(&def.name);
self.overlay.extra_rules.insert(def.name.clone());
// Rules accepted earlier in this batch are not in the engine yet, so
// the cycle check would not see their arcs. Keep the arc, not just the
// name, so a batch cannot smuggle in a cycle one op at a time.
if let Some(via) = def.via_edge.clone() {
self.overlay
.extra_rule_arcs
.insert(def.name.clone(), (via, def.edge_type.clone()));
}
}
fn check_rename_node(&self, old: &str, new: &str) -> Result<()> {
if !self.has_key(old) {
return Err(GraphError::KeyNotFound { key: old.into() });
}
if self.has_key(new) {
return Err(GraphError::DuplicateKey { key: new.into() });
}
Ok(())
}
fn note_rename_node(&mut self, old: &str, new: &str) {
// Mark old as deleted so subsequent batch ops cannot reference it.
self.overlay.extra_keys.remove(old);
self.overlay.deleted_keys.insert(old.to_string());
// Mark new as extra so subsequent batch ops can reference it.
self.overlay.deleted_keys.remove(new);
self.overlay.extra_keys.insert(new.to_string());
// Migrate any overlay props from old key to new key.
let new_str = new.to_string();
let transferred: Vec<((String, String), Value)> = self
.overlay
.extra_props
.iter()
.filter(|((k, _), _)| k.as_str() == old)
.map(|((_, f), v)| ((new_str.clone(), f.clone()), v.clone()))
.collect();
self.overlay
.extra_props
.retain(|(k, _), _| k.as_str() != old);
for (k, v) in transferred {
self.overlay.extra_props.insert(k, v);
}
// Migrate removed_props.
let transferred_removed: Vec<(String, String)> = self
.overlay
.removed_props
.iter()
.filter(|(k, _)| k.as_str() == old)
.map(|(_, f)| (new_str.clone(), f.clone()))
.collect();
self.overlay
.removed_props
.retain(|(k, _)| k.as_str() != old);
for k in transferred_removed {
self.overlay.removed_props.insert(k);
}
}
fn note_delete_rule(&mut self, name: &str) {
self.overlay.extra_rules.remove(name);
// Drop its chain arc too: a rule created and then deleted in the same
// batch must not make a later, legal rule look like a cycle.
self.overlay.extra_rule_arcs.remove(name);
self.overlay.deleted_rules.insert(name.to_string());
// Treat the deleted rule's current provenance as gone so a later
// delete_edge of those triples is a no-op (matches sequential).
if let Some(triples) = self.db.engine.provenance().get(name) {
for &(et, s, d) in triples {
let Some(etype) = self.db.syms.resolve(et) else {
continue;
};
let Some(src) = self.db.ids.key_of(s) else {
continue;
};
let Some(dst) = self.db.ids.key_of(d) else {
continue;
};
let k = (etype.to_string(), src.to_string(), dst.to_string());
self.overlay.extra_edges.remove(&k);
self.overlay.deleted_edges.insert(k);
}
}
}
}
/// Collects mutations and commits them as one WAL `Batch` frame.
///
/// Holds `&mut GraphDb` for its lifetime. Queue with the same method names
/// as [`GraphDb`]; call [`commit`](Self::commit) to validate, log, and apply.
/// See [`GraphDb::batch`] for validation and atomicity rules.
pub struct BatchBuilder<'a, F: Fs> {
db: &'a mut GraphDb<F>,
ops: Vec<BatchOp>,
}
impl<'a, F: Fs> BatchBuilder<'a, F> {
pub fn insert_node(
&mut self,
label: &str,
key: &str,
props: Vec<(String, Value)>,
) -> &mut Self {
self.ops.push(BatchOp::InsertNode {
label: label.into(),
key: key.into(),
props,
});
self
}
pub fn insert_edge(&mut self, edge_type: &str, src_key: &str, dst_key: &str) -> &mut Self {
self.ops.push(BatchOp::InsertEdge {
edge_type: edge_type.into(),
src_key: src_key.into(),
dst_key: dst_key.into(),
});
self
}
pub fn set_prop(&mut self, key: &str, field: &str, value: Value) -> &mut Self {
self.ops.push(BatchOp::SetProp {
key: key.into(),
field: field.into(),
value,
});
self
}
pub fn remove_prop(&mut self, key: &str, field: &str) -> &mut Self {
self.ops.push(BatchOp::RemoveProp {
key: key.into(),
field: field.into(),
});
self
}
pub fn delete_edge(&mut self, edge_type: &str, src_key: &str, dst_key: &str) -> &mut Self {
self.ops.push(BatchOp::DeleteEdge {
edge_type: edge_type.into(),
src_key: src_key.into(),
dst_key: dst_key.into(),
});
self
}
pub fn delete_node(&mut self, key: &str) -> &mut Self {
self.ops.push(BatchOp::DeleteNode { key: key.into() });
self
}
pub fn create_rule(&mut self, def: RuleDef) -> &mut Self {
self.ops.push(BatchOp::CreateRule(def));
self
}
pub fn delete_rule(&mut self, name: &str) -> &mut Self {
self.ops.push(BatchOp::DeleteRule { name: name.into() });
self
}
/// Queue a node-rename in this batch.
///
/// Validation (old exists, new not taken) runs at commit time.
pub fn rename_node(&mut self, old_key: &str, new_key: &str) -> &mut Self {
self.ops.push(BatchOp::RenameNode {
old_key: old_key.into(),
new_key: new_key.into(),
});
self
}
/// Queue an edge insert with endpoint auto-creation.
///
/// Any missing endpoint is created as a plain node `{key, label:
/// placeholder_label, no props}` inside this batch frame. Rules fire and
/// last-change is updated for each auto-created node.
pub fn insert_edge_upsert(
&mut self,
edge_type: &str,
src_key: &str,
dst_key: &str,
placeholder_label: &str,
) -> &mut Self {
self.ops.push(BatchOp::InsertEdgeUpsert {
edge_type: edge_type.into(),
src_key: src_key.into(),
dst_key: dst_key.into(),
placeholder_label: placeholder_label.into(),
});
self
}
/// Validate every queued op, then log one `Batch` frame and apply.
/// Empty / all-noop batches return `Ok(())` without writing the WAL.
/// A second `commit()` after a successful one is an empty-batch no-op
/// (queued ops were taken).
/// Takes `&mut self` so it chains after the queue methods (`b.insert_node(..).commit()`)
/// and also works as `let mut b = db.batch(); b.insert_node(..); b.commit()`.
///
/// **Rule-window limitation:** batch validation cannot see edges that a
/// rule created earlier in the *same* batch will derive at apply time, so
/// a `delete_edge` / `insert_edge` in that window is silently no-oped
/// where sequential calls would return `Err(RuleOwned)`. State integrity
/// is unaffected (idempotent apply, provenance intact). Create rules in
/// their own batch, or sequentially, when later ops may touch derived
/// edges.
/// Validate every queued op and commit atomically.
///
/// Returns `(nodes_inserted, edges_inserted)` — the counts of node and edge
/// WAL records actually written (duplicate edges are silent no-ops and are
/// NOT counted). Both are 0 when the batch is empty or all-noop.
pub fn commit(&mut self) -> Result<(usize, usize)> {
let ops = std::mem::take(&mut self.ops);
self.db.commit_batch(ops)
}
/// Same as [`commit`](Self::commit) but tail the inner events with
/// [`MutationEvent::Ingested`] instead of [`MutationEvent::BatchApplied`].
pub(crate) fn commit_ingest(&mut self, label: &str, inserted: usize) -> Result<(usize, usize)> {
let ops = std::mem::take(&mut self.ops);
self.db
.commit_logged_batch(ops, Some((label.to_string(), inserted)), None)
}
}
pub struct NodeRef<'a, F: Fs> {
db: &'a GraphDb<F>,
id: u32,
}
impl<'a, F: Fs> NodeRef<'a, F> {
pub fn key(&self) -> &str {
self.db.ids.key_of(self.id).expect("dense ids")
}
pub fn label(&self) -> &str {
let sym = self
.db
.labels
.get(self.id as usize)
.copied()
.filter(|&s| s != u32::MAX)
.expect("real nodes always have a label; u32::MAX sentinel cannot occur");
self.db.syms.resolve(sym).expect("interned label symbol")
}
pub fn prop(&self, field: &str) -> Option<Value> {
self.db
.props_view()
.get(self.id, field)
.map(|vr| vr.into_value())
}
/// All stored fields for this node, sorted by field name.
///
/// Reads from the full base+overlay view so that props stored only in the
/// V8 snapshot base (i.e. before any post-snapshot WAL writes) are visible.
pub fn props(&self) -> BTreeMap<String, Value> {
let mut out = BTreeMap::new();
let pv = self.db.props_view();
for field in pv.field_names() {
if let Some(vr) = pv.get(self.id, &field) {
out.insert(field, vr.into_value());
}
}
out
}
/// depth-N BFS as a ResultSet: columns ["key","label","depth"], BFS order.
pub fn neighborhood(&self, depth: u32, edge_types: Option<&[&str]>, dir: Dir) -> ResultSet {
let view = self.db.view();
let resolved: Option<Vec<u32>> = edge_types.map(|names| {
names
.iter()
.filter_map(|name| view.syms.get(name))
.collect()
});
let nb = neighborhood(&view, self.id, depth, resolved.as_deref(), dir);
let mut rs = ResultSet::new(vec!["key".into(), "label".into(), "depth".into()]);
for (nid, d) in nb.nodes {
let key = view.key_of(nid);
let label = view
.label_of(nid)
.expect("real nodes always have a label; u32::MAX sentinel cannot occur");
rs.push_row(vec![
Some(Value::Str(key.to_string())),
Some(Value::Str(label.to_string())),
Some(Value::Int(d as i64)),
]);
}
rs
}
/// 1-hop, Both directions: edge-type name → sorted unique neighbor keys.
pub fn grouped_by_edge_type(&self) -> BTreeMap<String, Vec<String>> {
let view = self.db.view();
let mut groups: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for e in expand(&view, self.id, None, Dir::Both) {
// Skip edges with unknown etypes (only possible from corrupt large
// TOPOLOGY section; function returns BTreeMap not Result).
let Some(etype) = view.syms.resolve(e.etype) else {
continue;
};
let etype = etype.to_string();
let nbr = if e.src == self.id { e.dst } else { e.src };
groups
.entry(etype)
.or_default()
.insert(view.key_of(nbr).to_string());
}
groups
.into_iter()
.map(|(k, v)| (k, v.into_iter().collect()))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use core_rules::Predicate;
fn tmp_dir(name: &str) -> std::path::PathBuf {
let d =
std::env::temp_dir().join(format!("graphdb-db-unit-{}-{}", name, std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
fn fk_rule() -> RuleDef {
RuleDef {
name: "works_at".into(),
src_label: "Person".into(),
dst_label: "Org".into(),
predicate: Predicate::KeyMatch {
field: "org_id".into(),
},
edge_type: "WORKS_AT".into(),
weight_prop: None,
max_edges: None,
approximate: false,
via_label: None,
via_edge: None,
via_dir: None,
namespace: None,
}
}
/// Regression guard for the no-views delta-copy fast path.
///
/// When no views are defined, `pending_deltas_since().to_vec()` must never
/// be called — even during a large CreateRule backfill. The DELTA_COPY_COUNT
/// thread-local is incremented inside every `if !view_store.is_empty()` block;
/// a count of 0 after the entire sequence proves the guard fires correctly.
#[test]
fn no_delta_copy_when_no_views() {
DELTA_COPY_COUNT.with(|c| c.set(0));
let dir = tmp_dir("no-delta-copy");
{
let mut db = GraphDb::open(&dir).unwrap();
// Insert 50 Org + 50 Person nodes with FK links.
for i in 0..50u32 {
db.insert_node("Org", &format!("o{i}"), vec![]).unwrap();
}
for i in 0..50u32 {
db.insert_node(
"Person",
&format!("p{i}"),
vec![("org_id".into(), Value::Str(format!("o{i}")))],
)
.unwrap();
}
// CreateRule backfill should NOT invoke to_vec() when no views are defined.
db.create_rule(fk_rule()).unwrap();
// Counter must stay 0 — no views, no copies.
let copies = DELTA_COPY_COUNT.with(|c| c.get());
assert_eq!(
copies, 0,
"pending_deltas_since().to_vec() called despite no views"
);
// Derived edges must still be correct (the guard skips only the
// empty delta propagation loop, not the rule application itself).
let nbrs = db.neighbors("p0", "WORKS_AT", Direction::Out).unwrap();
assert_eq!(
nbrs,
vec!["o0"],
"rule must derive edges even with no views"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// Gating regression: subscribe AFTER a backfill must see no stale events.
/// subscribe BEFORE a backfill must see every edge-fire event.
#[test]
fn subscribe_after_backfill_no_stale_events() {
let dir = tmp_dir("sub-after-backfill");
{
let mut db = GraphDb::open(&dir).unwrap();
for i in 0..10u32 {
db.insert_node("Org", &format!("o{i}"), vec![]).unwrap();
db.insert_node(
"Person",
&format!("p{i}"),
vec![("org_id".into(), Value::Str(format!("o{i}")))],
)
.unwrap();
}
// Create rule BEFORE subscribing — emit_deltas is false during backfill.
db.create_rule(fk_rule()).unwrap();
// Subscribe AFTER the backfill — queue must be empty (no stale events).
let sub = db.subscribe_all_rules().unwrap();
// No events should have queued for the prior backfill.
assert!(
sub.try_recv().is_none(),
"subscribe after backfill must see no stale events"
);
// Inserting a new node now should fire an event (emit_deltas is now true).
db.insert_node("Org", "o_new", vec![]).unwrap();
db.insert_node(
"Person",
"p_new",
vec![("org_id".into(), Value::Str("o_new".into()))],
)
.unwrap();
let ev = sub.recv_timeout(std::time::Duration::from_millis(200));
assert!(
ev.is_some(),
"edge-fire event must arrive after subscribe (emit_deltas=true)"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// Gating regression: subscribe BEFORE a backfill → events flow.
#[test]
fn subscribe_before_backfill_events_flow() {
let dir = tmp_dir("sub-before-backfill");
{
let mut db = GraphDb::open(&dir).unwrap();
// Subscribe FIRST — emit_deltas becomes true.
let sub = db.subscribe_all_rules().unwrap();
for i in 0..5u32 {
db.insert_node("Org", &format!("o{i}"), vec![]).unwrap();
db.insert_node(
"Person",
&format!("p{i}"),
vec![("org_id".into(), Value::Str(format!("o{i}")))],
)
.unwrap();
}
// Backfill fires with emit_deltas=true → events queued.
db.create_rule(fk_rule()).unwrap();
// Should receive at least one edge-fired event from the backfill.
let mut received = 0usize;
while sub.try_recv().is_some() {
received += 1;
}
assert!(
received > 0,
"subscribe before backfill must receive edge-fire events (got 0)"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// Companion: when a view IS defined, the delta path fires and view values update.
#[test]
fn delta_copy_fires_when_view_exists() {
use core_rules::ViewSource;
DELTA_COPY_COUNT.with(|c| c.set(0));
let dir = tmp_dir("delta-copy-with-view");
{
let mut db = GraphDb::open(&dir).unwrap();
db.insert_node("Org", "o1", vec![]).unwrap();
db.insert_node(
"Person",
"p1",
vec![("org_id".into(), Value::Str("o1".into()))],
)
.unwrap();
// Declare a Degree view so is_empty() returns false.
db.create_view(ViewDef {
name: "degree_out".into(),
label: "Person".into(),
view_prop: "degree_out".into(),
source: ViewSource::Degree {
edge_type: "WORKS_AT".into(),
direction: Direction::Out,
},
})
.unwrap();
db.create_rule(fk_rule()).unwrap();
// At least one delta copy should have happened (CreateRule backfill).
let copies = DELTA_COPY_COUNT.with(|c| c.get());
assert!(
copies > 0,
"expected delta copy to fire when a view is defined"
);
// View value should be computed: p1 has one WORKS_AT out-edge.
let info = db.node_info("p1").unwrap();
let degree = info.props.get("degree_out");
assert!(
degree.is_some(),
"view prop should be written to node props"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// Regression: `open_at_with` must call `rebuild_all` after WAL replay so
/// derived-edge-driven view values reflect the as-of state rather than just
/// the initial backfill written at `CreateView` time.
///
/// Base WAL frames (indices 0..=5 before history markers):
/// 0: insert Org "o1"
/// 1: create_view "employee_count" (Degree / WORKS_AT / In) on Org
/// 2: create_rule fk_rule (WORKS_AT, Person→Org via org_id)
/// 3: insert Person "p1" → rule fires WORKS_AT p1→o1 (degree = 1) ← mid
/// 4: insert Person "p2" → rule fires WORKS_AT p2→o1 (degree = 2)
/// 5: insert Person "p3" → rule fires WORKS_AT p3→o1 (degree = 3) ← latest
///
/// Each rule-fire also appends a DerivedEdgeAdded history-marker frame (state
/// no-op), so the total commit count is higher than the base frame count.
/// The "latest" open_at commit is computed dynamically via `wal_commit_count_at`.
///
/// Without `rebuild_all`, the as-of instance's "emp" view stays at the
/// initial backfill value (0) instead of reflecting the replayed derived edges.
#[test]
fn open_at_derived_edge_view_values_correct() {
use core_rules::ViewSource;
let dir = tmp_dir("open-at-view-rebuild");
{
let mut db = GraphDb::open(&dir).unwrap();
// frame 0
db.insert_node("Org", "o1", vec![]).unwrap();
// frame 1: create view — initial backfill sees 0 derived edges (none fired yet)
db.create_view(ViewDef {
name: "employee_count".into(),
label: "Org".into(),
view_prop: "emp".into(),
source: ViewSource::Degree {
edge_type: "WORKS_AT".into(),
direction: Direction::In,
},
})
.unwrap();
// frame 2: create rule — no Persons yet; backfill is a no-op
db.create_rule(fk_rule()).unwrap();
// frame 3: p1 — rule fires WORKS_AT p1→o1; degree = 1
db.insert_node(
"Person",
"p1",
vec![("org_id".into(), Value::Str("o1".into()))],
)
.unwrap();
// frame 4: p2 — degree = 2
db.insert_node(
"Person",
"p2",
vec![("org_id".into(), Value::Str("o1".into()))],
)
.unwrap();
// frame 5: p3 — degree = 3
db.insert_node(
"Person",
"p3",
vec![("org_id".into(), Value::Str("o1".into()))],
)
.unwrap();
// Sanity: normal open sees degree = 3.
assert_eq!(
db.get_view_prop("o1", "emp"),
Some(Value::Int(3)),
"normal db must show degree 3 after 3 derived edges"
);
} // WAL flushed
// Re-open normally to get the authoritative reference value.
let normal_db = GraphDb::open(&dir).unwrap();
let normal_emp = normal_db.get_view_prop("o1", "emp");
assert_eq!(
normal_emp,
Some(Value::Int(3)),
"re-opened normal db must show degree 3"
);
// Latest as-of (last WAL commit): must match the normal open.
// History-marker frames are appended after each rule-fire, so the total
// commit count is computed dynamically rather than hardcoded.
let total = crate::wal_commit_count_at(&dir).unwrap();
let aof_latest = GraphDb::open_at(&dir, total - 1).unwrap();
assert_eq!(
aof_latest.get_view_prop("o1", "emp"),
normal_emp,
"open_at latest: derived-edge view must equal normal open (rebuild_all required)"
);
// Mid-history as-of (commit 3 = p1 insert Batch frame): only p1; degree = 1.
// The DerivedEdgeAdded marker for p1 is at frame 4 (state no-op on replay),
// so replaying 0..=3 correctly re-derives only the p1→o1 edge.
let aof_mid = GraphDb::open_at(&dir, 3).unwrap();
assert_eq!(
aof_mid.get_view_prop("o1", "emp"),
Some(Value::Int(1)),
"open_at mid-history: only p1 exists at frame 3, degree must be 1"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Pin: subscribe_* on an as-of instance must return Err(ReadOnly) —
/// as-of instances never commit, so distribute_events never runs and any
/// subscription would wait forever.
#[test]
fn subscribe_on_as_of_returns_read_only_error() {
let dir = tmp_dir("sub-as-of-read-only");
{
let mut db = GraphDb::open(&dir).unwrap();
db.insert_node("Org", "o1", vec![]).unwrap();
db.create_rule(fk_rule()).unwrap();
}
let mut aof = GraphDb::open_at(&dir, 0).unwrap();
assert!(
matches!(
aof.subscribe_all_rules(),
Err(core_storage::GraphError::ReadOnly)
),
"subscribe_all_rules on as-of must return ReadOnly"
);
assert!(
matches!(
aof.subscribe_writes(),
Err(core_storage::GraphError::ReadOnly)
),
"subscribe_writes on as-of must return ReadOnly"
);
assert!(
matches!(
aof.subscribe_rule("works_at"),
Err(core_storage::GraphError::ReadOnly)
),
"subscribe_rule on as-of must return ReadOnly"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Regression: a failed dense WAL rewrite must not leave speculative
/// interns in `syms`. If it does, the next successful mutation logs an
/// `Intern` record with an inflated id; replay (which never saw the
/// orphans) assigns a smaller id and the WAL becomes unreplayable.
#[test]
fn dense_rewrite_error_rolls_back_speculative_interns() {
let dir = tmp_dir("dense-rewrite-rollback");
{
let mut db = GraphDb::open(&dir).unwrap();
db.insert_node("Person", "a", vec![]).unwrap();
// Bypass MutPreview validation to hit the rewrite's own error path
// (same shape as an id-exhaustion failure mid-rewrite). The
// InsertEdge arm interns the edge type before it resolves keys.
let err = db.rewrite_wal_dense(vec![WalRecord::InsertEdge {
edge_type: "ORPHAN_TYPE".into(),
src_key: "missing".into(),
dst_key: "a".into(),
}]);
assert!(err.is_err(), "rewrite of a missing src key must fail");
assert_eq!(
db.syms.get("ORPHAN_TYPE"),
None,
"failed rewrite must roll back speculative interns"
);
// A later successful mutation must produce a replayable WAL.
db.set_prop("a", "later_field", Value::Int(2)).unwrap();
}
let db = GraphDb::open(&dir).expect("WAL must replay after failed rewrite");
assert_eq!(db.get_prop("a", "later_field"), Some(Value::Int(2)));
let _ = std::fs::remove_dir_all(&dir);
}
}