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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team
use crate::runtime::context::QueryContext;
use crate::runtime::flush_coordinator::{
FinalizeFn, FlushCoordinator, FlushOutcome as AsyncFlushOutcome, RotatedFlush, SharedFlushCtx,
};
use crate::runtime::id_allocator::IdAllocator;
use crate::runtime::l0::{L0Buffer, serialize_constraint_key};
use crate::runtime::l0_manager::L0Manager;
use crate::runtime::property_manager::PropertyManager;
use crate::runtime::wal::WriteAheadLog;
use crate::storage::adjacency_manager::AdjacencyManager;
use crate::storage::delta::{L1Entry, Op};
use crate::storage::main_edge::MainEdgeDataset;
use crate::storage::main_vertex::MainVertexDataset;
use crate::storage::manager::StorageManager;
use anyhow::{Result, anyhow};
use chrono::Utc;
use metrics;
use parking_lot::{Mutex as PlMutex, RwLock};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use tracing::{debug, info, instrument};
use uni_common::Properties;
use uni_common::Value;
use uni_common::config::UniConfig;
use uni_common::core::fork::ForkId;
use uni_common::core::id::{Eid, Vid};
use uni_common::core::schema::{ConstraintTarget, ConstraintType, IndexDefinition};
use uni_common::core::snapshot::{EdgeSnapshot, LabelSnapshot, SnapshotManifest};
use uni_xervo::runtime::ModelRuntime;
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct WriterConfig {
pub max_mutations: usize,
/// Enable the partial-column MergeInsert path for SET-only flushes.
///
/// When `true`, `Writer::insert_vertex_partial` records the touched
/// property keys into `L0Buffer::vertex_partial_keys` and the flush
/// routes those VIDs through Lance `MergeInsertBuilder` with a
/// subset-of-schema source, skipping the read of (and write of)
/// the unchanged columns — including wide ones like embeddings.
///
/// When `false`, `insert_vertex_partial` falls back to the
/// read-modify-write `insert_vertex_with_labels` path (preserving
/// bit-for-bit equivalence with prior releases). Default `false`
/// for the first release; flip to `true` after telemetry on the
/// issue #72 ingest workload confirms the win.
///
/// See the soundness probe at
/// `crates/uni-store/tests/common/storage/lance_merge_insert_probe.rs`.
pub partial_lance_writes: bool,
}
impl Default for WriterConfig {
fn default() -> Self {
Self {
max_mutations: 10_000,
partial_lance_writes: false,
}
}
}
/// RAII latch on [`StorageManager::flush_in_progress`].
///
/// Sets the flag to `true` on construction (via CAS) and back to `false` on
/// drop, so any `?` early-exit inside `flush_to_l1` cannot leave the flag
/// stuck. Returns `None` if a flush is already in progress, providing
/// forward-compatible exclusion once the outer writer-RwLock is removed in
/// Phase 4 of the concurrent-writer refactor.
// FlushInProgressGuard moved to storage/manager.rs so flush_coordinator.rs
// can hold it on RotatedFlush without a writer.rs back-import cycle.
pub use crate::storage::manager::FlushInProgressGuard;
/// Output of [`Writer::flush_l0_rotate`]: the to-be-flushed L0 buffer,
/// captured WAL LSN, current_version, and the in-progress guard whose
/// lifetime spans the full flush (including the future async stream
/// phase that runs on a spawned task).
struct RotateOutput {
old_l0_arc: Arc<RwLock<L0Buffer>>,
wal_lsn: u64,
current_version: u64,
flush_in_progress_guard: FlushInProgressGuard,
}
/// Project a property map to a subset selected by `keys`. Used to
/// run `touched_needs_full_read` against just the SET-touched keys
/// when the caller passes a fully-merged `props` map.
fn props_subset(props: &Properties, keys: &HashSet<String>) -> Properties {
let mut out = Properties::new();
for k in keys {
if let Some(v) = props.get(k) {
out.insert(k.clone(), v.clone());
}
}
out
}
/// Output of [`Writer::flush_stream_l1`]: the built (but not yet
/// published) snapshot manifest and its id. Finalize is responsible
/// for `save_snapshot` + `set_latest_snapshot` + `cached_manifest`
/// update.
struct FlushOutcome {
manifest: SnapshotManifest,
snapshot_id: String,
}
pub struct Writer {
pub l0_manager: Arc<L0Manager>,
pub storage: Arc<StorageManager>,
pub schema_manager: Arc<uni_common::core::schema::SchemaManager>,
pub allocator: Arc<IdAllocator>,
pub config: UniConfig,
/// Optional embedding runtime. `OnceLock` so the initializer can run
/// on `&self` after the `Writer` has been wrapped in `Arc<Writer>`
/// (Phase 4 of concurrent_writer.md). Read through
/// [`Writer::xervo_runtime`] — the field itself is private to keep
/// callers oblivious to the OnceLock representation.
xervo_runtime: OnceLock<Arc<ModelRuntime>>,
/// Property manager for cache invalidation after flush
pub property_manager: Option<Arc<PropertyManager>>,
/// Adjacency manager for dual-write (edges survive flush).
adjacency_manager: Arc<AdjacencyManager>,
/// Timestamp of last flush or creation. Interior-mutable so that
/// `&self` callers can update it; uncontended in practice because all
/// writes happen inside the single-flusher critical section.
/// Arc-wrapped so it can travel into the SharedFlushCtx that the
/// async-flush coordinator passes to spawned stream/finalize tasks.
last_flush_time: Arc<PlMutex<std::time::Instant>>,
/// Background compaction task handle (prevents concurrent compaction races)
compaction_handle: Arc<RwLock<Option<tokio::task::JoinHandle<()>>>>,
/// Optional index rebuild manager for post-flush automatic rebuild scheduling.
/// `OnceLock` for the same reason as `xervo_runtime`.
/// Wrapped in `Arc` so the async-flush finalize path can read it
/// from a spawned task via `SharedFlushCtx`.
index_rebuild_manager: Arc<OnceLock<Arc<crate::storage::index_rebuild::IndexRebuildManager>>>,
/// Cached snapshot manifest from the last flush. Avoids re-reading from
/// object store on every flush_to_l1 call. Wrapped in a `Mutex` for
/// `&self` access; uncontended because all access is inside the
/// single-flusher critical section.
cached_manifest: Arc<PlMutex<Option<SnapshotManifest>>>,
/// Identifier of the fork this writer serves, if any. `None` for
/// primary's writer. Set by [`crate::fork::writer_factory::new_for_fork`]
/// and read in `flush_to_l1` to emit fork-tagged metrics and to fire
/// the fragment-count guard rail (Phase 2 Day 12).
pub fork_id: Option<ForkId>,
/// Number of `flush_to_l1` calls since this writer was constructed.
/// Used as a proxy for L1 fragment growth on the fork's branches:
/// each flush typically appends ~1 fragment per touched dataset, so
/// the count tracks the order of magnitude of fragment accumulation.
/// Reading the actual `Dataset::manifest().fragments.len()` per
/// flush would add a per-dataset object-store roundtrip on the hot
/// commit path; the proxy keeps the guard rail purely observational
/// (Phase 5 introduces fork compaction proper). Only meaningful when
/// `fork_id.is_some()`. `Relaxed` is sufficient — observational only.
fork_flush_count: Arc<AtomicU64>,
/// Whether the fork-fragment warning has already fired at the
/// configured threshold. One-shot per writer lifetime. `Relaxed` is
/// sufficient — observational only.
fork_fragment_warn_fired: Arc<AtomicBool>,
/// Dedicated lock for the genuinely-exclusive flush path. Acquired by
/// the [`Writer::flush_to_l1`] entry and by `commit_transaction_l0`
/// across its WAL-append + L0-merge window. Replaces the outer
/// `Arc<RwLock<Writer>>` for flush exclusion once Phase 4 drops it.
/// Arc-wrapped so async-flush coordinator's finalize path can
/// re-acquire it from a spawned task via SharedFlushCtx.
flush_lock: Arc<tokio::sync::Mutex<()>>,
/// Coordinator for async-flush pipeline. Owns the back-pressure
/// semaphore, rotate-order sequence, single-finalizer task, and
/// pending-flush counter. Always present even when async flush is
/// disabled — the sync `flush_to_l1` path uses it for the future
/// `FlushInProgressGuard`/permit ownership model.
/// Coordinator is `None` when `async_flush_enabled = false`. The
/// coordinator's finalizer task captures `SharedFlushCtx` which
/// includes `Arc<StorageManager>`; on a fork-scoped Writer that
/// also pins the fork's `ForkScope` via `storage.fork_scope`, so
/// the holder count never drops. Constructing it only when the
/// feature is actually on avoids that side-effect for all
/// existing sync-flush paths. When async-flush graduates from
/// opt-in to default (Commit 12), `drop_fork` (Commit 8) handles
/// the drain explicitly.
#[allow(dead_code)] // first production use lands in Commit 6/7
pub(crate) flush_coordinator: Option<Arc<crate::runtime::flush_coordinator::FlushCoordinator>>,
/// Optimistic-concurrency commit-sequence counter (SSI). Incremented once
/// per successful commit under `flush_lock`; a transaction captures the
/// current value at begin as its read sequence (`L0Buffer::occ_read_seq`).
///
/// Always allocated; consulted only when `config.ssi_enabled` is `true`.
commit_sequence: Arc<AtomicU64>,
/// Bounded log of recently-committed write-sets for OCC conflict detection.
/// Read and updated only under `flush_lock`.
///
/// Always allocated; consulted only when `config.ssi_enabled` is `true`.
committed_writes: Arc<PlMutex<crate::runtime::occ::CommitRegistry>>,
/// Per-row pessimistic locks for `FOR UPDATE` (SSI escape hatch), keyed by
/// canonical (label, key-props) bytes. A transaction holds the lock from
/// MATCH until commit/rollback, serializing concurrent `FOR UPDATE` writers
/// on the same key (avoiding optimistic abort-retry on hot keys).
///
/// Always allocated; populated only when `config.ssi_enabled` is `true`.
for_update_locks: Arc<dashmap::DashMap<Vec<u8>, Arc<tokio::sync::Mutex<()>>>>,
}
/// Number of recent commits retained for OCC conflict detection. Large enough
/// that under-run — and the resulting conservative abort — is rare in practice;
/// each entry is a small set of touched ids.
const OCC_REGISTRY_CAPACITY: usize = 4096;
impl Writer {
pub async fn new(
storage: Arc<StorageManager>,
schema_manager: Arc<uni_common::core::schema::SchemaManager>,
start_version: u64,
) -> Result<Self> {
Self::new_with_config(
storage,
schema_manager,
start_version,
UniConfig::default(),
None,
None,
)
.await
}
pub async fn new_with_config(
storage: Arc<StorageManager>,
schema_manager: Arc<uni_common::core::schema::SchemaManager>,
start_version: u64,
config: UniConfig,
wal: Option<Arc<WriteAheadLog>>,
allocator: Option<Arc<IdAllocator>>,
) -> Result<Self> {
let allocator = if let Some(a) = allocator {
a
} else {
let store = storage.store();
let path = object_store::path::Path::from("id_allocator.json");
Arc::new(IdAllocator::new(store, path, 1000).await?)
};
let l0_manager = Arc::new(L0Manager::new(start_version, wal));
let property_manager = Some(Arc::new(PropertyManager::new(
storage.clone(),
schema_manager.clone(),
1000,
)));
let adjacency_manager = storage.adjacency_manager();
// Hoist the Arc'd fields so we can both stash them on Writer and
// hand the same Arcs to the SharedFlushCtx that FlushCoordinator
// captures. Single-source-of-truth for each piece of mutable
// shared state.
let last_flush_time = Arc::new(PlMutex::new(std::time::Instant::now()));
let cached_manifest = Arc::new(PlMutex::new(None));
let fork_flush_count = Arc::new(AtomicU64::new(0));
let fork_fragment_warn_fired = Arc::new(AtomicBool::new(false));
let flush_lock = Arc::new(tokio::sync::Mutex::new(()));
let compaction_handle = Arc::new(RwLock::new(None));
let index_rebuild_manager: Arc<
OnceLock<Arc<crate::storage::index_rebuild::IndexRebuildManager>>,
> = Arc::new(OnceLock::new());
let flush_coordinator = if config.async_flush_enabled {
let shared = SharedFlushCtx {
storage: storage.clone(),
l0_manager: l0_manager.clone(),
adjacency_manager: adjacency_manager.clone(),
property_manager: property_manager.clone(),
schema_manager: schema_manager.clone(),
cached_manifest: cached_manifest.clone(),
last_flush_time: last_flush_time.clone(),
fork_id: None,
fork_flush_count: fork_flush_count.clone(),
fork_fragment_warn_fired: fork_fragment_warn_fired.clone(),
fork_fragment_warn_threshold: config.fork_fragment_warn_threshold,
flush_lock: flush_lock.clone(),
index_rebuild_manager: index_rebuild_manager.clone(),
compaction_handle: compaction_handle.clone(),
compaction_config: config.compaction.clone(),
index_rebuild_config: config.index_rebuild.clone(),
auto_rebuild_enabled: config.index_rebuild.auto_rebuild_enabled,
};
let finalize_fn: Arc<dyn FinalizeFn> = Arc::new(WriterFinalizer);
Some(Arc::new(FlushCoordinator::new(
config.max_pending_flushes,
shared,
finalize_fn,
)))
} else {
None
};
let commit_sequence = Arc::new(AtomicU64::new(0));
let committed_writes = Arc::new(PlMutex::new(crate::runtime::occ::CommitRegistry::new(
OCC_REGISTRY_CAPACITY,
)));
let for_update_locks = Arc::new(dashmap::DashMap::new());
Ok(Self {
l0_manager,
storage,
schema_manager,
allocator,
config,
xervo_runtime: OnceLock::new(),
property_manager,
adjacency_manager,
last_flush_time,
compaction_handle,
index_rebuild_manager,
cached_manifest,
fork_id: None,
fork_flush_count,
fork_fragment_warn_fired,
flush_lock,
flush_coordinator,
commit_sequence,
committed_writes,
for_update_locks,
})
}
/// Returns the shared pessimistic lock handle for a `FOR UPDATE` row key,
/// creating it on first use. The caller `.lock_owned().await`s the returned
/// mutex and holds the guard for the transaction's lifetime.
pub fn row_lock_handle(&self, key: &[u8]) -> Arc<tokio::sync::Mutex<()>> {
self.for_update_locks
.entry(key.to_vec())
.or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
.clone()
}
/// Prunes `FOR UPDATE` lock-map entries for `keys` that no live transaction
/// holds anymore, so the map does not grow without bound across the keyspace.
///
/// Called when a transaction ends, **after** its guards have been dropped.
/// `remove_if` evaluates its predicate under the DashMap shard lock, which is
/// the same lock `row_lock_handle` takes to clone an entry — so the check
/// `strong_count == 1` (only the map holds the `Arc`) is race-free: a
/// concurrent acquirer either already cloned the `Arc` (count ≥ 2 → we skip
/// removal) or has not yet taken the shard lock (it will mint a fresh entry
/// after we remove). Either way no two transactions ever lock different
/// `Mutex` instances for the same key.
pub fn release_for_update_locks(&self, keys: &[Vec<u8>]) {
for key in keys {
self.for_update_locks
.remove_if(key, |_, handle| Arc::strong_count(handle) == 1);
}
}
/// Number of live entries in the `FOR UPDATE` lock map. Introspection for
/// tests that the map does not leak entries across transactions (G5).
pub fn for_update_lock_count(&self) -> usize {
self.for_update_locks.len()
}
/// The current OCC commit sequence. A `FOR UPDATE` acquisition re-stamps a
/// fresh transaction's `occ_read_seq` to this so its conflict-detection
/// baseline advances to lock-acquisition time (read-latest under the lock).
pub fn current_commit_sequence(&self) -> u64 {
self.commit_sequence.load(Ordering::Relaxed)
}
/// Build a fresh `SharedFlushCtx` from this Writer's current state.
/// Used by the async-flush stream/finalize paths to pass into spawned
/// tasks without smuggling `Arc<Writer>` (which would create a cycle
/// with `flush_coordinator -> FinalizeFn -> Writer`).
pub(crate) fn shared_ctx(&self) -> SharedFlushCtx {
SharedFlushCtx {
storage: self.storage.clone(),
l0_manager: self.l0_manager.clone(),
adjacency_manager: self.adjacency_manager.clone(),
property_manager: self.property_manager.clone(),
schema_manager: self.schema_manager.clone(),
cached_manifest: self.cached_manifest.clone(),
last_flush_time: self.last_flush_time.clone(),
fork_id: self.fork_id,
fork_flush_count: self.fork_flush_count.clone(),
fork_fragment_warn_fired: self.fork_fragment_warn_fired.clone(),
fork_fragment_warn_threshold: self.config.fork_fragment_warn_threshold,
flush_lock: self.flush_lock.clone(),
index_rebuild_manager: self.index_rebuild_manager.clone(),
compaction_handle: self.compaction_handle.clone(),
compaction_config: self.config.compaction.clone(),
index_rebuild_config: self.config.index_rebuild.clone(),
auto_rebuild_enabled: self.config.index_rebuild.auto_rebuild_enabled,
}
}
/// Borrow the flush coordinator if async flush is enabled.
/// Returns `None` when `config.async_flush_enabled = false`.
/// External callers (`drop_fork`) use this to drain pending streams.
pub fn flush_coordinator(
&self,
) -> Option<&Arc<crate::runtime::flush_coordinator::FlushCoordinator>> {
self.flush_coordinator.as_ref()
}
/// Set the index rebuild manager for post-flush automatic rebuild scheduling.
///
/// One-shot: returns `Err` if already set. The receiver is `&self` so this
/// can be called after the `Writer` has been wrapped in `Arc<Writer>`.
pub fn set_index_rebuild_manager(
&self,
manager: Arc<crate::storage::index_rebuild::IndexRebuildManager>,
) -> Result<()> {
self.index_rebuild_manager
.set(manager)
.map_err(|_| anyhow!("index_rebuild_manager already set"))
}
/// Replay WAL mutations into the current L0 buffer.
pub async fn replay_wal(&self, wal_high_water_mark: u64) -> Result<usize> {
let l0 = self.l0_manager.get_current();
let wal = l0.read().wal.clone();
if let Some(wal) = wal {
wal.initialize().await?;
let mutations = wal.replay_since(wal_high_water_mark).await?;
let count = mutations.len();
if count > 0 {
log::info!(
"Replaying {} mutations from WAL (LSN > {})",
count,
wal_high_water_mark
);
let mut l0_guard = l0.write();
l0_guard.replay_mutations(mutations)?;
}
Ok(count)
} else {
Ok(0)
}
}
/// Allocates the next VID (pure auto-increment).
pub async fn next_vid(&self) -> Result<Vid> {
self.allocator.allocate_vid().await
}
/// Allocates multiple VIDs at once for bulk operations.
/// This is more efficient than calling next_vid() in a loop.
pub async fn allocate_vids(&self, count: usize) -> Result<Vec<Vid>> {
self.allocator.allocate_vids(count).await
}
/// Allocates the next EID (pure auto-increment).
pub async fn next_eid(&self, _type_id: u32) -> Result<Eid> {
self.allocator.allocate_eid().await
}
/// Allocates multiple EIDs at once for bulk operations.
/// This is more efficient than calling next_eid() in a loop.
pub async fn allocate_eids(&self, count: usize) -> Result<Vec<Eid>> {
self.allocator.allocate_eids(count).await
}
/// Install the embedding runtime exactly once. Receiver is `&self` so it
/// can be called after the `Writer` has been wrapped in `Arc<Writer>`.
pub fn set_xervo_runtime(&self, runtime: Arc<ModelRuntime>) -> Result<()> {
self.xervo_runtime
.set(runtime)
.map_err(|_| anyhow!("xervo_runtime already set"))
}
pub fn xervo_runtime(&self) -> Option<Arc<ModelRuntime>> {
self.xervo_runtime.get().cloned()
}
/// Create a new empty L0 buffer for transaction-scoped mutations.
///
/// Only reads the current version — no exclusive lock required on Writer.
/// The returned buffer has no WAL reference; mutations are logged at
/// commit time via [`Self::commit_transaction_l0`].
pub fn create_transaction_l0(&self) -> Arc<RwLock<L0Buffer>> {
let current_version = self.l0_manager.get_current().read().current_version;
// Transaction mutations are logged to WAL at COMMIT time, not during the transaction.
let buf = L0Buffer::new(current_version, None);
// SSI: stamp the OCC read sequence at begin so commit can detect any
// transaction that committed since. Gated on the runtime `ssi_enabled`
// toggle — when off, `occ_read_set` stays `None` and every downstream
// read-set recording / commit validation self-gates to a no-op.
let buf = if self.config.ssi_enabled {
let mut buf = buf;
buf.occ_read_seq = self.commit_sequence.load(Ordering::Relaxed);
// The read path records observed ids here for SSI antidependency
// detection; commit consults it.
buf.occ_read_set = Some(Arc::new(parking_lot::Mutex::new(
crate::runtime::l0::OccReadSet::default(),
)));
buf
} else {
buf
};
Arc::new(RwLock::new(buf))
}
/// Resolve the target L0 buffer for a mutation.
///
/// When `tx_l0` is `Some`, the mutation targets a transaction-private buffer.
/// When `None`, it targets the global L0 from the manager.
fn resolve_l0(&self, tx_l0: Option<&Arc<RwLock<L0Buffer>>>) -> Arc<RwLock<L0Buffer>> {
tx_l0
.cloned()
.unwrap_or_else(|| self.l0_manager.get_current())
}
fn update_metrics(&self) {
let l0 = self.l0_manager.get_current();
let size = l0.read().estimated_size;
metrics::gauge!("l0_buffer_size_bytes").set(size as f64);
}
/// Commit an externally-owned transaction L0 buffer.
///
/// Writes mutations to WAL, flushes, merges into main L0, and replays
/// edges into the AdjacencyManager. Returns the WAL LSN of the commit
/// (0 when no WAL is configured).
/// Commit a transaction's private L0 buffer into main L0.
///
/// Returns `(wal_lsn, flush_pending)`. When `flush_pending == true`, the
/// post-commit `should_flush()` predicate fired but no flush ran — the
/// caller is expected to spawn a background `flush_to_l1`. This is the
/// shape used when `UniConfig::async_flush_enabled` is set, so commits
/// don't block on L1-streaming I/O.
pub async fn commit_transaction_l0(
self: &Arc<Self>,
tx_l0_arc: Arc<RwLock<L0Buffer>>,
) -> Result<(u64, bool)> {
// Hold `flush_lock` across WAL append + flush + main-L0 merge.
// Two concurrent commits serialize here; in Phase 3 the outer
// `Arc<RwLock<Writer>>` already provides this exclusion, so the
// acquisition is uncontended. Phase 4 drops the outer lock and
// this becomes the load-bearing serialization point.
let _flush_lock_guard = self.flush_lock.lock().await;
// Crash-recovery seam: simulate process death immediately after winning
// the commit serialization point but before any durable work. No-op
// unless built with `--features failpoints`. (See ssi_resilience tests.)
fail::fail_point!("commit::after-flush-lock");
// SSI: optimistic conflict detection. This MUST run before any WAL
// write — `flush_wal()` below is the durable commit point and the WAL
// has no abort marker, so aborting after it would resurrect this
// transaction on crash recovery. The write-set is reused for
// registration after a successful merge.
// Runtime-gated on `config.ssi_enabled`. When off, no validation runs
// and `occ_write_set` is `None`, so the post-merge registration below
// is skipped — reproducing last-writer-wins exactly.
let occ_write_set: Option<crate::runtime::occ::WriteSet> = if self.config.ssi_enabled {
let tx_l0 = tx_l0_arc.read();
let read_seq = tx_l0.occ_read_seq;
let write_set = crate::runtime::occ::WriteSet::from_l0(&tx_l0);
if !write_set.is_empty() {
// Telemetry: one validation per non-empty (writing) commit. The
// ratio of conflicts to validations is the headline abort rate.
metrics::counter!("uni_ssi_commit_validations_total").increment(1);
// Read-set is consulted only for writing transactions, so a
// read-only commit (empty write-set) runs at snapshot isolation.
let read_guard = tx_l0.occ_read_set.as_ref().map(|rs| rs.lock());
if let Some(conflict) =
self.committed_writes
.lock()
.check(read_seq, &write_set, read_guard.as_deref())
{
use crate::runtime::occ::Conflict;
match &conflict {
Conflict::WriteWrite { .. } => metrics::counter!(
"uni_ssi_serialization_conflicts_total",
"kind" => "write_write",
)
.increment(1),
Conflict::ReadWrite { .. } => metrics::counter!(
"uni_ssi_serialization_conflicts_total",
"kind" => "read_write",
)
.increment(1),
Conflict::HistoryTruncated { .. } => {
metrics::counter!("uni_ssi_history_truncated_total").increment(1)
}
}
return Err(anyhow::Error::new(
uni_common::UniError::SerializationConflict {
message: conflict.to_string(),
},
));
}
}
// Validate against the committed main L0 under `flush_lock`:
// serializable MERGE uniqueness + CRDT carve-out soundness.
{
let main_l0 = self.l0_manager.get_current();
let main_l0 = main_l0.read();
// SSI / serializable MERGE: abort if a concurrent transaction has
// already committed a row with one of this transaction's unique
// keys. Commits serialize here, so this closes the race window
// left by the per-insert check. (Empty index → no iterations.)
for (key, vid) in &tx_l0.constraint_index {
if main_l0.has_constraint_key(key, *vid) {
metrics::counter!("uni_ssi_constraint_conflicts_total").increment(1);
return Err(anyhow::Error::new(
uni_common::UniError::ConstraintConflict {
message: "unique key already committed by a concurrent \
transaction"
.to_string(),
},
));
}
}
// CRDT carve-out soundness: a pure-CRDT write was dropped from the
// write-set assuming its merge commutes. If main L0 holds a
// *different* CRDT variant for the same property, the merge would
// silently overwrite it — abort instead of losing the update.
if let Some(conflict) =
crate::runtime::occ::crdt_carveout_overwrite(&tx_l0, &main_l0)
{
metrics::counter!("uni_ssi_crdt_aborts_total").increment(1);
return Err(anyhow::Error::new(
uni_common::UniError::SerializationConflict {
message: conflict.to_string(),
},
));
}
}
Some(write_set)
} else {
None
};
// Crash-recovery seam: SSI validation has passed; the transaction is
// about to become durable. A crash here must leave NO trace (validation
// happens before the WAL is touched). No-op unless `failpoints`.
fail::fail_point!("commit::after-validate");
// 1. Write transaction mutations to WAL BEFORE merging into main L0
// This ensures durability before visibility.
{
let tx_l0 = tx_l0_arc.read();
let main_l0_arc = self.l0_manager.get_current();
let main_l0 = main_l0_arc.read();
// If WAL exists, write mutations to it for durability
if let Some(wal) = main_l0.wal.as_ref() {
// Order: vertices first, then edges (to ensure src/dst exist on replay)
// Vertex insertions
for (vid, properties) in &tx_l0.vertex_properties {
if !tx_l0.vertex_tombstones.contains(vid) {
let labels = tx_l0.vertex_labels.get(vid).cloned().unwrap_or_default();
wal.append(&crate::runtime::wal::Mutation::InsertVertex {
vid: *vid,
properties: properties.clone(),
labels,
})?;
}
}
// Vertex deletions
for vid in &tx_l0.vertex_tombstones {
let labels = tx_l0.vertex_labels.get(vid).cloned().unwrap_or_default();
wal.append(&crate::runtime::wal::Mutation::DeleteVertex { vid: *vid, labels })?;
}
// Label-only mutations (SET n:Label / REMOVE n:Label). After
// vertex inserts (so the vertex exists on replay), before edges,
// and skipping vertices deleted in this same commit.
for vid in &tx_l0.vertex_label_overwrites {
if tx_l0.vertex_tombstones.contains(vid) {
continue;
}
let labels = tx_l0.vertex_labels.get(vid).cloned().unwrap_or_default();
wal.append(&crate::runtime::wal::Mutation::SetVertexLabels {
vid: *vid,
labels,
})?;
}
// Crash-recovery seam: vertices appended, edges not yet. Tests
// assert that a crash here (before `flush_wal`) recovers NOTHING
// — the durable commit point is the flush below, not append.
fail::fail_point!("commit::mid-wal");
// Edge insertions and deletions from edge_endpoints
for (eid, (src_vid, dst_vid, edge_type)) in &tx_l0.edge_endpoints {
if tx_l0.tombstones.contains_key(eid) {
let version = tx_l0.edge_versions.get(eid).copied().unwrap_or(0);
wal.append(&crate::runtime::wal::Mutation::DeleteEdge {
eid: *eid,
src_vid: *src_vid,
dst_vid: *dst_vid,
edge_type: *edge_type,
version,
})?;
} else {
let properties =
tx_l0.edge_properties.get(eid).cloned().unwrap_or_default();
let version = tx_l0.edge_versions.get(eid).copied().unwrap_or(0);
let edge_type_name = tx_l0.edge_types.get(eid).cloned();
wal.append(&crate::runtime::wal::Mutation::InsertEdge {
src_vid: *src_vid,
dst_vid: *dst_vid,
edge_type: *edge_type,
eid: *eid,
version,
properties,
edge_type_name,
})?;
}
}
// Tombstones for edges that only exist in the global L0 (not in
// this transaction's edge_endpoints). Without this, deletes of
// pre-existing edges would be silently lost.
for (eid, tombstone) in &tx_l0.tombstones {
if !tx_l0.edge_endpoints.contains_key(eid) {
let version = tx_l0.edge_versions.get(eid).copied().unwrap_or(0);
wal.append(&crate::runtime::wal::Mutation::DeleteEdge {
eid: *eid,
src_vid: tombstone.src_vid,
dst_vid: tombstone.dst_vid,
edge_type: tombstone.edge_type,
version,
})?;
}
}
}
}
// 2. Flush WAL to durable storage - THIS IS THE COMMIT POINT
let wal_lsn = self.flush_wal().await?;
// Crash-recovery seam: the WAL is durable but main L0 has NOT merged.
// A crash here must RECOVER the transaction on replay (it is committed),
// even though it was never made visible in-process. No-op unless `failpoints`.
fail::fail_point!("commit::after-wal-flush");
// Component C1: if an outstanding snapshot pins the current generation,
// clone it aside (lazy copy-on-write) before merging, so the pinning
// transaction's reads stay isolated from this commit. No-op — and zero
// cost — when nothing is pinned (the common case). We hold `flush_lock`,
// so this cannot race a flush rotate or another commit's merge; the merge
// below re-fetches `get_current()`, landing in the fresh post-freeze buffer.
// Self-gates on the runtime SSI toggle: a snapshot is only ever pinned by
// a transaction begun under `ssi_enabled`, so `is_current_pinned()` is
// always false when SSI is off and this is a zero-cost no-op.
if self.l0_manager.is_current_pinned() {
self.l0_manager.freeze_current_for_snapshot();
metrics::counter!("uni_l0_snapshot_freezes_total").increment(1);
}
// 3. Merge into main L0 and make visible
{
let tx_l0 = tx_l0_arc.read();
let main_l0_arc = self.l0_manager.get_current();
let mut main_l0 = main_l0_arc.write();
main_l0.merge(&tx_l0)?;
// Replay transaction edges into the AdjacencyManager overlay
for (eid, (src, dst, etype)) in &tx_l0.edge_endpoints {
let edge_version = tx_l0
.edge_versions
.get(eid)
.copied()
.unwrap_or(main_l0.current_version);
if tx_l0.tombstones.contains_key(eid) {
self.adjacency_manager
.add_tombstone(*eid, *src, *dst, *etype, edge_version);
} else {
self.adjacency_manager
.insert_edge(*src, *dst, *eid, *etype, edge_version);
}
}
// Replay tombstones for edges that only exist in the global L0
// (not in this transaction's edge_endpoints).
for (eid, tombstone) in &tx_l0.tombstones {
if !tx_l0.edge_endpoints.contains_key(eid) {
let edge_version = tx_l0
.edge_versions
.get(eid)
.copied()
.unwrap_or(main_l0.current_version);
self.adjacency_manager.add_tombstone(
*eid,
tombstone.src_vid,
tombstone.dst_vid,
tombstone.edge_type,
edge_version,
);
}
}
}
// Crash-recovery seam: durable AND merged, but the in-memory commit
// registry has not recorded this write-set yet. A crash here is
// indistinguishable from one at `after-wal-flush` on reopen (the
// registry is in-memory and rebuilt empty); the tx still recovers.
fail::fail_point!("commit::after-merge");
// SSI: register this commit's write-set under a fresh commit sequence so
// later transactions detect conflicts against it. Still under
// `flush_lock`, before the async-flush branch can drop the guard.
// `occ_write_set` is `Some` only when `config.ssi_enabled`.
if let Some(write_set) = occ_write_set
&& !write_set.is_empty()
{
let seq = self.commit_sequence.fetch_add(1, Ordering::Relaxed) + 1;
self.committed_writes.lock().record(seq, write_set);
}
self.update_metrics();
// 4. Best-effort post-commit auto-flush.
//
// Two paths:
// - async_flush_enabled = false (default): inline under our
// existing flush_lock guard via flush_inline_under_lock.
// - async_flush_enabled = true: rotate inline, drop flush_lock,
// then submit the stream phase to the coordinator. Gated on
// `pending_flush_count() < max_pending_flushes` so we don't
// stack up rotations beyond the configured pipeline depth.
// `try_acquire_permit` is non-blocking: if we lose the race
// for the last permit, we just skip this trigger (the next
// commit retries).
let mut flush_pending = false;
if self.should_flush() {
if self.config.async_flush_enabled
&& let Some(coord) = self.flush_coordinator.as_ref()
&& coord.pending_flush_count() < self.config.max_pending_flushes
{
match coord.try_acquire_permit() {
Some(permit) => {
let seq = coord.next_rotate_seq();
coord.note_pending();
match self.flush_l0_rotate().await {
Ok(rotate_out) => {
// Release flush_lock BEFORE the spawn so concurrent
// commits can proceed while the stream runs.
drop(_flush_lock_guard);
let parent_manifest = self.cached_manifest.lock().clone();
let rotated = crate::runtime::flush_coordinator::RotatedFlush {
seq,
old_l0_arc: rotate_out.old_l0_arc.clone(),
wal_lsn: rotate_out.wal_lsn,
current_version: rotate_out.current_version,
name: None,
parent_manifest,
permit,
flush_in_progress_guard: rotate_out.flush_in_progress_guard,
};
let writer = self.clone();
let _ticket = coord.submit_for_stream(
rotated,
move |old_l0, wal, ver, n| async move {
let outcome =
writer.flush_stream_l1(old_l0, wal, ver, n).await?;
Ok(crate::runtime::flush_coordinator::FlushOutcome {
new_manifest: outcome.manifest,
snapshot_id: outcome.snapshot_id,
})
},
);
flush_pending = true;
// Early return — flush_lock already dropped.
return Ok((wal_lsn, flush_pending));
}
Err(e) => {
tracing::warn!("Async rotate failed (non-critical): {}", e);
// permit drops here, freeing the slot
}
}
}
None => {
// Race: someone else grabbed the last permit. Skip;
// next commit will retry should_flush().
metrics::counter!("uni_flush_trigger_skipped_total").increment(1);
}
}
} else if let Err(e) = self.flush_inline_under_lock(None).await {
tracing::warn!("Post-commit flush check failed (non-critical): {}", e);
}
}
Ok((wal_lsn, flush_pending))
}
/// Flush the WAL buffer to durable storage.
///
/// Returns the LSN of the flushed segment, or `0` when no WAL is configured.
pub async fn flush_wal(&self) -> Result<u64> {
let l0 = self.l0_manager.get_current();
let wal = l0.read().wal.clone();
match wal {
Some(wal) => Ok(wal.flush().await?),
None => Ok(0),
}
}
/// Record property removals in the active L0 mutation stats.
///
/// Routes to the transaction L0 if provided, otherwise to the main L0.
pub fn track_properties_removed(&self, count: usize, tx_l0: Option<&Arc<RwLock<L0Buffer>>>) {
if count == 0 {
return;
}
let l0 = self.resolve_l0(tx_l0);
l0.write().mutation_stats.properties_removed += count;
}
/// Validates vertex constraints for the given properties.
/// In the new design, label is passed as a parameter since VID no longer embeds label.
async fn validate_vertex_constraints_for_label(
&self,
vid: Vid,
properties: &Properties,
label: &str,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
self.validate_vertex_constraints_for_label_impl(vid, properties, label, tx_l0, false)
.await
}
/// Partial-update sibling: validates only constraints touching keys
/// present in `properties` (the touched set). NOT NULL is checked
/// only for touched keys; multi-key UNIQUE / CHECK / EXISTS are
/// skipped when any referenced key is absent (the caller is
/// expected to have routed to the full-row path in that case via
/// `touched_needs_full_read`).
async fn validate_vertex_constraints_for_label_partial(
&self,
vid: Vid,
properties: &Properties,
label: &str,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
self.validate_vertex_constraints_for_label_impl(vid, properties, label, tx_l0, true)
.await
}
async fn validate_vertex_constraints_for_label_impl(
&self,
vid: Vid,
properties: &Properties,
label: &str,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
partial: bool,
) -> Result<()> {
let schema = self.schema_manager.schema();
{
// 1. Check NOT NULL constraints (from Property definitions).
// Under partial-update mode, skip properties NOT in
// `properties` — they retain their previous (already-
// validated) value.
if let Some(props_meta) = schema.properties.get(label) {
for (prop_name, meta) in props_meta {
if !meta.nullable {
let present = properties.get(prop_name);
if partial && present.is_none() {
continue;
}
if present.is_none_or(|v| v.is_null()) {
log::warn!(
"Constraint violation: Property '{}' cannot be null for label '{}'",
prop_name,
label
);
return Err(anyhow!(
"Constraint violation: Property '{}' cannot be null",
prop_name
));
}
}
}
}
// 2. Check Explicit Constraints (Unique, Check, etc.)
for constraint in &schema.constraints {
if !constraint.enabled {
continue;
}
match &constraint.target {
ConstraintTarget::Label(l) if l == label => {}
_ => continue,
}
match &constraint.constraint_type {
ConstraintType::Unique {
properties: unique_props,
} => {
// Support single and multi-property unique constraints
if !unique_props.is_empty() {
let mut key_values = Vec::new();
let mut missing = false;
for prop in unique_props {
if let Some(val) = properties.get(prop) {
key_values.push((prop.clone(), val.clone()));
} else {
missing = true; // Can't enforce if property missing (partial update?)
// For INSERT, missing means null?
// If property is nullable, unique constraint typically allows multiple nulls or ignores?
// For now, only check if ALL keys are present
}
}
if !missing {
self.check_unique_constraint_multi(label, &key_values, vid, tx_l0)
.await?;
}
}
}
ConstraintType::Exists { property } => {
if properties.get(property).is_none_or(|v| v.is_null()) {
log::warn!(
"Constraint violation: Property '{}' must exist for label '{}'",
property,
label
);
return Err(anyhow!(
"Constraint violation: Property '{}' must exist",
property
));
}
}
ConstraintType::Check { expression } => {
if !self.evaluate_check_constraint(expression, properties)? {
return Err(anyhow!(
"CHECK constraint '{}' violated: expression '{}' evaluated to false",
constraint.name,
expression
));
}
}
_ => {
return Err(anyhow!("Unsupported constraint type"));
}
}
}
}
Ok(())
}
/// Validates vertex constraints for a vertex with the given labels.
/// Labels must be passed explicitly since the vertex may not yet be in L0.
/// Unknown labels (not in schema) are skipped.
async fn validate_vertex_constraints(
&self,
vid: Vid,
properties: &Properties,
labels: &[String],
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let schema = self.schema_manager.schema();
// Validate constraints only for known labels
for label in labels {
// Skip unknown labels (schemaless support)
if schema.get_label_case_insensitive(label).is_none() {
continue;
}
self.validate_vertex_constraints_for_label(vid, properties, label, tx_l0)
.await?;
}
// Check global ext_id uniqueness if ext_id is provided
if let Some(ext_id) = properties.get("ext_id").and_then(|v| v.as_str()) {
self.check_extid_globally_unique(ext_id, vid, tx_l0).await?;
}
Ok(())
}
/// Partial sibling of `validate_vertex_constraints` — validates only
/// constraints touching keys present in `properties`. Used by
/// `insert_vertex_partial`'s fast path; the caller pre-screens for
/// multi-key UNIQUE constraints via `touched_needs_full_read`.
async fn validate_vertex_constraints_partial(
&self,
vid: Vid,
touched: &Properties,
labels: &[String],
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let schema = self.schema_manager.schema();
for label in labels {
if schema.get_label_case_insensitive(label).is_none() {
continue;
}
self.validate_vertex_constraints_for_label_partial(vid, touched, label, tx_l0)
.await?;
}
if let Some(ext_id) = touched.get("ext_id").and_then(|v| v.as_str()) {
self.check_extid_globally_unique(ext_id, vid, tx_l0).await?;
}
Ok(())
}
/// Collect ext_ids and unique constraint keys from an iterator of vertex properties.
///
/// Used to build a constraint key index from L0 buffers for batch validation.
fn collect_constraint_keys_from_properties<'a>(
properties_iter: impl Iterator<Item = &'a Properties>,
label: &str,
constraints: &[uni_common::core::schema::Constraint],
existing_keys: &mut HashMap<String, HashSet<String>>,
existing_extids: &mut HashSet<String>,
) {
for props in properties_iter {
if let Some(ext_id) = props.get("ext_id").and_then(|v| v.as_str()) {
existing_extids.insert(ext_id.to_string());
}
for constraint in constraints {
if !constraint.enabled {
continue;
}
if let ConstraintTarget::Label(l) = &constraint.target {
if l != label {
continue;
}
} else {
continue;
}
if let ConstraintType::Unique {
properties: unique_props,
} = &constraint.constraint_type
{
let mut key_parts = Vec::new();
let mut all_present = true;
for prop in unique_props {
if let Some(val) = props.get(prop) {
key_parts.push(format!("{}:{}", prop, val));
} else {
all_present = false;
break;
}
}
if all_present {
let key = key_parts.join("|");
existing_keys
.entry(constraint.name.clone())
.or_default()
.insert(key);
}
}
}
}
}
/// Validates constraints for a batch of vertices efficiently.
///
/// This method builds an in-memory index from L0 buffers ONCE instead of scanning
/// per vertex, reducing complexity from O(n²) to O(n) for bulk inserts.
///
/// # Arguments
/// * `vids` - VIDs of vertices being inserted
/// * `properties_batch` - Properties for each vertex
/// * `label` - Label for all vertices (assumes single label for now)
///
/// # Performance
/// For N vertices with unique constraints:
/// - Old approach: O(N²) - scan L0 buffer N times
/// - New approach: O(N) - scan L0 buffer once, build HashSet, check each vertex in O(1)
async fn validate_vertex_batch_constraints(
&self,
vids: &[Vid],
properties_batch: &[Properties],
label: &str,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
if vids.len() != properties_batch.len() {
return Err(anyhow!("VID/properties length mismatch"));
}
let schema = self.schema_manager.schema();
// 1. Validate NOT NULL constraints for each vertex
if let Some(props_meta) = schema.properties.get(label) {
for (idx, properties) in properties_batch.iter().enumerate() {
for (prop_name, meta) in props_meta {
if !meta.nullable && properties.get(prop_name).is_none_or(|v| v.is_null()) {
return Err(anyhow!(
"Constraint violation at index {}: Property '{}' cannot be null",
idx,
prop_name
));
}
}
}
}
// 2. Build constraint key index from L0 buffers (ONCE for entire batch)
let mut existing_keys: HashMap<String, HashSet<String>> = HashMap::new();
let mut existing_extids: HashSet<String> = HashSet::new();
// Scan current L0 buffer
{
let l0 = self.l0_manager.get_current();
let l0_guard = l0.read();
Self::collect_constraint_keys_from_properties(
l0_guard.vertex_properties.values(),
label,
&schema.constraints,
&mut existing_keys,
&mut existing_extids,
);
}
// Scan transaction L0 if present
if let Some(tx_l0) = tx_l0 {
let tx_l0_guard = tx_l0.read();
Self::collect_constraint_keys_from_properties(
tx_l0_guard.vertex_properties.values(),
label,
&schema.constraints,
&mut existing_keys,
&mut existing_extids,
);
}
// 3. Check batch vertices against index AND check for duplicates within batch
let mut batch_keys: HashMap<String, HashMap<String, usize>> = HashMap::new();
let mut batch_extids: HashMap<String, usize> = HashMap::new();
for (idx, (_vid, properties)) in vids.iter().zip(properties_batch.iter()).enumerate() {
// Check ext_id uniqueness
if let Some(ext_id) = properties.get("ext_id").and_then(|v| v.as_str()) {
if existing_extids.contains(ext_id) {
return Err(anyhow!(
"Constraint violation at index {}: ext_id '{}' already exists",
idx,
ext_id
));
}
if let Some(first_idx) = batch_extids.get(ext_id) {
return Err(anyhow!(
"Constraint violation: ext_id '{}' duplicated in batch at indices {} and {}",
ext_id,
first_idx,
idx
));
}
batch_extids.insert(ext_id.to_string(), idx);
}
// Check unique constraints
for constraint in &schema.constraints {
if !constraint.enabled {
continue;
}
if let ConstraintTarget::Label(l) = &constraint.target {
if l != label {
continue;
}
} else {
continue;
}
match &constraint.constraint_type {
ConstraintType::Unique {
properties: unique_props,
} => {
let mut key_parts = Vec::new();
let mut all_present = true;
for prop in unique_props {
if let Some(val) = properties.get(prop) {
key_parts.push(format!("{}:{}", prop, val));
} else {
all_present = false;
break;
}
}
if all_present {
let key = key_parts.join("|");
// Check against existing L0 keys
if let Some(keys) = existing_keys.get(&constraint.name)
&& keys.contains(&key)
{
return Err(anyhow!(
"Constraint violation at index {}: Duplicate composite key for label '{}' (constraint '{}')",
idx,
label,
constraint.name
));
}
// Check for duplicates within batch
let batch_constraint_keys =
batch_keys.entry(constraint.name.clone()).or_default();
if let Some(first_idx) = batch_constraint_keys.get(&key) {
return Err(anyhow!(
"Constraint violation: Duplicate key '{}' in batch at indices {} and {}",
key,
first_idx,
idx
));
}
batch_constraint_keys.insert(key, idx);
}
}
ConstraintType::Exists { property }
if properties.get(property).is_none_or(|v| v.is_null()) =>
{
return Err(anyhow!(
"Constraint violation at index {}: Property '{}' must exist",
idx,
property
));
}
ConstraintType::Check { expression }
if !self.evaluate_check_constraint(expression, properties)? =>
{
return Err(anyhow!(
"Constraint violation at index {}: CHECK constraint '{}' violated",
idx,
constraint.name
));
}
_ => {}
}
}
}
// 4. Check storage for unique constraints (can batch this into a single query)
for constraint in &schema.constraints {
if !constraint.enabled {
continue;
}
if let ConstraintTarget::Label(l) = &constraint.target {
if l != label {
continue;
}
} else {
continue;
}
if let ConstraintType::Unique {
properties: unique_props,
} = &constraint.constraint_type
{
// Build compound OR filter for all batch vertices
let mut or_filters = Vec::new();
for properties in properties_batch.iter() {
let mut and_parts = Vec::new();
let mut all_present = true;
for prop in unique_props {
if let Some(val) = properties.get(prop) {
let val_str = match val {
Value::String(s) => format!("'{}'", s.replace('\'', "''")),
Value::Int(n) => n.to_string(),
Value::Float(f) => f.to_string(),
Value::Bool(b) => b.to_string(),
_ => {
all_present = false;
break;
}
};
and_parts.push(format!("{} = {}", prop, val_str));
} else {
all_present = false;
break;
}
}
if all_present {
or_filters.push(format!("({})", and_parts.join(" AND ")));
}
}
#[cfg(feature = "lance-backend")]
if !or_filters.is_empty() {
let vid_list: Vec<String> =
vids.iter().map(|v| v.as_u64().to_string()).collect();
let filter = format!(
"({}) AND _deleted = false AND _vid NOT IN ({})",
or_filters.join(" OR "),
vid_list.join(", ")
);
if let Ok(ds) = self.storage.vertex_dataset(label)
&& let Ok(lance_ds) = ds.open_raw().await
{
let count = lance_ds.count_rows(Some(filter.clone())).await?;
if count > 0 {
return Err(anyhow!(
"Constraint violation: Duplicate composite key for label '{}' in storage (constraint '{}')",
label,
constraint.name
));
}
}
}
}
}
Ok(())
}
/// Checks that ext_id is globally unique across all vertices.
///
/// Searches L0 buffers (current, transaction, pending) and the main vertices table
/// to ensure no other vertex uses this ext_id.
///
/// # Errors
///
/// Returns error if another vertex with the same ext_id exists.
async fn check_extid_globally_unique(
&self,
ext_id: &str,
current_vid: Vid,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
// Check L0 buffers: current, transaction, and pending flush
let l0_buffers_to_check: Vec<Arc<RwLock<L0Buffer>>> = {
let mut buffers = vec![self.l0_manager.get_current()];
if let Some(tx_l0) = tx_l0 {
buffers.push(tx_l0.clone());
}
buffers.extend(self.l0_manager.get_pending_flush());
buffers
};
for l0 in &l0_buffers_to_check {
if let Some(vid) =
Self::find_extid_in_properties(&l0.read().vertex_properties, ext_id, current_vid)
{
return Err(anyhow!(
"Constraint violation: ext_id '{}' already exists (vertex {:?})",
ext_id,
vid
));
}
}
// Check main vertices table (if it exists)
// Pass None for global uniqueness check (not snapshot-isolated)
let backend = self.storage.backend();
if let Ok(Some(found_vid)) = MainVertexDataset::find_by_ext_id(backend, ext_id, None).await
&& found_vid != current_vid
{
return Err(anyhow!(
"Constraint violation: ext_id '{}' already exists (vertex {:?})",
ext_id,
found_vid
));
}
Ok(())
}
/// Search vertex properties for a duplicate ext_id, excluding `current_vid`.
fn find_extid_in_properties(
vertex_properties: &HashMap<Vid, Properties>,
ext_id: &str,
current_vid: Vid,
) -> Option<Vid> {
vertex_properties.iter().find_map(|(&vid, props)| {
if vid != current_vid && props.get("ext_id").and_then(|v| v.as_str()) == Some(ext_id) {
Some(vid)
} else {
None
}
})
}
/// Helper to get vertex labels from L0 buffer.
fn get_vertex_labels_from_l0(&self, vid: Vid) -> Option<Vec<String>> {
let l0 = self.l0_manager.get_current();
let l0_guard = l0.read();
// Check if vertex is tombstoned (deleted) - if so, return None
if l0_guard.vertex_tombstones.contains(&vid) {
return None;
}
l0_guard.get_vertex_labels(vid).map(|l| l.to_vec())
}
/// Get vertex labels from all sources: current L0, pending L0s, and storage.
/// This is the proper way to read vertex labels after a flush, as it checks both
/// in-memory buffers and persisted storage.
pub async fn get_vertex_labels(
&self,
vid: Vid,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Option<Vec<String>> {
// 1. Check current L0
if let Some(labels) = self.get_vertex_labels_from_l0(vid) {
return Some(labels);
}
// 2. Check transaction L0 if present
if let Some(tx_l0) = tx_l0 {
let guard = tx_l0.read();
if guard.vertex_tombstones.contains(&vid) {
return None;
}
if let Some(labels) = guard.get_vertex_labels(vid) {
return Some(labels.to_vec());
}
}
// 3. Check pending flush L0s
for pending_l0 in self.l0_manager.get_pending_flush() {
let guard = pending_l0.read();
if guard.vertex_tombstones.contains(&vid) {
return None;
}
if let Some(labels) = guard.get_vertex_labels(vid) {
return Some(labels.to_vec());
}
}
// 4. Check storage
self.find_vertex_labels_in_storage(vid).await.ok().flatten()
}
/// Helper to get edge type from L0 buffer.
fn get_edge_type_from_l0(&self, eid: Eid) -> Option<String> {
let l0 = self.l0_manager.get_current();
let l0_guard = l0.read();
l0_guard.get_edge_type(eid).map(|s| s.to_string())
}
/// Look up the edge type ID (u32) for an EID from the L0 buffer's edge endpoints.
/// Falls back to the transaction L0 if available.
pub fn get_edge_type_id_from_l0(
&self,
eid: Eid,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Option<u32> {
// Check transaction L0 first
if let Some(tx_l0) = tx_l0 {
let guard = tx_l0.read();
if let Some((_, _, etype)) = guard.get_edge_endpoint_full(eid) {
return Some(etype);
}
}
// Fall back to main L0
let l0 = self.l0_manager.get_current();
let l0_guard = l0.read();
l0_guard
.get_edge_endpoint_full(eid)
.map(|(_, _, etype)| etype)
}
/// Set the type name for an edge (used for schemaless edge types).
/// This is called during CREATE for edge types not found in the schema.
pub fn set_edge_type(
&self,
eid: Eid,
type_name: String,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) {
self.resolve_l0(tx_l0).write().set_edge_type(eid, type_name);
}
/// Evaluate a simple CHECK constraint expression.
/// Supports: "property op value" (e.g., "age > 18", "status = 'active'")
fn evaluate_check_constraint(&self, expression: &str, properties: &Properties) -> Result<bool> {
let parts: Vec<&str> = expression.split_whitespace().collect();
if parts.len() != 3 {
// For now, only support "prop op val"
// Fallback to true if too complex to avoid breaking, but warn
log::warn!(
"Complex CHECK constraint expression '{}' not fully supported yet; allowing write.",
expression
);
return Ok(true);
}
let prop_part = parts[0].trim_start_matches('(');
// Handle "variable.property" format - take the part after the dot
let prop_name = if let Some(idx) = prop_part.find('.') {
&prop_part[idx + 1..]
} else {
prop_part
};
let op = parts[1];
let val_str = parts[2].trim_end_matches(')');
let prop_val = match properties.get(prop_name) {
Some(v) => v,
None => return Ok(true), // If property missing, CHECK usually passes (unless NOT NULL)
};
// Parse value string (handle quotes for strings)
let target_val = if (val_str.starts_with('\'') && val_str.ends_with('\''))
|| (val_str.starts_with('"') && val_str.ends_with('"'))
{
Value::String(val_str[1..val_str.len() - 1].to_string())
} else if let Ok(n) = val_str.parse::<i64>() {
Value::Int(n)
} else if let Ok(n) = val_str.parse::<f64>() {
Value::Float(n)
} else if let Ok(b) = val_str.parse::<bool>() {
Value::Bool(b)
} else {
// Check for internal format wrappers if they somehow leaked through
if val_str.starts_with("Number(") && val_str.ends_with(')') {
let n_str = &val_str[7..val_str.len() - 1];
if let Ok(n) = n_str.parse::<i64>() {
Value::Int(n)
} else if let Ok(n) = n_str.parse::<f64>() {
Value::Float(n)
} else {
Value::String(val_str.to_string())
}
} else {
Value::String(val_str.to_string())
}
};
match op {
"=" | "==" => Ok(prop_val == &target_val),
"!=" | "<>" => Ok(prop_val != &target_val),
">" => self
.compare_values(prop_val, &target_val)
.map(|o| o.is_gt()),
"<" => self
.compare_values(prop_val, &target_val)
.map(|o| o.is_lt()),
">=" => self
.compare_values(prop_val, &target_val)
.map(|o| o.is_ge()),
"<=" => self
.compare_values(prop_val, &target_val)
.map(|o| o.is_le()),
_ => {
log::warn!("Unsupported operator '{}' in CHECK constraint", op);
Ok(true)
}
}
}
fn compare_values(&self, a: &Value, b: &Value) -> Result<std::cmp::Ordering> {
use std::cmp::Ordering;
fn cmp_f64(x: f64, y: f64) -> Ordering {
x.partial_cmp(&y).unwrap_or(Ordering::Equal)
}
match (a, b) {
(Value::Int(n1), Value::Int(n2)) => Ok(n1.cmp(n2)),
(Value::Float(f1), Value::Float(f2)) => Ok(cmp_f64(*f1, *f2)),
(Value::Int(n), Value::Float(f)) => Ok(cmp_f64(*n as f64, *f)),
(Value::Float(f), Value::Int(n)) => Ok(cmp_f64(*f, *n as f64)),
(Value::String(s1), Value::String(s2)) => Ok(s1.cmp(s2)),
_ => Err(anyhow!(
"Cannot compare incompatible types: {:?} vs {:?}",
a,
b
)),
}
}
async fn check_unique_constraint_multi(
&self,
label: &str,
key_values: &[(String, Value)],
current_vid: Vid,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
// Serialize constraint key once for O(1) lookups
let key = serialize_constraint_key(label, key_values);
// 1. Check L0 (in-memory) using O(1) constraint index
{
let l0 = self.l0_manager.get_current();
let l0_guard = l0.read();
if l0_guard.has_constraint_key(&key, current_vid) {
return Err(anyhow!(
"Constraint violation: Duplicate composite key for label '{}'",
label
));
}
}
// Check Transaction L0
if let Some(tx_l0) = tx_l0 {
let tx_l0_guard = tx_l0.read();
if tx_l0_guard.has_constraint_key(&key, current_vid) {
return Err(anyhow!(
"Constraint violation: Duplicate composite key for label '{}' (in tx)",
label
));
}
}
// 2. Check Storage (L1/L2)
let filters: Vec<String> = key_values
.iter()
.map(|(prop, val)| {
let val_str = match val {
Value::String(s) => format!("'{}'", s.replace('\'', "''")),
Value::Int(n) => n.to_string(),
Value::Float(f) => f.to_string(),
Value::Bool(b) => b.to_string(),
_ => "NULL".to_string(),
};
format!("{} = {}", prop, val_str)
})
.collect();
let mut filter = filters.join(" AND ");
filter.push_str(&format!(
" AND _deleted = false AND _vid != {}",
current_vid.as_u64()
));
#[cfg(feature = "lance-backend")]
if let Ok(ds) = self.storage.vertex_dataset(label)
&& let Ok(lance_ds) = ds.open_raw().await
{
let count = lance_ds.count_rows(Some(filter.clone())).await?;
if count > 0 {
return Err(anyhow!(
"Constraint violation: Duplicate composite key for label '{}' (in storage). Filter: {}",
label,
filter
));
}
}
Ok(())
}
async fn check_write_pressure(&self) -> Result<()> {
let status = self
.storage
.compaction_status()
.map_err(|e| anyhow::anyhow!("Failed to get compaction status: {}", e))?;
let l1_runs = status.l1_runs;
let throttle = &self.config.throttle;
if l1_runs >= throttle.hard_limit {
log::warn!("Write stalled: L1 runs ({}) at hard limit", l1_runs);
// Simple polling for now
while self
.storage
.compaction_status()
.map_err(|e| anyhow::anyhow!("Failed to get compaction status: {}", e))?
.l1_runs
>= throttle.hard_limit
{
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
} else if l1_runs >= throttle.soft_limit {
let excess = l1_runs - throttle.soft_limit;
// Cap multiplier to avoid overflow
let excess = std::cmp::min(excess, 31);
let multiplier = 2_u32.pow(excess as u32);
let delay = throttle.base_delay * multiplier;
tokio::time::sleep(delay).await;
}
Ok(())
}
/// Check transaction memory limit to prevent OOM.
/// No-op when no transaction is active.
fn check_transaction_memory(&self, tx_l0: Option<&Arc<RwLock<L0Buffer>>>) -> Result<()> {
if let Some(tx_l0) = tx_l0 {
let size = tx_l0.read().estimated_size;
if size > self.config.max_transaction_memory {
return Err(anyhow!(
"Transaction memory limit exceeded: {} bytes used, limit is {} bytes. \
Roll back or commit the current transaction.",
size,
self.config.max_transaction_memory
));
}
}
Ok(())
}
async fn get_query_context(
&self,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Option<QueryContext> {
Some(QueryContext::new_with_pending(
self.l0_manager.get_current(),
tx_l0.cloned(),
self.l0_manager.get_pending_flush(),
))
}
/// Layer-1 CRDT variant enforcement, shared by the single-vertex and batch
/// write paths.
///
/// Rejects a declared CRDT property written as a parsed CRDT value
/// (`Value::Map`) whose variant differs from the schema's declared variant.
/// A mismatch would make the commit-time merge silently overwrite instead of
/// merge, and the OCC CRDT carve-out (`occ::crdt_carveout_overwrite` /
/// `WriteSet::from_l0`) would hide it as a lost update — so it must be caught
/// at write time, on *every* write path. `try_as_crdt` is `Map`-gated, so the
/// JSON-string (Cypher) form and non-CRDT values pass through untouched: they
/// are never carved out and stay conflictable.
fn enforce_crdt_variants(
props_meta: &std::collections::HashMap<String, uni_common::core::schema::PropertyMeta>,
properties: &Properties,
) -> Result<()> {
for (key, value) in properties {
let Some(meta) = props_meta.get(key) else {
continue;
};
let uni_common::core::schema::DataType::Crdt(expected) = &meta.r#type else {
continue;
};
if let Some(crdt) = crate::runtime::l0::try_as_crdt(value)
&& crdt.type_name() != expected.type_name()
{
return Err(anyhow::Error::new(uni_common::UniError::Constraint {
message: format!(
"CRDT property '{key}' must be written as a {} value",
expected.type_name()
),
}));
}
}
Ok(())
}
/// Prepare a vertex for upsert by merging CRDT properties with existing values.
///
/// When `label` is provided, uses it directly to look up property metadata.
/// Otherwise falls back to discovering the label from L0 buffers and storage.
///
/// # Errors
///
/// Returns an error if CRDT property merging fails.
async fn prepare_vertex_upsert(
&self,
vid: Vid,
properties: &mut Properties,
label: Option<&str>,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let Some(pm) = &self.property_manager else {
return Ok(());
};
let schema = self.schema_manager.schema();
// Resolve label: use provided label or discover from L0/storage
let discovered_labels;
let label_name = if let Some(l) = label {
Some(l)
} else {
discovered_labels = self.get_vertex_labels(vid, tx_l0).await;
discovered_labels
.as_ref()
.and_then(|l| l.first().map(|s| s.as_str()))
};
let Some(label_str) = label_name else {
return Ok(());
};
let Some(props_meta) = schema.properties.get(label_str) else {
return Ok(());
};
// Identify CRDT properties in the insert data
let crdt_keys: Vec<String> = properties
.keys()
.filter(|key| {
props_meta.get(*key).is_some_and(|meta| {
matches!(meta.r#type, uni_common::core::schema::DataType::Crdt(_))
})
})
.cloned()
.collect();
if crdt_keys.is_empty() {
return Ok(());
}
// Enforce that each declared CRDT property written as a parsed CRDT value
// (`Value::Map`) carries its declared variant. A mismatched variant makes
// `merge_crdt_properties` overwrite rather than merge at commit, and the
// OCC carve-out (`occ::crdt_carveout_overwrite` / `WriteSet::from_l0`)
// would hide that as a silent lost update — reject it at the source.
//
// Only the `Map` form is checked: it is exactly the form the carve-out
// applies to (`try_as_crdt` is `Map`-gated). A CRDT written as a JSON
// string (the Cypher form) or a non-CRDT value is never carved out — it
// stays conflictable — so it poses no carve-out soundness risk and is left
// to the existing merge/parse path. This is the declared-property half of
// the layered fix; the commit-time check covers undeclared CRDT-shaped values.
Self::enforce_crdt_variants(props_meta, properties)?;
let ctx = self.get_query_context(tx_l0).await;
for key in crdt_keys {
let existing = pm.get_vertex_prop_with_ctx(vid, &key, ctx.as_ref()).await?;
if !existing.is_null()
&& let Some(val) = properties.get_mut(&key)
{
*val = pm.merge_crdt_values(&existing, val)?;
}
}
Ok(())
}
async fn prepare_edge_upsert(
&self,
eid: Eid,
properties: &mut Properties,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
if let Some(pm) = &self.property_manager {
let schema = self.schema_manager.schema();
// Get edge type from L0 buffer instead of from EID
let type_name = self.get_edge_type_from_l0(eid);
if let Some(ref t_name) = type_name
&& let Some(props_meta) = schema.properties.get(t_name)
{
let mut crdt_keys = Vec::new();
for (key, _) in properties.iter() {
if let Some(meta) = props_meta.get(key)
&& matches!(meta.r#type, uni_common::core::schema::DataType::Crdt(_))
{
crdt_keys.push(key.clone());
}
}
if !crdt_keys.is_empty() {
let ctx = self.get_query_context(tx_l0).await;
for key in crdt_keys {
let existing = pm.get_edge_prop(eid, &key, ctx.as_ref()).await?;
if !existing.is_null()
&& let Some(val) = properties.get_mut(&key)
{
*val = pm.merge_crdt_values(&existing, val)?;
}
}
}
}
}
Ok(())
}
#[instrument(skip(self, properties), level = "trace")]
pub async fn insert_vertex(
&self,
vid: Vid,
properties: Properties,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
self.insert_vertex_with_labels(vid, properties, &[], tx_l0)
.await?;
Ok(())
}
/// Component C1 (G4): before a non-transactional mutation merges into main
/// L0, if an outstanding snapshot pins the current generation, freeze it
/// aside so snapshots taken *before* this write stay isolated from it.
///
/// `flush_lock` (acquired and released here) serializes the freeze against
/// concurrent commit-time freezes/merges, matching the atomicity the tx
/// commit path gets. No-op for transactional writes (their freeze happens at
/// commit) and — the common case — when nothing is pinned, where it costs one
/// atomic load. Freezes at most once per pinned generation: the freeze
/// installs a fresh unpinned `current`, so later writes in the same bulk
/// import see no pin and merge in place, and the snapshot keeps reading the
/// frozen pre-import buffer.
async fn freeze_for_non_tx_write_if_pinned(&self, tx_l0: Option<&Arc<RwLock<L0Buffer>>>) {
// Self-gates on the runtime SSI toggle: nothing pins a snapshot unless a
// transaction began under `ssi_enabled`, so `is_current_pinned()` is
// always false (one atomic load) when SSI is off.
if tx_l0.is_none() && self.l0_manager.is_current_pinned() {
let _flush_lock_guard = self.flush_lock.lock().await;
// Re-check under the lock: a concurrent commit may have frozen first.
if self.l0_manager.is_current_pinned() {
self.l0_manager.freeze_current_for_snapshot();
metrics::counter!("uni_l0_snapshot_freezes_total").increment(1);
}
}
}
#[instrument(skip(self, properties, labels), level = "trace")]
pub async fn insert_vertex_with_labels(
&self,
vid: Vid,
mut properties: Properties,
labels: &[String],
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<Properties> {
let start = std::time::Instant::now();
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
// Component C1 (G4): a non-transactional write (`tx_l0 == None`, e.g. bulk
// import / LOAD CSV) mutates main L0 directly, outside the commit-time
// snapshot freeze. Freeze the pinned generation aside first so snapshots
// taken before this write stay isolated from it.
self.freeze_for_non_tx_write_if_pinned(tx_l0).await;
if !self.try_defer_embedding(labels, &properties, vid, tx_l0) {
self.process_embeddings_for_labels(labels, &mut properties)
.await?;
}
self.validate_vertex_constraints(vid, &properties, labels, tx_l0)
.await?;
self.prepare_vertex_upsert(
vid,
&mut properties,
labels.first().map(|s| s.as_str()),
tx_l0,
)
.await?;
// Clone properties and labels before moving into L0 to return them and populate constraint index
let properties_copy = properties.clone();
let labels_copy = labels.to_vec();
{
let l0 = self.resolve_l0(tx_l0);
let mut l0_guard = l0.write();
l0_guard.insert_vertex_with_labels(vid, properties, labels);
// Populate constraint index for O(1) duplicate detection
let schema = self.schema_manager.schema();
for label in &labels_copy {
if schema.get_label_case_insensitive(label).is_none() {
if self.config.strict_schema {
return Err(anyhow::anyhow!(
"Label '{}' is not defined in the schema \
(strict_schema is enabled).",
label
));
}
continue; // Schemaless: skip unknown labels.
}
// For each unique constraint on this label, insert into constraint index
for constraint in &schema.constraints {
if !constraint.enabled {
continue;
}
if let ConstraintTarget::Label(l) = &constraint.target {
if l != label {
continue;
}
} else {
continue;
}
if let ConstraintType::Unique {
properties: unique_props,
} = &constraint.constraint_type
{
let mut key_values = Vec::new();
let mut all_present = true;
for prop in unique_props {
if let Some(val) = properties_copy.get(prop) {
key_values.push((prop.clone(), val.clone()));
} else {
all_present = false;
break;
}
}
if all_present {
let key = serialize_constraint_key(label, &key_values);
l0_guard.insert_constraint_key(key, vid);
}
}
}
}
}
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
if start.elapsed().as_millis() > 100 {
log::warn!("Slow insert_vertex: {}ms", start.elapsed().as_millis());
}
Ok(properties_copy)
}
/// True iff routing this partial write through MergeInsert would
/// miss a constraint check. Specifically: a multi-key UNIQUE
/// constraint where the touched-set doesn't cover all member keys
/// requires the unchanged keys from the existing row to compute
/// the composite. Conservative: also returns true if any touched
/// key is `ext_id` (uniqueness checked globally — handled in the
/// full-row path).
fn touched_needs_full_read(&self, touched: &Properties, labels: &[String]) -> bool {
if touched.contains_key("ext_id") {
return true;
}
let schema = self.schema_manager.schema();
for label in labels {
if schema.get_label_case_insensitive(label).is_none() {
continue;
}
for constraint in &schema.constraints {
if !constraint.enabled {
continue;
}
if let ConstraintTarget::Label(l) = &constraint.target {
if !l.eq_ignore_ascii_case(label) {
continue;
}
} else {
continue;
}
if let ConstraintType::Unique {
properties: unique_props,
} = &constraint.constraint_type
{
if unique_props.len() < 2 {
continue; // single-key UNIQUE — partial path sees the key
}
if unique_props.iter().any(|p| touched.contains_key(p)) {
return true;
}
}
}
}
false
}
/// Insert a vertex's FULL property row plus a touched-keys hint so
/// the flush emits ONLY those columns via Lance MergeInsert.
///
/// Caller must have read the full row (via PropertyManager) and
/// applied SET-touched values on top before calling — same input
/// shape as `insert_vertex_with_labels`. The new arg `touched_keys`
/// is the set of property keys this SET statement actually
/// assigned; L0 records it in `vertex_partial_keys[vid]` and the
/// flush filters the MergeInsert source schema down to those keys.
/// When `UniConfig::partial_lance_writes == false`, falls through
/// to `insert_vertex_with_labels` (Append) — preserving bit-for-bit
/// equivalence with prior releases.
#[instrument(skip(self, props, touched_keys, labels), level = "trace")]
pub async fn insert_vertex_partial_full(
&self,
vid: Vid,
mut props: Properties,
touched_keys: HashSet<String>,
labels: &[String],
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
if !self.config.partial_lance_writes
|| self.touched_needs_full_read(&props_subset(&props, &touched_keys), labels)
{
self.insert_vertex_with_labels(vid, props, labels, tx_l0)
.await?;
return Ok(());
}
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
if !self.try_defer_embedding(labels, &props, vid, tx_l0) {
self.process_embeddings_for_labels(labels, &mut props)
.await?;
}
// Full-row validation runs because we have the complete map;
// no need for the partial-only validator.
self.validate_vertex_constraints(vid, &props, labels, tx_l0)
.await?;
{
let l0 = self.resolve_l0(tx_l0);
let mut l0_guard = l0.write();
l0_guard.insert_vertex_partial_full(vid, props, touched_keys, labels);
}
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
metrics::counter!("uni_partial_writes_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
Ok(())
}
/// Insert a vertex's *partial* property set without first reading the
/// full row.
///
/// When `WriterConfig::partial_lance_writes` is `true`, the touched
/// keys flow into `L0Buffer::vertex_partial_keys` so the next flush
/// emits them via Lance `MergeInsertBuilder` against a subset-of-
/// schema source — preserving untouched columns (e.g., embeddings)
/// byte-equal in Lance with no read at the caller and no write of
/// those columns.
///
/// When the flag is `false`, this falls back to the existing
/// `insert_vertex_with_labels` path after merging `touched` with
/// the current properties from L0/storage. The caller can therefore
/// use this entry point unconditionally; the optimization activates
/// only when the flag is on.
#[instrument(skip(self, touched, labels), level = "trace")]
pub async fn insert_vertex_partial(
&self,
vid: Vid,
touched: Properties,
labels: &[String],
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let needs_full_read =
!self.config.partial_lance_writes || self.touched_needs_full_read(&touched, labels);
if needs_full_read {
// Flag-off fallback (or constraint-driven fallback): merge
// `touched` with the current full property snapshot from
// L0/storage and route through the existing path. Preserves
// bit-for-bit equivalence with the pre-Round-11 release.
let existing = if let Some(pm) = &self.property_manager {
pm.get_all_vertex_props_with_ctx(vid, None)
.await
.unwrap_or_default()
.unwrap_or_default()
} else {
Properties::new()
};
let mut merged = existing;
for (k, v) in touched {
merged.insert(k, v);
}
self.insert_vertex_with_labels(vid, merged, labels, tx_l0)
.await?;
return Ok(());
}
// Flag-on fast path: stage the partial update directly. Pressure
// checks, embedding generation, constraint validation all still
// run — but the validator is the partial-aware variant that
// skips NOT NULL / multi-key UNIQUE / CHECK / EXISTS for
// properties not present in `touched`. Multi-key UNIQUE that
// overlaps the touched set forces a fallback above via
// `touched_needs_full_read`.
let mut touched = touched;
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
if !self.try_defer_embedding(labels, &touched, vid, tx_l0) {
self.process_embeddings_for_labels(labels, &mut touched)
.await?;
}
self.validate_vertex_constraints_partial(vid, &touched, labels, tx_l0)
.await?;
{
let l0 = self.resolve_l0(tx_l0);
let mut l0_guard = l0.write();
l0_guard.insert_vertex_partial(vid, touched, labels);
}
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
metrics::counter!("uni_partial_writes_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
Ok(())
}
/// Insert multiple vertices with batched operations.
///
/// This method uses batched operations to achieve O(N) complexity instead of O(N²)
/// for bulk inserts with unique constraints.
///
/// # Performance Improvements
/// - Batch VID allocation: 1 call instead of N calls
/// - Batch constraint validation: O(N) instead of O(N²)
/// - Batch embedding generation: 1 API call per config instead of N calls
/// - Transaction wrapping: Automatic flush deferral, atomicity
///
/// # Arguments
/// * `vids` - Pre-allocated VIDs for the vertices
/// * `properties_batch` - Properties for each vertex
/// * `labels` - Labels for all vertices (assumes single label for simplicity)
///
/// # Errors
/// Returns error if:
/// - VID/properties length mismatch
/// - Constraint violation detected
/// - Embedding generation fails
/// - Transaction commit fails
///
/// # Atomicity
/// If this method fails, all changes are rolled back (if transaction was started here).
pub async fn insert_vertices_batch(
&self,
vids: Vec<Vid>,
mut properties_batch: Vec<Properties>,
labels: Vec<String>,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<Vec<Properties>> {
let start = std::time::Instant::now();
// Validate inputs
if vids.len() != properties_batch.len() {
return Err(anyhow!(
"VID/properties size mismatch: {} vids, {} properties",
vids.len(),
properties_batch.len()
));
}
if vids.is_empty() {
return Ok(Vec::new());
}
// Batch operations — writes go directly to the resolved L0.
// Atomicity is guaranteed by the caller holding the writer lock.
let result = async {
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
// Component C1 (G4): batch bulk-import is the canonical non-tx write —
// freeze the pinned generation aside before merging so snapshot
// readers stay isolated. No-op when unpinned or transactional.
self.freeze_for_non_tx_write_if_pinned(tx_l0).await;
// Batch embedding generation (1 API call per config)
self.process_embeddings_for_batch(&labels, &mut properties_batch)
.await?;
// Batch constraint validation (O(N) instead of O(N²))
let label = labels
.first()
.ok_or_else(|| anyhow!("No labels provided"))?;
self.validate_vertex_batch_constraints(&vids, &properties_batch, label, tx_l0)
.await?;
// Batch prepare (CRDT merging if needed)
// Check schema once: skip entirely if no CRDT properties for this label.
// For new vertices (freshly allocated VIDs), there are no existing CRDT
// values to merge, so the per-vertex lookup is unnecessary in that case.
let has_crdt_fields = {
let schema = self.schema_manager.schema();
schema
.properties
.get(label.as_str())
.is_some_and(|props_meta| {
props_meta.values().any(|meta| {
matches!(meta.r#type, uni_common::core::schema::DataType::Crdt(_))
})
})
};
if has_crdt_fields {
// Layer-1 variant enforcement (G3): the batch path must reject a
// declared-CRDT variant mismatch exactly as the single-vertex
// `prepare_vertex_upsert` does. Without this, a wrong-variant CRDT
// written via batch import slips past write-time validation and
// the OCC carve-out then masks the overwrite as a lost update.
{
let schema = self.schema_manager.schema();
if let Some(props_meta) = schema.properties.get(label.as_str()) {
for props in &properties_batch {
Self::enforce_crdt_variants(props_meta, props)?;
}
}
}
// Batch fetch existing CRDT values: collect VIDs that need merging,
// then query once via PropertyManager instead of per-vertex lookups.
let schema = self.schema_manager.schema();
let crdt_keys: Vec<String> = schema
.properties
.get(label.as_str())
.map(|props_meta| {
props_meta
.iter()
.filter(|(_, meta)| {
matches!(meta.r#type, uni_common::core::schema::DataType::Crdt(_))
})
.map(|(key, _)| key.clone())
.collect()
})
.unwrap_or_default();
if let Some(pm) = &self.property_manager {
let ctx = self.get_query_context(tx_l0).await;
for (vid, props) in vids.iter().zip(&mut properties_batch) {
for key in &crdt_keys {
if props.contains_key(key) {
let existing =
pm.get_vertex_prop_with_ctx(*vid, key, ctx.as_ref()).await?;
if !existing.is_null()
&& let Some(val) = props.get_mut(key)
{
*val = pm.merge_crdt_values(&existing, val)?;
}
}
}
}
}
}
// Batch L0 writes — route to active L0 (transaction L0 if active, else current).
let target_l0 = self.resolve_l0(tx_l0);
let properties_result = properties_batch.clone();
{
let mut l0_guard = target_l0.write();
for (vid, props) in vids.iter().zip(properties_batch.iter()) {
l0_guard.insert_vertex_with_labels(*vid, props.clone(), &labels);
}
}
// Update metrics (batch increment)
metrics::counter!("uni_l0_buffer_mutations_total").increment(vids.len() as u64);
self.update_metrics();
Ok::<Vec<Properties>, anyhow::Error>(properties_result)
}
.await;
let props = result?;
if start.elapsed().as_millis() > 100 {
log::warn!(
"Slow insert_vertices_batch ({} vertices): {}ms",
vids.len(),
start.elapsed().as_millis()
);
}
Ok(props)
}
/// Delete a vertex by VID.
///
/// When `labels` is provided, uses them directly to populate L0 for
/// correct tombstone flushing. Otherwise discovers labels from L0
/// buffers and storage (which can be slow for many vertices).
///
/// # Errors
///
/// Returns an error if write pressure stalls, label lookup fails, or
/// the L0 delete operation fails.
#[instrument(skip(self, labels), level = "trace")]
pub async fn delete_vertex(
&self,
vid: Vid,
labels: Option<Vec<String>>,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let start = std::time::Instant::now();
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
self.freeze_for_non_tx_write_if_pinned(tx_l0).await; // C1 (G4)
let l0 = self.resolve_l0(tx_l0);
// Before deleting, ensure we have the vertex's labels stored in L0
// so the tombstone can be properly flushed to the correct label datasets.
let has_labels = {
let l0_guard = l0.read();
l0_guard.vertex_labels.contains_key(&vid)
};
if !has_labels {
let resolved_labels = if let Some(provided) = labels {
// Caller provided labels — skip the lookup entirely
Some(provided)
} else {
// Discover labels from pending flush L0s, then storage
let mut found = None;
for pending_l0 in self.l0_manager.get_pending_flush() {
let pending_guard = pending_l0.read();
if let Some(l) = pending_guard.get_vertex_labels(vid) {
found = Some(l.to_vec());
break;
}
}
if found.is_none() {
found = self.find_vertex_labels_in_storage(vid).await?;
}
found
};
if let Some(found_labels) = resolved_labels {
let mut l0_guard = l0.write();
l0_guard.vertex_labels.insert(vid, found_labels);
}
}
l0.write().delete_vertex(vid)?;
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
if start.elapsed().as_millis() > 100 {
log::warn!("Slow delete_vertex: {}ms", start.elapsed().as_millis());
}
Ok(())
}
/// Find vertex labels from storage by querying the main vertices table.
/// Returns the labels from the latest non-deleted version of the vertex.
async fn find_vertex_labels_in_storage(&self, vid: Vid) -> Result<Option<Vec<String>>> {
use crate::backend::types::ScanRequest;
use arrow_array::Array;
use arrow_array::cast::AsArray;
let backend = self.storage.backend();
let table_name = MainVertexDataset::table_name();
// Check if table exists first; if not, vertex hasn't been flushed to storage yet
if !backend.table_exists(table_name).await? {
return Ok(None);
}
// Query for this specific vid (don't filter by _deleted yet - we need to find the latest version first)
let filter = format!("_vid = {}", vid.as_u64());
let batches = backend
.scan(
ScanRequest::all(table_name)
.with_filter(filter)
.with_columns(vec![
"_vid".to_string(),
"labels".to_string(),
"_version".to_string(),
"_deleted".to_string(),
]),
)
.await
.unwrap_or_default();
// Find the row with the highest version number
let mut max_version: Option<u64> = None;
let mut labels: Option<Vec<String>> = None;
let mut is_deleted = false;
for batch in batches {
if batch.num_rows() == 0 {
continue;
}
let version_array = batch
.column_by_name("_version")
.unwrap()
.as_primitive::<arrow_array::types::UInt64Type>();
let deleted_array = batch.column_by_name("_deleted").unwrap().as_boolean();
let labels_array = batch.column_by_name("labels").unwrap().as_list::<i32>();
for row_idx in 0..batch.num_rows() {
let version = version_array.value(row_idx);
if max_version.is_none_or(|mv| version > mv) {
is_deleted = deleted_array.value(row_idx);
let labels_list = labels_array.value(row_idx);
let string_array = labels_list.as_string::<i32>();
let vertex_labels: Vec<String> = (0..string_array.len())
.filter(|&i| !string_array.is_null(i))
.map(|i| string_array.value(i).to_string())
.collect();
max_version = Some(version);
labels = Some(vertex_labels);
}
}
}
// If the latest version is deleted, return None
if is_deleted { Ok(None) } else { Ok(labels) }
}
#[expect(clippy::too_many_arguments)]
#[instrument(skip(self, props, touched_keys), level = "trace")]
pub async fn insert_edge_partial_full(
&self,
src_vid: Vid,
dst_vid: Vid,
edge_type: u32,
eid: Eid,
props: Properties,
edge_type_name: Option<String>,
touched_keys: HashSet<String>,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
self.freeze_for_non_tx_write_if_pinned(tx_l0).await; // C1 (G4)
if !self.config.partial_lance_writes {
return self
.insert_edge(
src_vid,
dst_vid,
edge_type,
eid,
props,
edge_type_name,
tx_l0,
)
.await;
}
let start = std::time::Instant::now();
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
let mut props = props;
self.prepare_edge_upsert(eid, &mut props, tx_l0).await?;
let l0 = self.resolve_l0(tx_l0);
l0.write().insert_edge_partial_full(
src_vid,
dst_vid,
edge_type,
eid,
props,
edge_type_name,
touched_keys,
)?;
if tx_l0.is_none() {
let version = l0.read().current_version;
self.adjacency_manager
.insert_edge(src_vid, dst_vid, eid, edge_type, version);
}
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
metrics::counter!("uni_partial_writes_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
if start.elapsed().as_millis() > 100 {
log::warn!(
"Slow insert_edge_partial_full: {}ms",
start.elapsed().as_millis()
);
}
Ok(())
}
#[expect(clippy::too_many_arguments)]
pub async fn insert_edge(
&self,
src_vid: Vid,
dst_vid: Vid,
edge_type: u32,
eid: Eid,
mut properties: Properties,
edge_type_name: Option<String>,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let start = std::time::Instant::now();
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
self.freeze_for_non_tx_write_if_pinned(tx_l0).await; // C1 (G4)
self.prepare_edge_upsert(eid, &mut properties, tx_l0)
.await?;
let l0 = self.resolve_l0(tx_l0);
l0.write()
.insert_edge(src_vid, dst_vid, edge_type, eid, properties, edge_type_name)?;
// Dual-write to AdjacencyManager overlay (survives flush).
// Skip for transaction-local L0 -- transaction edges are overlaid separately.
if tx_l0.is_none() {
let version = l0.read().current_version;
self.adjacency_manager
.insert_edge(src_vid, dst_vid, eid, edge_type, version);
}
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
if start.elapsed().as_millis() > 100 {
log::warn!("Slow insert_edge: {}ms", start.elapsed().as_millis());
}
Ok(())
}
#[instrument(skip(self), level = "trace")]
pub async fn delete_edge(
&self,
eid: Eid,
src_vid: Vid,
dst_vid: Vid,
edge_type: u32,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> Result<()> {
let start = std::time::Instant::now();
self.check_write_pressure().await?;
self.check_transaction_memory(tx_l0)?;
self.freeze_for_non_tx_write_if_pinned(tx_l0).await; // C1 (G4)
let l0 = self.resolve_l0(tx_l0);
l0.write().delete_edge(eid, src_vid, dst_vid, edge_type)?;
// Dual-write tombstone to AdjacencyManager overlay.
if tx_l0.is_none() {
let version = l0.read().current_version;
self.adjacency_manager
.add_tombstone(eid, src_vid, dst_vid, edge_type, version);
}
metrics::counter!("uni_l0_buffer_mutations_total").increment(1);
self.update_metrics();
if tx_l0.is_none() {
self.check_flush().await?;
}
if start.elapsed().as_millis() > 100 {
log::warn!("Slow delete_edge: {}ms", start.elapsed().as_millis());
}
Ok(())
}
/// Decide whether a flush should be triggered based on mutation count
/// or elapsed time since the last flush.
///
/// Extracted from [`Writer::check_flush`] so `commit_transaction_l0` can
/// reuse the decision while bypassing the lock-acquiring entry point
/// (it already holds `flush_lock`).
fn should_flush(&self) -> bool {
let count = self.l0_manager.get_current().read().mutation_count;
if count == 0 {
return false;
}
if count >= self.config.auto_flush_threshold {
return true;
}
if let Some(interval) = self.config.auto_flush_interval
&& self.last_flush_time.lock().elapsed() >= interval
&& count >= self.config.auto_flush_min_mutations
{
return true;
}
false
}
/// Check if flush should be triggered based on mutation count or time elapsed.
/// This method is called after each write operation and can also be called
/// by a background task for time-based flushing.
pub async fn check_flush(&self) -> Result<()> {
if self.should_flush() {
self.flush_to_l1(None).await?;
}
Ok(())
}
/// Process embeddings for a vertex using labels passed directly.
/// Use this when labels haven't been stored to L0 yet.
async fn process_embeddings_for_labels(
&self,
labels: &[String],
properties: &mut Properties,
) -> Result<()> {
let label_name = labels.first().map(|s| s.as_str());
self.process_embeddings_impl(label_name, properties).await
}
/// Phase B: if `defer_embeddings` is enabled in `UniConfig` and the
/// vertex has an embedding config that hasn't been satisfied by the
/// caller-provided properties, enqueue the VID in
/// `L0Buffer::pending_embeddings` and return `true`. The caller then
/// skips `process_embeddings_for_labels` and the embedding is computed
/// in a single batched call at flush time via
/// `drain_pending_embeddings`.
///
/// Returns `false` (caller falls back to today's per-row eager embed)
/// if any of:
/// - the flag is off,
/// - no label has an embedding config,
/// - the user already provided the target property (matches the
/// existing skip-if-present semantics at writer.rs:2727).
///
/// Trade-off: when deferral is active, in-tx reads of the embedding
/// column return only what was already in storage (or nothing for
/// brand-new vertices). Existing tests that RETURN n.embedding in
/// the same tx as a SET on the source column must run with the flag
/// off; opt in only when no such reads happen between write and
/// commit.
fn try_defer_embedding(
&self,
labels: &[String],
properties: &Properties,
vid: Vid,
tx_l0: Option<&Arc<RwLock<L0Buffer>>>,
) -> bool {
if !self.config.defer_embeddings {
return false;
}
let Some(label) = labels.first() else {
return false;
};
let schema = self.schema_manager.schema();
let mut has_unsatisfied_cfg = false;
for idx in &schema.indexes {
if let IndexDefinition::Vector(v_cfg) = idx
&& v_cfg.label == *label
&& v_cfg.embedding_config.is_some()
&& !properties.contains_key(&v_cfg.property)
{
has_unsatisfied_cfg = true;
break;
}
}
if !has_unsatisfied_cfg {
return false;
}
let l0 = self.resolve_l0(tx_l0);
let mut guard = l0.write();
guard.pending_embeddings.insert(vid, label.clone());
true
}
/// Drain `pending_embeddings` from the rotated old-L0 right before
/// `flush_stream_l1` reads it. Groups by label, issues one batched
/// `process_embeddings_for_batch` call per label, and writes the
/// resulting embedding vectors into each VID's `vertex_properties`
/// map. After this returns, the flush proceeds against an L0 that
/// looks no different from one whose embeddings were generated
/// per-row at insert.
///
/// Idempotent: a VID whose embedding was already materialized
/// (e.g., by on-demand read paths in a future Phase B revision) is
/// detected via `properties.contains_key(target_prop)` inside
/// `process_embeddings_for_batch` (writer.rs:~2650), so re-running
/// the drain is safe.
async fn drain_pending_embeddings(&self, old_l0_arc: &Arc<RwLock<L0Buffer>>) -> Result<()> {
let by_label: HashMap<String, Vec<Vid>> = {
let guard = old_l0_arc.read();
if guard.pending_embeddings.is_empty() {
return Ok(());
}
let mut m: HashMap<String, Vec<Vid>> = HashMap::new();
for (vid, label) in &guard.pending_embeddings {
m.entry(label.clone()).or_default().push(*vid);
}
m
};
for (label, vids) in by_label {
let mut properties_batch: Vec<Properties> = {
let guard = old_l0_arc.read();
vids.iter()
.map(|vid| {
guard
.vertex_properties
.get(vid)
.cloned()
.unwrap_or_default()
})
.collect()
};
self.process_embeddings_for_batch(std::slice::from_ref(&label), &mut properties_batch)
.await?;
let mut guard = old_l0_arc.write();
for (vid, props) in vids.iter().zip(properties_batch) {
let target = guard.vertex_properties.entry(*vid).or_default();
for (k, v) in props {
target.insert(k, v);
}
guard.pending_embeddings.remove(vid);
}
}
Ok(())
}
/// Process embeddings for a batch of vertices efficiently.
///
/// Groups vertices by embedding config and makes batched API calls to the
/// embedding service instead of calling once per vertex.
///
/// # Performance
/// For N vertices with embedding config:
/// - Old approach: N API calls to embedding service
/// - New approach: 1 API call per embedding config (usually 1 total)
async fn process_embeddings_for_batch(
&self,
labels: &[String],
properties_batch: &mut [Properties],
) -> Result<()> {
let label_name = labels.first().map(|s| s.as_str());
let schema = self.schema_manager.schema();
if let Some(label) = label_name {
// Find vector indexes with embedding config for this label
let mut configs = Vec::new();
for idx in &schema.indexes {
if let IndexDefinition::Vector(v_config) = idx
&& v_config.label == label
&& let Some(emb_config) = &v_config.embedding_config
{
configs.push((v_config.property.clone(), emb_config.clone()));
}
}
if configs.is_empty() {
return Ok(());
}
for (target_prop, emb_config) in configs {
// Collect input texts from all vertices that need embeddings
let mut input_texts: Vec<String> = Vec::new();
let mut needs_embedding: Vec<usize> = Vec::new();
for (idx, properties) in properties_batch.iter().enumerate() {
// Skip if target property already exists
if properties.contains_key(&target_prop) {
continue;
}
// Check if source properties exist
let mut inputs = Vec::new();
for src_prop in &emb_config.source_properties {
if let Some(val) = properties.get(src_prop)
&& let Some(s) = val.as_str()
{
inputs.push(s.to_string());
}
}
if !inputs.is_empty() {
let input_text = inputs.join(" ");
let input_text = match &emb_config.document_prefix {
Some(prefix) => format!("{prefix}{input_text}"),
None => input_text,
};
input_texts.push(input_text);
needs_embedding.push(idx);
}
}
if input_texts.is_empty() {
continue;
}
let runtime = self.xervo_runtime.get().ok_or_else(|| {
anyhow!("Uni-Xervo runtime not configured for auto-embedding")
})?;
let embedder = runtime.embedding(&emb_config.alias).await?;
// Batch generate embeddings (single API call)
let input_refs: Vec<&str> = input_texts.iter().map(|s| s.as_str()).collect();
let embeddings = embedder.embed(input_refs).await?;
// Distribute results back to properties
for (embedding_idx, &prop_idx) in needs_embedding.iter().enumerate() {
if let Some(vec) = embeddings.get(embedding_idx) {
let vals: Vec<Value> =
vec.iter().map(|f| Value::Float(*f as f64)).collect();
properties_batch[prop_idx].insert(target_prop.clone(), Value::List(vals));
}
}
}
}
Ok(())
}
async fn process_embeddings_impl(
&self,
label_name: Option<&str>,
properties: &mut Properties,
) -> Result<()> {
let schema = self.schema_manager.schema();
if let Some(label) = label_name {
// Find vector indexes with embedding config for this label
let mut configs = Vec::new();
for idx in &schema.indexes {
if let IndexDefinition::Vector(v_config) = idx
&& v_config.label == label
&& let Some(emb_config) = &v_config.embedding_config
{
configs.push((v_config.property.clone(), emb_config.clone()));
}
}
if configs.is_empty() {
log::info!("No embedding config found for label {}", label);
}
for (target_prop, emb_config) in configs {
// If target property already exists, skip (assume user provided it)
if properties.contains_key(&target_prop) {
continue;
}
// Check if source properties exist
let mut inputs = Vec::new();
for src_prop in &emb_config.source_properties {
if let Some(val) = properties.get(src_prop)
&& let Some(s) = val.as_str()
{
inputs.push(s.to_string());
}
}
if inputs.is_empty() {
continue;
}
let input_text = inputs.join(" ");
let input_text = match &emb_config.document_prefix {
Some(prefix) => format!("{prefix}{input_text}"),
None => input_text,
};
let runtime = self.xervo_runtime.get().ok_or_else(|| {
anyhow!("Uni-Xervo runtime not configured for auto-embedding")
})?;
let embedder = runtime.embedding(&emb_config.alias).await?;
// Generate
let embeddings = embedder.embed(vec![input_text.as_str()]).await?;
if let Some(vec) = embeddings.first() {
// Store as array of floats
let vals: Vec<Value> = vec.iter().map(|f| Value::Float(*f as f64)).collect();
properties.insert(target_prop.clone(), Value::List(vals));
}
}
}
Ok(())
}
/// Flushes the current in-memory L0 buffer to L1 storage.
///
/// # Lock Ordering
///
/// To prevent deadlocks, locks must be acquired in the following order:
/// 1. `Writer` lock (held by caller via outer `Arc<RwLock<Writer>>`; removed in Phase 4)
/// 2. `flush_lock` (acquired by this entry point; held across the whole flush)
/// 3. `L0Manager` lock (via `begin_flush` / `get_current`)
/// 4. `L0Buffer` lock (individual buffer RWLocks)
/// 5. `Index` / `Storage` locks (during actual flush)
///
/// Callers that already hold `flush_lock` (today only `commit_transaction_l0`)
/// must call `flush_inline_under_lock` (private) directly to avoid a re-entrant
/// `tokio::sync::Mutex` deadlock — see concurrent_writer.md §5.5.
pub async fn flush_to_l1(&self, name: Option<String>) -> Result<String> {
// Drain any in-flight async flushes first. `flush_to_l1` is a
// SYNCHRONIZATION BARRIER — callers (test fixtures, fork
// setup, shutdown paths) rely on it as "all writes are now
// durably in Lance". Without the drain, an async stream from
// a recent commit might still be writing to Lance when
// `flush_to_l1` returns, leaving a window where forks branch
// off pre-write Lance state and lose data.
if let Some(coord) = self.flush_coordinator.as_ref() {
let _ = coord.drain(self.config.drop_fork_drain_timeout).await;
}
let _flush_lock_guard = self.flush_lock.lock().await;
self.flush_inline_under_lock(name).await
}
/// Async-flush entry point: rotate under `flush_lock`, release the
/// lock, then submit the stream phase to the [`FlushCoordinator`].
/// Returns a [`FlushTicket`](crate::runtime::flush_coordinator::FlushTicket)
/// that resolves when finalize completes.
///
/// Errors if `config.async_flush_enabled = false` (the coordinator
/// is `None` in that case — see `flush_coordinator` field doc).
pub async fn flush_to_l1_async(
self: &Arc<Self>,
name: Option<String>,
) -> Result<crate::runtime::flush_coordinator::FlushTicket> {
let coord = self
.flush_coordinator
.as_ref()
.ok_or_else(|| anyhow!("async flush not enabled (config.async_flush_enabled=false)"))?
.clone();
// 1. Acquire permit FIRST (outside flush_lock) so we don't
// introduce a permit-while-holding-flush-lock convoy.
let permit = coord.acquire_permit().await?;
let seq = coord.next_rotate_seq();
coord.note_pending();
// 2. Rotate under flush_lock (µs work).
let RotateOutput {
old_l0_arc,
wal_lsn,
current_version,
flush_in_progress_guard,
} = {
let _flush_lock_guard = self.flush_lock.lock().await;
self.flush_l0_rotate().await?
};
// 3. Build the coordinator's RotatedFlush. parent_manifest is the
// cached_manifest snapshot at this moment.
let parent_manifest = self.cached_manifest.lock().clone();
let rotated = RotatedFlush {
seq,
old_l0_arc: old_l0_arc.clone(),
wal_lsn,
current_version,
name: name.clone(),
parent_manifest,
permit,
flush_in_progress_guard,
};
// 4. Spawn the stream phase via the coordinator. The closure
// captures Arc<Writer> transiently — drops when stream
// completes (bounded, ~50-500 ms).
let writer = self.clone();
let ticket = coord.submit_for_stream(rotated, move |old_l0, wal, ver, n| async move {
let outcome = writer.flush_stream_l1(old_l0, wal, ver, n).await?;
Ok(crate::runtime::flush_coordinator::FlushOutcome {
new_manifest: outcome.manifest,
snapshot_id: outcome.snapshot_id,
})
});
Ok(ticket)
}
/// Phase A+B+C of the flush: flush the WAL, rotate L0 (so the
/// to-be-flushed buffer moves to `pending_flush` and a fresh L0 takes
/// its place), and hand off the WAL to the new L0.
///
/// Runs in microseconds. Must be called under `flush_lock` (the caller
/// is responsible). The returned [`RotateOutput`] carries everything
/// the subsequent stream + finalize phases need; in particular the
/// [`FlushInProgressGuard`] is bound to the return value so it stays
/// alive for the full flush lifetime — including any future async
/// path where stream runs on a spawned task.
async fn flush_l0_rotate(&self) -> Result<RotateOutput> {
// Acquire the in-progress counter BEFORE any heavy work. The
// guard lives on RotateOutput; dropping RotateOutput drops the
// guard, so the counter goes back to zero exactly when the flush
// is fully done.
let flush_in_progress_guard = FlushInProgressGuard::new(&self.storage);
// A. Flush WAL BEFORE rotating L0. If WAL flush fails, the
// current L0 is still active and mutations are retained in
// memory until restart/retry.
let wal_for_truncate = {
let current_l0 = self.l0_manager.get_current();
let l0_guard = current_l0.read();
l0_guard.wal.clone()
};
let wal_lsn = if let Some(ref w) = wal_for_truncate {
w.flush().await?
} else {
0
};
// B. Begin flush: rotate L0 and keep old L0 visible to reads via
// pending_flush until complete_flush is called by finalize.
let old_l0_arc = self.l0_manager.begin_flush(0, None);
metrics::counter!("uni_l0_buffer_rotations_total").increment(1);
// C. WAL handoff: record wal_lsn on old L0, transfer WAL handle
// and current_version to the new L0.
let current_version;
{
let mut old_l0_guard = old_l0_arc.write();
current_version = old_l0_guard.current_version;
old_l0_guard.wal_lsn_at_flush = wal_lsn;
let wal = old_l0_guard.wal.take();
let new_l0_arc = self.l0_manager.get_current();
let mut new_l0_guard = new_l0_arc.write();
new_l0_guard.wal = wal;
new_l0_guard.current_version = current_version;
}
Ok(RotateOutput {
old_l0_arc,
wal_lsn,
current_version,
flush_in_progress_guard,
})
}
/// Phases D, E, F, G of the flush: L1 collect, orphan resolve,
/// manifest seed, Lance writes. Reads from `old_l0_arc` (kept in
/// pending_flush by Phase B); writes append-only Lance datasets; does
/// NOT call save_snapshot / set_latest_snapshot — those are
/// finalize's job, so the manifest doesn't get published until the
/// next phase.
///
/// Today takes `&self`; in a follow-up commit this becomes a
/// static `Send + 'static` function over `SharedFlushCtx` so it can
/// run on a spawned task while concurrent commits proceed.
async fn flush_stream_l1(
&self,
old_l0_arc: Arc<RwLock<L0Buffer>>,
wal_lsn: u64,
current_version: u64,
name: Option<String>,
) -> Result<FlushOutcome> {
// Phase B: materialize any deferred embeddings before column
// extraction. No-op when `defer_embeddings` is off (the set will
// be empty). On-demand reads of the embedding column are a TODO
// for a future revision (see UniConfig::defer_embeddings docs).
self.drain_pending_embeddings(&old_l0_arc).await?;
let schema = self.schema_manager.schema();
// 2. Acquire Read lock on Old L0 for flushing
let mut entries_by_type: HashMap<u32, Vec<L1Entry>> = HashMap::new();
// (Vid, labels, properties, deleted, version)
type VertexEntry = (Vid, Vec<String>, Properties, bool, u64);
let mut vertices_by_label: HashMap<u16, Vec<VertexEntry>> = HashMap::new();
// Partial-column updates (Lance MergeInsert path). Per-VID tuple:
// (vid, full L0 properties map, version, set of keys to update).
// Only the keys in the HashSet are emitted to the partial source;
// the full props map is retained so the per-row column extractor
// can read each touched key's value.
type PartialEntry = (Vid, Properties, u64, std::collections::HashSet<String>);
let mut partial_by_label: HashMap<u16, Vec<PartialEntry>> = HashMap::new();
// DELETE-via-MergeInsert (Round-12 §B): tombstones flush as a
// partial source with just `_vid`, `_deleted=true`, `_version`,
// `_updated_at`. Skips the wide-row Append payload that adds
// nothing on a soft-delete.
let mut tombstones_by_label: HashMap<u16, Vec<(Vid, u64)>> = HashMap::new();
let mut main_vertex_tombstones: Vec<(Vid, u64)> = Vec::new();
// Collect vertex timestamps from L0 for flushing to storage
let mut vertex_created_at: HashMap<Vid, i64> = HashMap::new();
let mut vertex_updated_at: HashMap<Vid, i64> = HashMap::new();
// Track tombstones missing labels for storage query fallback
let mut orphaned_tombstones: Vec<(Vid, u64)> = Vec::new();
{
let old_l0 = old_l0_arc.read();
// 1. Collect all edges and tombstones from L0
for edge in old_l0.graph.edges() {
let properties = old_l0
.edge_properties
.get(&edge.eid)
.cloned()
.unwrap_or_default();
let version = old_l0.edge_versions.get(&edge.eid).copied().unwrap_or(0);
// Get timestamps from L0 buffer (populated during insert)
let created_at = old_l0.edge_created_at.get(&edge.eid).copied();
let updated_at = old_l0.edge_updated_at.get(&edge.eid).copied();
entries_by_type
.entry(edge.edge_type)
.or_default()
.push(L1Entry {
src_vid: edge.src_vid,
dst_vid: edge.dst_vid,
eid: edge.eid,
op: Op::Insert,
version,
properties,
created_at,
updated_at,
});
}
// From tombstones
for tombstone in old_l0.tombstones.values() {
let version = old_l0
.edge_versions
.get(&tombstone.eid)
.copied()
.unwrap_or(0);
// Get timestamps - for deletes, updated_at reflects deletion time
let created_at = old_l0.edge_created_at.get(&tombstone.eid).copied();
let updated_at = old_l0.edge_updated_at.get(&tombstone.eid).copied();
entries_by_type
.entry(tombstone.edge_type)
.or_default()
.push(L1Entry {
src_vid: tombstone.src_vid,
dst_vid: tombstone.dst_vid,
eid: tombstone.eid,
op: Op::Delete,
version,
properties: HashMap::new(),
created_at,
updated_at,
});
}
// 1b. Collect vertices by label (using vertex_labels from L0)
//
// Helper: fan-out a single vertex entry into per-label buckets.
// Each per-label table row carries the full label set so multi-label
// info is preserved after flush.
let push_vertex_to_labels =
|vid: Vid,
all_labels: &[String],
props: Properties,
deleted: bool,
version: u64,
out: &mut HashMap<u16, Vec<VertexEntry>>| {
for label in all_labels {
if let Some(label_id) = schema.label_id_by_name(label) {
out.entry(label_id).or_default().push((
vid,
all_labels.to_vec(),
props.clone(),
deleted,
version,
));
}
}
};
for (vid, props) in &old_l0.vertex_properties {
let version = old_l0.vertex_versions.get(vid).copied().unwrap_or(0);
// Collect timestamps for this vertex
if let Some(&ts) = old_l0.vertex_created_at.get(vid) {
vertex_created_at.insert(*vid, ts);
}
if let Some(&ts) = old_l0.vertex_updated_at.get(vid) {
vertex_updated_at.insert(*vid, ts);
}
if let Some(labels) = old_l0.vertex_labels.get(vid) {
// Partial-write routing: when this VID was last
// touched via `insert_vertex_partial` AND the
// partial_lance_writes flag is on, send only the
// touched columns to a MergeInsert batch. Otherwise
// (CREATE, MERGE-ON-CREATE, full-replace SET, DELETE
// — or flag off) use the existing full-row Append.
let is_partial = self.config.partial_lance_writes
&& old_l0.vertex_partial_keys.contains_key(vid);
if is_partial {
if let Some(touched) = old_l0.vertex_partial_keys.get(vid) {
for label in labels {
if let Some(label_id) = schema.label_id_by_name(label) {
partial_by_label.entry(label_id).or_default().push((
*vid,
props.clone(),
version,
touched.clone(),
));
}
}
}
} else {
push_vertex_to_labels(
*vid,
labels,
props.clone(),
false,
version,
&mut vertices_by_label,
);
}
}
}
for &vid in &old_l0.vertex_tombstones {
let version = old_l0.vertex_versions.get(&vid).copied().unwrap_or(0);
if let Some(&ts) = old_l0.vertex_updated_at.get(&vid) {
vertex_updated_at.insert(vid, ts);
}
if let Some(labels) = old_l0.vertex_labels.get(&vid) {
// Round-12 §B: tombstones flush via Lance MergeInsert
// (just `_vid`, `_deleted=true`, `_version`,
// `_updated_at`) — skipping the wide-row Append.
// Unconditional (no `partial_lance_writes` gating);
// tombstone Append carries no useful payload.
for label in labels {
if let Some(label_id) = schema.label_id_by_name(label) {
tombstones_by_label
.entry(label_id)
.or_default()
.push((vid, version));
}
}
} else {
// Tombstone missing labels (old WAL format) - collect for storage query fallback
orphaned_tombstones.push((vid, version));
}
}
} // Drop read lock
// Resolve orphaned tombstones (missing labels) from storage
if !orphaned_tombstones.is_empty() {
tracing::warn!(
count = orphaned_tombstones.len(),
"Tombstones missing labels in L0, querying storage as fallback"
);
for (vid, version) in orphaned_tombstones {
if let Ok(Some(labels)) = self.find_vertex_labels_in_storage(vid).await
&& !labels.is_empty()
{
for label in &labels {
if let Some(label_id) = schema.label_id_by_name(label) {
// Round-12 §B: route through partial tombstone too.
tombstones_by_label
.entry(label_id)
.or_default()
.push((vid, version));
}
}
}
}
}
// 1. Load previous snapshot from cache, or fall back to storage.
//
// Use clone() not take(): for the async path, multiple
// concurrent streams may run; if we take() here, a sibling
// stream sees cached_manifest = None and seeds from
// load_latest_snapshot (stale), losing the chain. clone()
// preserves the parent. Finalize writes back the new manifest
// unconditionally.
let mut manifest = if let Some(cached) = self.cached_manifest.lock().clone() {
cached
} else {
self.storage
.snapshot_manager()
.load_latest_snapshot()
.await?
.unwrap_or_else(|| {
SnapshotManifest::new(Uuid::new_v4().to_string(), schema.schema_version)
})
};
// Update snapshot metadata
// Save parent snapshot ID before generating new one (for lineage tracking)
let parent_id = manifest.snapshot_id.clone();
manifest.parent_snapshot = Some(parent_id);
manifest.snapshot_id = Uuid::new_v4().to_string();
manifest.name = name;
manifest.created_at = Utc::now();
manifest.version_high_water_mark = current_version;
manifest.wal_high_water_mark = wal_lsn;
let snapshot_id = manifest.snapshot_id.clone();
tracing::Span::current().record("snapshot_id", &snapshot_id);
// 2. Write main unified tables FIRST (before deltas).
// Ensures the dual-write invariant: by the time an EID appears in a
// delta table, it already exists in main_edges. This prevents the
// compaction debug_assert from firing when compaction interleaves
// with flush at async yield points.
//
// 2.1 Main edges table
let (main_edges, edge_created_at_map, edge_updated_at_map) = {
let _old_l0 = old_l0_arc.read();
let mut main_edges: Vec<(
uni_common::core::id::Eid,
Vid,
Vid,
String,
Properties,
bool,
u64,
)> = Vec::new();
let mut edge_created_at_map: HashMap<uni_common::core::id::Eid, i64> = HashMap::new();
let mut edge_updated_at_map: HashMap<uni_common::core::id::Eid, i64> = HashMap::new();
for (&edge_type_id, entries) in entries_by_type.iter() {
for entry in entries {
let edge_type_name = self
.storage
.schema_manager()
.edge_type_name_by_id_unified(edge_type_id)
.unwrap_or_else(|| "unknown".to_string());
let deleted = matches!(entry.op, Op::Delete);
main_edges.push((
entry.eid,
entry.src_vid,
entry.dst_vid,
edge_type_name,
entry.properties.clone(),
deleted,
entry.version,
));
if let Some(ts) = entry.created_at {
edge_created_at_map.insert(entry.eid, ts);
}
if let Some(ts) = entry.updated_at {
edge_updated_at_map.insert(entry.eid, ts);
}
}
}
(main_edges, edge_created_at_map, edge_updated_at_map)
};
if !main_edges.is_empty() {
let main_edge_batch = MainEdgeDataset::build_record_batch(
&main_edges,
Some(&edge_created_at_map),
Some(&edge_updated_at_map),
)?;
MainEdgeDataset::write_batch(self.storage.backend(), main_edge_batch).await?;
MainEdgeDataset::ensure_default_indexes(self.storage.backend()).await?;
}
// 2.2 Main vertices table
let main_vertices: Vec<(Vid, Vec<String>, Properties, bool, u64)> = {
let old_l0 = old_l0_arc.read();
let mut vertices = Vec::new();
// Live vertices: full-row Append on the main table (the
// props_json blob is required for global ID lookups). For
// partial-row VIDs (vertex_partial_keys non-empty), the
// main table still needs the full props for the
// ext_id-uniqueness path; we keep the Append here. The
// per-label Lance write IS partial via MergeInsert.
for (vid, props) in &old_l0.vertex_properties {
let version = old_l0.vertex_versions.get(vid).copied().unwrap_or(0);
let labels = old_l0.vertex_labels.get(vid).cloned().unwrap_or_default();
vertices.push((*vid, labels, props.clone(), false, version));
}
// Tombstones: collected into `main_vertex_tombstones` for
// the MergeInsert path below; skipping the wide-row Append.
for &vid in &old_l0.vertex_tombstones {
let version = old_l0.vertex_versions.get(&vid).copied().unwrap_or(0);
main_vertex_tombstones.push((vid, version));
}
vertices
};
if !main_vertices.is_empty() {
let main_vertex_batch = MainVertexDataset::build_record_batch(
&main_vertices,
Some(&vertex_created_at),
Some(&vertex_updated_at),
)?;
MainVertexDataset::write_batch(self.storage.backend(), main_vertex_batch).await?;
}
// Round-12 §B: tombstones via MergeInsert on the main vertices
// table. Independent of `vertex_properties` length.
if !main_vertex_tombstones.is_empty() {
let tomb_batch = MainVertexDataset::build_tombstone_partial_batch(
&main_vertex_tombstones,
Some(&vertex_updated_at),
)?;
MainVertexDataset::merge_insert_tombstone_batch(self.storage.backend(), tomb_batch)
.await?;
}
if !main_vertices.is_empty() || !main_vertex_tombstones.is_empty() {
MainVertexDataset::ensure_default_indexes(self.storage.backend()).await?;
}
// 3. For each edge type, write FWD and BWD delta runs
for (&edge_type_id, entries) in entries_by_type.iter() {
// Get edge type name from unified lookup (handles both schema'd and schemaless)
let edge_type_name = self
.storage
.schema_manager()
.edge_type_name_by_id_unified(edge_type_id)
.ok_or_else(|| anyhow!("Edge type ID {} not found", edge_type_id))?;
// FWD Run (sorted by src_vid)
// Round-12 §A: split entries into full-row Append and
// partial MergeInsert routes based on `edge_partial_keys`.
// Edges in `edge_partial_keys` were last written via
// `insert_edge_partial_full`; the per-edge-type delta
// tables receive only the touched schema columns plus
// (when any overflow key was touched) the regenerated
// `overflow_json` blob. Untouched columns retain their
// previous-version value via Lance MergeInsert.
let partial_eids: std::collections::HashSet<Eid> = {
let old_l0 = old_l0_arc.read();
entries
.iter()
.filter(|e| {
self.config.partial_lance_writes
&& old_l0.edge_partial_keys.contains_key(&e.eid)
})
.map(|e| e.eid)
.collect()
};
let touched_union_by_eid: HashMap<Eid, std::collections::HashSet<String>> = {
let old_l0 = old_l0_arc.read();
partial_eids
.iter()
.filter_map(|eid| old_l0.edge_partial_keys.get(eid).map(|s| (*eid, s.clone())))
.collect()
};
let (full_entries, partial_entries): (Vec<L1Entry>, Vec<L1Entry>) = entries
.clone()
.into_iter()
.partition(|e| !partial_eids.contains(&e.eid));
let backend = self.storage.backend();
// FWD run (sorted by src_vid)
let mut fwd_full = full_entries.clone();
fwd_full.sort_by_key(|e| e.src_vid);
let mut fwd_partial = partial_entries.clone();
fwd_partial.sort_by_key(|e| e.src_vid);
let fwd_ds = self.storage.delta_dataset(&edge_type_name, "fwd")?;
if !fwd_full.is_empty() {
let fwd_batch = fwd_ds.build_record_batch(&fwd_full, &schema)?;
fwd_ds.write_run(backend, fwd_batch).await?;
}
if !fwd_partial.is_empty() {
let touched_union: std::collections::HashSet<String> = fwd_partial
.iter()
.flat_map(|e| {
touched_union_by_eid
.get(&e.eid)
.cloned()
.unwrap_or_default()
.into_iter()
})
.collect();
let fwd_partial_batch =
fwd_ds.build_partial_record_batch(&fwd_partial, &touched_union, &schema)?;
fwd_ds
.merge_insert_partial_run(backend, fwd_partial_batch)
.await?;
}
fwd_ds.ensure_eid_index(backend).await?;
// BWD Run (sorted by dst_vid)
let mut bwd_full = full_entries.clone();
bwd_full.sort_by_key(|e| e.dst_vid);
let mut bwd_partial = partial_entries.clone();
bwd_partial.sort_by_key(|e| e.dst_vid);
let bwd_ds = self.storage.delta_dataset(&edge_type_name, "bwd")?;
if !bwd_full.is_empty() {
let bwd_batch = bwd_ds.build_record_batch(&bwd_full, &schema)?;
bwd_ds.write_run(backend, bwd_batch).await?;
}
if !bwd_partial.is_empty() {
let touched_union: std::collections::HashSet<String> = bwd_partial
.iter()
.flat_map(|e| {
touched_union_by_eid
.get(&e.eid)
.cloned()
.unwrap_or_default()
.into_iter()
})
.collect();
let bwd_partial_batch =
bwd_ds.build_partial_record_batch(&bwd_partial, &touched_union, &schema)?;
bwd_ds
.merge_insert_partial_run(backend, bwd_partial_batch)
.await?;
}
bwd_ds.ensure_eid_index(backend).await?;
// Update Manifest
let current_snap =
manifest
.edges
.entry(edge_type_name.to_string())
.or_insert(EdgeSnapshot {
version: 0,
count: 0,
lance_version: 0,
});
current_snap.version += 1;
current_snap.count += entries.len() as u64;
// LanceDB tables don't expose Lance version directly
current_snap.lance_version = 0;
// Note: No CSR invalidation needed. AdjacencyManager's overlay
// already has these edges via dual-write in insert_edge/delete_edge.
}
// 4. Per-label vertex table writes
// Iterate all labels that have either full-row OR partial-write
// data pending. A label may appear in only one of the two maps
// (e.g., all updates on this label were partial-only).
let all_label_ids: std::collections::HashSet<u16> = vertices_by_label
.keys()
.chain(partial_by_label.keys())
.chain(tombstones_by_label.keys())
.copied()
.collect();
for label_id in all_label_ids {
let vertices = vertices_by_label.remove(&label_id).unwrap_or_default();
let label_name = schema
.label_name_by_id(label_id)
.ok_or_else(|| anyhow!("Label ID {} not found", label_id))?;
let ds = self.storage.vertex_dataset(label_name)?;
// Collect inverted index updates before consuming vertices
// Maps: cfg.property -> (added, removed)
type InvertedUpdateMap = HashMap<String, (HashMap<Vid, Vec<String>>, HashSet<Vid>)>;
let mut inverted_updates: InvertedUpdateMap = HashMap::new();
for idx in &schema.indexes {
if let IndexDefinition::Inverted(cfg) = idx
&& cfg.label == label_name
{
let mut added: HashMap<Vid, Vec<String>> = HashMap::new();
let mut removed: HashSet<Vid> = HashSet::new();
for (vid, _labels, props, deleted, _version) in &vertices {
if *deleted {
removed.insert(*vid);
} else if let Some(prop_value) = props.get(&cfg.property) {
// Extract terms from the property value (List<String>)
if let Some(arr) = prop_value.as_array() {
let terms: Vec<String> = arr
.iter()
.filter_map(|v| v.as_str().map(ToString::to_string))
.collect();
if !terms.is_empty() {
added.insert(*vid, terms);
}
}
}
}
// Round-12 §B: tombstones no longer in `vertices`;
// pull them from `tombstones_by_label` for inverted
// index removal.
if let Some(tomb_rows) = tombstones_by_label.get(&label_id) {
for (vid, _) in tomb_rows {
removed.insert(*vid);
}
}
if !added.is_empty() || !removed.is_empty() {
inverted_updates.insert(cfg.property.clone(), (added, removed));
}
}
}
let mut v_data = Vec::new();
let mut d_data = Vec::new();
let mut ver_data = Vec::new();
for (vid, labels, props, deleted, version) in vertices {
v_data.push((vid, labels, props));
d_data.push(deleted);
ver_data.push(version);
}
let backend = self.storage.backend();
// Skip the full-row Append entirely if this label only has
// partial-write rows pending.
if !v_data.is_empty() {
let batch = ds.build_record_batch_with_timestamps(
&v_data,
&d_data,
&ver_data,
&schema,
Some(&vertex_created_at),
Some(&vertex_updated_at),
)?;
ds.write_batch(backend, batch, &schema).await?;
}
// Partial-column batch (Lance MergeInsert path). The flag
// gates whether the routing classified any VIDs as partial;
// outside the flag this collection is always empty so the
// call below is a cheap no-op.
if let Some(partial_rows) = partial_by_label.remove(&label_id)
&& !partial_rows.is_empty()
{
let touched_union: std::collections::HashSet<String> = partial_rows
.iter()
.flat_map(|(_, _, _, keys)| keys.iter().cloned())
.collect();
let pairs: Vec<(Vid, Properties)> = partial_rows
.iter()
.map(|(vid, props, _, _)| (*vid, props.clone()))
.collect();
let versions: Vec<u64> = partial_rows.iter().map(|(_, _, v, _)| *v).collect();
let partial_batch = ds.build_partial_record_batch(
&pairs,
&versions,
&touched_union,
&schema,
Some(&vertex_updated_at),
)?;
if partial_batch.num_rows() > 0 {
ds.merge_insert_batch(backend, partial_batch).await?;
}
}
// Tombstone batch (Round-12 §B): always MergeInsert with
// just `_vid`, `_deleted=true`, `_version`, `_updated_at`.
// No partial_lance_writes gating — tombstones never carry
// useful property payload to write. Captured tombstone vids
// also drive `remove_from_vid_labels_index` below.
let tombstone_rows = tombstones_by_label.remove(&label_id).unwrap_or_default();
if !tombstone_rows.is_empty() {
let tomb_batch =
ds.build_tombstone_partial_batch(&tombstone_rows, Some(&vertex_updated_at))?;
if tomb_batch.num_rows() > 0 {
ds.merge_insert_batch(backend, tomb_batch).await?;
}
}
ds.ensure_default_indexes(backend).await?;
// Update VidLabelsIndex (if enabled). v_data carries live
// vertices; tombstone removals come from the
// `tombstone_rows` captured above the MergeInsert call.
for ((vid, labels, _props), &deleted) in v_data.iter().zip(d_data.iter()) {
if deleted {
self.storage.remove_from_vid_labels_index(*vid);
} else {
self.storage.update_vid_labels_index(*vid, labels.clone());
}
}
for (vid, _) in &tombstone_rows {
self.storage.remove_from_vid_labels_index(*vid);
}
// Update Manifest
let current_snap =
manifest
.vertices
.entry(label_name.to_string())
.or_insert(LabelSnapshot {
version: 0,
count: 0,
lance_version: 0,
});
current_snap.version += 1;
current_snap.count += v_data.len() as u64;
// LanceDB tables don't expose Lance version directly
current_snap.lance_version = 0;
// Invalidate table cache to ensure next read picks up new version
self.storage.invalidate_table_cache(label_name);
// Apply inverted index updates incrementally
#[cfg(feature = "lance-backend")]
for idx in &schema.indexes {
if let IndexDefinition::Inverted(cfg) = idx
&& cfg.label == label_name
&& let Some((added, removed)) = inverted_updates.get(&cfg.property)
{
self.storage
.index_manager()
.update_inverted_index_incremental(cfg, added, removed)
.await?;
}
}
// Update UID index with new vertex mappings
// Collect (UniId, Vid) mappings from non-deleted vertices
#[cfg(feature = "lance-backend")]
{
let mut uid_mappings: Vec<(uni_common::core::id::UniId, Vid)> = Vec::new();
for (vid, _labels, props) in &v_data {
let ext_id = props.get("ext_id").and_then(|v| v.as_str());
let uid = crate::storage::vertex::VertexDataset::compute_vertex_uid(
label_name, ext_id, props,
);
uid_mappings.push((uid, *vid));
}
if !uid_mappings.is_empty()
&& let Ok(uid_index) = self.storage.uid_index(label_name)
{
uid_index.write_mapping(&uid_mappings).await?;
}
}
}
Ok(FlushOutcome {
manifest,
snapshot_id,
})
}
/// Composition entry that assumes the caller already holds `flush_lock`.
/// Runs rotate + stream + finalize_locked in sequence. Used by
/// [`Writer::flush_to_l1`] (acquires the lock first) and by
/// `commit_transaction_l0`'s post-merge auto-flush branch (which already
/// holds the lock from the commit critical section).
#[instrument(
skip(self),
fields(snapshot_id, mutations_count, size_bytes),
level = "info"
)]
async fn flush_inline_under_lock(&self, name: Option<String>) -> Result<String> {
let start = std::time::Instant::now();
let (initial_size, initial_count) = {
let l0_arc = self.l0_manager.get_current();
let l0 = l0_arc.read();
(l0.estimated_size, l0.mutation_count)
};
tracing::Span::current().record("size_bytes", initial_size);
tracing::Span::current().record("mutations_count", initial_count);
debug!("Starting L0 flush to L1");
// Phases A (WAL pre-flush), B (rotate), C (WAL handoff).
// FlushInProgressGuard lives on RotateOutput and stays alive for
// the full flush — including the finalize_locked call below.
let RotateOutput {
old_l0_arc,
wal_lsn,
current_version,
flush_in_progress_guard: _flush_guard,
} = self.flush_l0_rotate().await?;
// Phases D (L1 collect), E (orphan resolve), F (manifest seed),
// G (Lance writes). Builds the manifest but does NOT publish it.
let FlushOutcome {
manifest,
snapshot_id,
} = self
.flush_stream_l1(old_l0_arc.clone(), wal_lsn, current_version, name)
.await?;
// Phases H..S: publish manifest, complete_flush, WAL truncate,
// property cache clear, last_flush_time, metrics, l1_runs++,
// compaction trigger, index-rebuild scheduling, fork tick.
self.flush_finalize_locked(
old_l0_arc,
wal_lsn,
manifest,
snapshot_id,
initial_size,
initial_count,
start,
)
.await
}
/// Phases H..S of the flush: publish the manifest and run all
/// post-publish bookkeeping. Assumes the caller already holds
/// `flush_lock` — see [`Writer::flush_finalize_now`] for the
/// lock-acquiring variant used by the async finalize path.
#[allow(clippy::too_many_arguments)]
async fn flush_finalize_locked(
&self,
old_l0_arc: Arc<RwLock<L0Buffer>>,
wal_lsn: u64,
manifest: SnapshotManifest,
snapshot_id: String,
initial_size: usize,
initial_count: usize,
start: std::time::Instant,
) -> Result<String> {
Self::flush_finalize_body(
&self.shared_ctx(),
old_l0_arc,
wal_lsn,
manifest,
snapshot_id,
initial_size,
initial_count,
start,
)
.await
}
/// Phases H..S of the flush, lock-acquiring variant. Used by the
/// async-flush finalizer task (running on a spawned tokio task),
/// which holds neither `&self` nor `flush_lock`. Briefly re-acquires
/// `flush_lock` to serialize the publish boundary, then runs the
/// same body as `flush_finalize_locked` but over a SharedFlushCtx.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn flush_finalize_now(
shared: SharedFlushCtx,
old_l0_arc: Arc<RwLock<L0Buffer>>,
wal_lsn: u64,
manifest: SnapshotManifest,
snapshot_id: String,
initial_size: usize,
initial_count: usize,
start: std::time::Instant,
) -> Result<String> {
let _flush_lock_guard = shared.flush_lock.clone().lock_owned().await;
Self::flush_finalize_body(
&shared,
old_l0_arc,
wal_lsn,
manifest,
snapshot_id,
initial_size,
initial_count,
start,
)
.await
}
/// Shared body of `flush_finalize_locked` and `flush_finalize_now`.
/// Static over `SharedFlushCtx`; the caller is responsible for
/// holding `flush_lock`.
#[allow(clippy::too_many_arguments)]
async fn flush_finalize_body(
shared: &SharedFlushCtx,
old_l0_arc: Arc<RwLock<L0Buffer>>,
wal_lsn: u64,
mut manifest: SnapshotManifest,
snapshot_id: String,
initial_size: usize,
initial_count: usize,
start: std::time::Instant,
) -> Result<String> {
// Parent-snapshot fixup. The stream phase built `manifest` with
// parent_snapshot set from cached_manifest at stream time. If
// OTHER flushes (sync or async) have finalized since then,
// cached_manifest has advanced. Re-link this manifest to the
// current cached chain so we don't orphan their data when we
// overwrite cached_manifest below.
let current_parent_id = shared
.cached_manifest
.lock()
.as_ref()
.map(|m| m.snapshot_id.clone());
if current_parent_id.is_some() && manifest.parent_snapshot != current_parent_id {
manifest.parent_snapshot = current_parent_id;
metrics::counter!("uni_flush_parent_chain_fixups_total").increment(1);
}
// H. Publish manifest (body first, then pointer — recovery is
// idempotent if we crash between the two).
shared
.storage
.snapshot_manager()
.save_snapshot(&manifest)
.await?;
shared
.storage
.snapshot_manager()
.set_latest_snapshot(&manifest.snapshot_id)
.await?;
// I. Cache manifest for next flush to avoid re-reading from object store.
*shared.cached_manifest.lock() = Some(manifest.clone());
// J. Complete flush: remove old L0 from pending_flush. MUST happen
// BEFORE WAL truncation so min_pending_wal_lsn is accurate.
shared.l0_manager.complete_flush(&old_l0_arc);
// K. Truncate WAL up to the safe LSN.
let wal_handle = shared.l0_manager.get_current().read().wal.clone();
if let Some(w) = wal_handle {
let safe_lsn = shared
.l0_manager
.min_pending_wal_lsn()
.map(|min_pending| min_pending.min(wal_lsn))
.unwrap_or(wal_lsn);
w.truncate_before(safe_lsn).await?;
}
// L. Invalidate property cache after flush to prevent stale reads.
if let Some(ref pm) = shared.property_manager {
pm.clear_cache().await;
}
// M. Reset last flush time for time-based auto-flush.
*shared.last_flush_time.lock() = std::time::Instant::now();
info!(
snapshot_id,
mutations_count = initial_count,
size_bytes = initial_size,
"L0 flush to L1 completed successfully"
);
metrics::histogram!("uni_flush_duration_seconds").record(start.elapsed().as_secs_f64());
metrics::counter!("uni_flush_bytes_total").increment(initial_size as u64);
metrics::counter!("uni_flush_rows_total").increment(initial_count as u64);
// P. Increment flush generation counter for write throttling.
{
let mut status = uni_common::sync::acquire_mutex(
&shared.storage.compaction_status,
"compaction_status",
)?;
status.l1_runs += 1;
}
// Q. Trigger CSR compaction if enough frozen segments have accumulated.
let am = shared.adjacency_manager.clone();
if am.should_compact(shared.compaction_config.frozen_segments_compact_threshold) {
let previous_still_running = {
let guard = shared.compaction_handle.read();
guard.as_ref().is_some_and(|h| !h.is_finished())
};
if previous_still_running {
info!("Skipping compaction: previous compaction still in progress");
} else {
let handle = tokio::spawn(async move {
am.compact();
});
*shared.compaction_handle.write() = Some(handle);
}
}
// R. Post-flush: check if any indexes need rebuilding based on thresholds.
if shared.auto_rebuild_enabled
&& let Some(rebuild_mgr) = shared.index_rebuild_manager.get()
{
Self::schedule_index_rebuilds_if_needed_static(
&manifest,
rebuild_mgr.clone(),
shared.schema_manager.clone(),
shared.index_rebuild_config.clone(),
);
}
// S. Emit fork-fragment observability after a successful forked flush.
Self::tick_fork_fragment_observability_static(
shared.fork_id,
shared.fork_flush_count.clone(),
shared.fork_fragment_warn_fired.clone(),
shared.fork_fragment_warn_threshold,
);
Ok(snapshot_id)
}
/// Increment fork-flush bookkeeping and fire the fragment warn
/// once if the threshold is crossed.
///
/// Each flush typically appends ~1 fragment per touched dataset on
/// the fork's branches; without compaction (deferred to Phase 5)
/// long-lived heavy-write forks degrade. The flush count is a
/// proxy for actual fragment growth — reading
/// `Dataset::manifest().fragments.len()` per dataset would add a
/// per-flush object-store roundtrip on the hot commit path, which
/// is too costly for a purely observational guard rail.
///
/// No-op for primary writers (`fork_id == None`).
#[allow(dead_code)] // called by tests; production path uses _static
pub(crate) fn tick_fork_fragment_observability(&self) {
Self::tick_fork_fragment_observability_static(
self.fork_id,
self.fork_flush_count.clone(),
self.fork_fragment_warn_fired.clone(),
self.config.fork_fragment_warn_threshold,
);
}
/// Static variant of [`Writer::tick_fork_fragment_observability`].
/// Used by the async-flush finalize path, where we hold a
/// [`SharedFlushCtx`] bundle of Arcs rather than `&Writer`.
pub(crate) fn tick_fork_fragment_observability_static(
fork_id: Option<ForkId>,
fork_flush_count: Arc<AtomicU64>,
fork_fragment_warn_fired: Arc<AtomicBool>,
warn_threshold: usize,
) {
let Some(fork_id) = fork_id else { return };
// `Relaxed` is sufficient: observational counter, no synchronizes-with.
let new_count = fork_flush_count.fetch_add(1, Ordering::Relaxed) + 1;
let fork_label = fork_id.to_string();
metrics::gauge!(
"uni_fork_l1_flushes",
"fork" => fork_label.clone(),
)
.set(new_count as f64);
let threshold = warn_threshold as u64;
if !fork_fragment_warn_fired.load(Ordering::Relaxed)
&& threshold > 0
&& new_count >= threshold
{
fork_fragment_warn_fired.store(true, Ordering::Relaxed);
tracing::warn!(
fork = %fork_label,
flush_count = new_count,
threshold,
"fork has exceeded the L1 flush-count threshold; \
fork compaction is deferred to Phase 5 — consider \
drop+recreate or promotion to bound fragment growth"
);
}
}
/// Check rebuild thresholds and schedule background index rebuilds for
/// labels that exceed growth or age limits. Marks affected indexes as
/// `Stale` and spawns an async task to schedule the rebuild.
#[allow(dead_code)] // production path uses _static; kept as the
// documented instance entry point.
fn schedule_index_rebuilds_if_needed(
&self,
manifest: &SnapshotManifest,
rebuild_mgr: Arc<crate::storage::index_rebuild::IndexRebuildManager>,
) {
Self::schedule_index_rebuilds_if_needed_static(
manifest,
rebuild_mgr,
self.schema_manager.clone(),
self.config.index_rebuild.clone(),
);
}
/// Static variant of [`Writer::schedule_index_rebuilds_if_needed`].
/// Used by the async-flush finalize path, where we hold the
/// [`SchemaManager`] via `SharedFlushCtx` rather than `&Writer`.
pub(crate) fn schedule_index_rebuilds_if_needed_static(
manifest: &SnapshotManifest,
rebuild_mgr: Arc<crate::storage::index_rebuild::IndexRebuildManager>,
schema_manager: Arc<uni_common::core::schema::SchemaManager>,
index_rebuild_config: uni_common::config::IndexRebuildConfig,
) {
let checker =
crate::storage::index_rebuild::RebuildTriggerChecker::new(index_rebuild_config);
let schema = schema_manager.schema();
let labels = checker.labels_needing_rebuild(manifest, &schema.indexes);
if labels.is_empty() {
return;
}
// Mark affected indexes as Stale
for label in &labels {
for idx in &schema.indexes {
if idx.label() == label {
let _ = schema_manager.update_index_metadata(idx.name(), |m| {
m.status = uni_common::core::schema::IndexStatus::Stale;
});
}
}
}
tokio::spawn(async move {
if let Err(e) = rebuild_mgr.schedule(labels).await {
tracing::warn!("Failed to schedule index rebuild: {e}");
}
});
}
}
/// `FinalizeFn` implementation that the `FlushCoordinator` invokes from
/// its single-task finalizer loop. Unit struct on purpose: it must NOT
/// hold `Arc<Writer>` (that would create a reference cycle Writer ->
/// FlushCoordinator -> Arc<dyn FinalizeFn> -> Writer). All state needed
/// for finalize travels in via `SharedFlushCtx`.
pub(crate) struct WriterFinalizer;
impl FinalizeFn for WriterFinalizer {
fn finalize<'a>(
&'a self,
rotated: RotatedFlush,
outcome: AsyncFlushOutcome,
shared: SharedFlushCtx,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String>> + Send + 'a>> {
Box::pin(async move {
// Read initial_size / initial_count from the rotated L0 so
// we don't have to plumb them through the coordinator
// submission. The buffer is still alive in pending_flush
// until `complete_flush` (J) below pops it.
let (initial_size, initial_count) = {
let l0 = rotated.old_l0_arc.read();
(l0.estimated_size, l0.mutation_count)
};
let result = Writer::flush_finalize_now(
shared,
rotated.old_l0_arc.clone(),
rotated.wal_lsn,
outcome.new_manifest,
outcome.snapshot_id,
initial_size,
initial_count,
std::time::Instant::now(),
)
.await;
// `rotated` (permit + flush_in_progress_guard) drops here.
drop(rotated.permit);
result
})
}
fn finalize_failure<'a>(
&'a self,
rotated: RotatedFlush,
err: anyhow::Error,
_shared: SharedFlushCtx,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Error> + Send + 'a>> {
Box::pin(async move {
tracing::warn!(
error = %err,
seq = rotated.seq,
"async flush stream failed; old L0 remains in pending_flush, \
WAL retains its data, recovery via WAL replay on restart"
);
metrics::counter!("uni_flush_failures_total").increment(1);
// Permit + guard drop here so back-pressure releases even on
// failure.
drop(rotated.permit);
err
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
/// Test that commit_transaction writes mutations to WAL before merging to main L0.
/// This verifies fix for issue #137 (transaction commit atomicity).
#[tokio::test]
async fn test_commit_transaction_wal_before_merge() -> Result<()> {
use crate::runtime::wal::WriteAheadLog;
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let path = dir.path().to_str().unwrap();
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
let _label_id = schema_manager.add_label("Test")?;
schema_manager.save().await?;
let storage = Arc::new(StorageManager::new(path, schema_manager.clone()).await?);
// Create WAL for main L0
let wal_path = ObjectStorePath::from("wal");
let wal = Arc::new(WriteAheadLog::new(store.clone(), wal_path));
let writer = Writer::new_with_config(
storage.clone(),
schema_manager.clone(),
1,
UniConfig::default(),
Some(wal),
None,
)
.await?;
// Begin transaction — create a transaction L0
let tx_l0 = writer.create_transaction_l0();
// Insert data in transaction
let vid_a = writer.next_vid().await?;
let vid_b = writer.next_vid().await?;
let mut props = std::collections::HashMap::new();
props.insert("test".to_string(), Value::String("data".to_string()));
writer
.insert_vertex_with_labels(vid_a, props.clone(), &["Test".to_string()], Some(&tx_l0))
.await?;
writer
.insert_vertex_with_labels(
vid_b,
std::collections::HashMap::new(),
&["Test".to_string()],
Some(&tx_l0),
)
.await?;
let eid = writer.next_eid(1).await?;
writer
.insert_edge(
vid_a,
vid_b,
1,
eid,
std::collections::HashMap::new(),
None,
Some(&tx_l0),
)
.await?;
// Get WAL before commit
let l0 = writer.l0_manager.get_current();
let wal = l0.read().wal.clone().expect("Main L0 should have WAL");
let mutations_before = wal.replay().await?;
let count_before = mutations_before.len();
// Commit transaction - this should write to WAL first
let writer = Arc::new(writer);
writer.commit_transaction_l0(tx_l0).await?;
// Verify WAL has the new mutations
let mutations_after = wal.replay().await?;
assert!(
mutations_after.len() > count_before,
"WAL should contain transaction mutations after commit"
);
// Verify mutations are in correct order: vertices first, then edges
let new_mutations: Vec<_> = mutations_after.into_iter().skip(count_before).collect();
let mut saw_vertex_a = false;
let mut saw_vertex_b = false;
let mut saw_edge = false;
for mutation in &new_mutations {
match mutation {
crate::runtime::wal::Mutation::InsertVertex { vid, .. } => {
if *vid == vid_a {
saw_vertex_a = true;
}
if *vid == vid_b {
saw_vertex_b = true;
}
// Vertices should come before edges
assert!(!saw_edge, "Vertices should be logged to WAL before edges");
}
crate::runtime::wal::Mutation::InsertEdge { eid: e, .. } => {
if *e == eid {
saw_edge = true;
}
// Edges should come after vertices
assert!(
saw_vertex_a && saw_vertex_b,
"Edge should be logged after both vertices"
);
}
_ => {}
}
}
assert!(saw_vertex_a, "Vertex A should be in WAL");
assert!(saw_vertex_b, "Vertex B should be in WAL");
assert!(saw_edge, "Edge should be in WAL");
// Verify data is also in main L0
let l0_read = l0.read();
assert!(
l0_read.vertex_properties.contains_key(&vid_a),
"Vertex A should be in main L0"
);
assert!(
l0_read.vertex_properties.contains_key(&vid_b),
"Vertex B should be in main L0"
);
assert!(
l0_read.edge_endpoints.contains_key(&eid),
"Edge should be in main L0"
);
Ok(())
}
/// Test that failed WAL flush leaves transaction intact for retry or rollback.
#[tokio::test]
async fn test_commit_transaction_wal_failure_rollback() -> Result<()> {
use crate::runtime::wal::WriteAheadLog;
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let path = dir.path().to_str().unwrap();
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
let _label_id = schema_manager.add_label("Test")?;
let _baseline_label_id = schema_manager.add_label("Baseline")?;
let _txdata_label_id = schema_manager.add_label("TxData")?;
schema_manager.save().await?;
let storage = Arc::new(StorageManager::new(path, schema_manager.clone()).await?);
// Create WAL for main L0
let wal_path = ObjectStorePath::from("wal");
let wal = Arc::new(WriteAheadLog::new(store.clone(), wal_path));
let writer = Writer::new_with_config(
storage.clone(),
schema_manager.clone(),
1,
UniConfig::default(),
Some(wal),
None,
)
.await?;
// Insert baseline data (outside transaction)
let baseline_vid = writer.next_vid().await?;
writer
.insert_vertex_with_labels(
baseline_vid,
[("baseline".to_string(), Value::Bool(true))]
.into_iter()
.collect(),
&["Baseline".to_string()],
None,
)
.await?;
// Begin transaction — create a transaction L0
let tx_l0 = writer.create_transaction_l0();
// Insert data in transaction
let tx_vid = writer.next_vid().await?;
writer
.insert_vertex_with_labels(
tx_vid,
[("tx_data".to_string(), Value::Bool(true))]
.into_iter()
.collect(),
&["TxData".to_string()],
Some(&tx_l0),
)
.await?;
// Capture main L0 state before rollback
let l0 = writer.l0_manager.get_current();
let vertex_count_before = l0.read().vertex_properties.len();
// Rollback transaction (simulating what would happen after WAL flush failure)
drop(tx_l0);
// Verify main L0 is unchanged
let vertex_count_after = l0.read().vertex_properties.len();
assert_eq!(
vertex_count_before, vertex_count_after,
"Main L0 should not change after rollback"
);
// Baseline should still be present
assert!(
l0.read().vertex_properties.contains_key(&baseline_vid),
"Baseline data should remain"
);
// Transaction data should NOT be in main L0
assert!(
!l0.read().vertex_properties.contains_key(&tx_vid),
"Transaction data should not be in main L0 after rollback"
);
Ok(())
}
/// Test that batch insert with shared labels does not clone labels per vertex.
/// This verifies fix for issue #161 (redundant label cloning).
#[tokio::test]
async fn test_batch_insert_shared_labels() -> Result<()> {
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let path = dir.path().to_str().unwrap();
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
let _label_id = schema_manager.add_label("Person")?;
schema_manager.save().await?;
let storage = Arc::new(StorageManager::new(path, schema_manager.clone()).await?);
let writer = Writer::new(storage.clone(), schema_manager.clone(), 1).await?;
// Shared labels - should not be cloned per vertex
let labels = &["Person".to_string()];
// Insert batch of vertices with same labels
let mut vids = Vec::new();
for i in 0..100 {
let vid = writer.next_vid().await?;
let mut props = std::collections::HashMap::new();
props.insert("id".to_string(), Value::Int(i));
writer
.insert_vertex_with_labels(vid, props, labels, None)
.await?;
vids.push(vid);
}
// Verify all vertices have the correct labels
let l0 = writer.l0_manager.get_current();
for vid in vids {
let l0_guard = l0.read();
let vertex_labels = l0_guard.vertex_labels.get(&vid);
assert!(vertex_labels.is_some(), "Vertex should have labels");
assert_eq!(
vertex_labels.unwrap(),
&vec!["Person".to_string()],
"Labels should match"
);
}
Ok(())
}
/// Test that estimated_size tracks mutations correctly and approximates size_bytes().
/// This verifies fix for issue #147 (O(V+E) size_bytes() in metrics).
#[tokio::test]
async fn test_estimated_size_tracks_mutations() -> Result<()> {
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let path = dir.path().to_str().unwrap();
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
let _label_id = schema_manager.add_label("Test")?;
schema_manager.save().await?;
let storage = Arc::new(StorageManager::new(path, schema_manager.clone()).await?);
let writer = Writer::new(storage.clone(), schema_manager.clone(), 1).await?;
let l0 = writer.l0_manager.get_current();
// Initial state should be empty
let initial_estimated = l0.read().estimated_size;
let initial_actual = l0.read().size_bytes();
assert_eq!(initial_estimated, 0, "Initial estimated_size should be 0");
assert_eq!(initial_actual, 0, "Initial size_bytes should be 0");
// Insert vertices with properties
let mut vids = Vec::new();
for i in 0..10 {
let vid = writer.next_vid().await?;
let mut props = std::collections::HashMap::new();
props.insert("name".to_string(), Value::String(format!("vertex_{}", i)));
props.insert("index".to_string(), Value::Int(i));
writer
.insert_vertex_with_labels(vid, props, &[], None)
.await?;
vids.push(vid);
}
// Verify estimated_size grew
let after_vertices_estimated = l0.read().estimated_size;
let after_vertices_actual = l0.read().size_bytes();
assert!(
after_vertices_estimated > 0,
"estimated_size should grow after insertions"
);
// Verify estimated_size is within reasonable bounds of actual size (within 2x)
let ratio = after_vertices_estimated as f64 / after_vertices_actual as f64;
assert!(
(0.5..=2.0).contains(&ratio),
"estimated_size ({}) should be within 2x of size_bytes ({}), ratio: {}",
after_vertices_estimated,
after_vertices_actual,
ratio
);
// Insert edges with a simple edge type
let edge_type = 1u32;
for i in 0..9 {
let eid = writer.next_eid(edge_type).await?;
writer
.insert_edge(
vids[i],
vids[i + 1],
edge_type,
eid,
std::collections::HashMap::new(),
Some("NEXT".to_string()),
None,
)
.await?;
}
// Verify estimated_size grew further
let after_edges_estimated = l0.read().estimated_size;
let after_edges_actual = l0.read().size_bytes();
assert!(
after_edges_estimated > after_vertices_estimated,
"estimated_size should grow after edge insertions"
);
// Verify still within reasonable bounds
let ratio = after_edges_estimated as f64 / after_edges_actual as f64;
assert!(
(0.5..=2.0).contains(&ratio),
"estimated_size ({}) should be within 2x of size_bytes ({}), ratio: {}",
after_edges_estimated,
after_edges_actual,
ratio
);
Ok(())
}
/// Test that flushing WAL on a writer with no mutations succeeds cleanly.
#[tokio::test]
async fn test_flush_wal_empty_l0_is_noop() -> Result<()> {
use crate::runtime::wal::WriteAheadLog;
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let path = dir.path().to_str().unwrap();
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
schema_manager.save().await?;
let storage = Arc::new(StorageManager::new(path, schema_manager.clone()).await?);
let wal_path = ObjectStorePath::from("wal");
let wal = Arc::new(WriteAheadLog::new(store.clone(), wal_path));
let writer = Writer::new_with_config(
storage.clone(),
schema_manager.clone(),
1,
UniConfig::default(),
Some(wal.clone()),
None,
)
.await?;
// Flush with no mutations — should succeed cleanly
let lsn = writer.flush_wal().await?;
// LSN should be 0 or 1 (no real mutations flushed)
assert!(lsn <= 1, "Empty flush should produce low LSN, got {}", lsn);
Ok(())
}
/// Test that transaction data does not leak into main L0 without commit.
#[tokio::test]
async fn test_transaction_isolation_without_commit() -> Result<()> {
use crate::runtime::wal::WriteAheadLog;
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let path = dir.path().to_str().unwrap();
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
let _label_id = schema_manager.add_label("Person")?;
schema_manager.save().await?;
let storage = Arc::new(StorageManager::new(path, schema_manager.clone()).await?);
let wal_path = ObjectStorePath::from("wal");
let wal = Arc::new(WriteAheadLog::new(store.clone(), wal_path));
let writer = Writer::new_with_config(
storage.clone(),
schema_manager.clone(),
1,
UniConfig::default(),
Some(wal),
None,
)
.await?;
// Create transaction L0
let tx_l0 = writer.create_transaction_l0();
// Insert vertex into transaction L0
let vid = writer.next_vid().await?;
writer
.insert_vertex_with_labels(
vid,
[("name".to_string(), Value::String("Ghost".to_string()))]
.into_iter()
.collect(),
&["Person".to_string()],
Some(&tx_l0),
)
.await?;
// Verify data is in transaction L0
assert!(
tx_l0.read().vertex_properties.contains_key(&vid),
"Transaction L0 should contain the vertex"
);
// Verify data is NOT in main L0
let main_l0 = writer.l0_manager.get_current();
assert!(
!main_l0.read().vertex_properties.contains_key(&vid),
"Main L0 should NOT contain uncommitted transaction data"
);
// Drop transaction without committing — data should be lost
drop(tx_l0);
// Main L0 still should not have it
assert!(
!main_l0.read().vertex_properties.contains_key(&vid),
"Main L0 should remain clean after dropped transaction"
);
Ok(())
}
/// Phase 2 Day 12: the fork-fragment warn fires exactly once when
/// the flush count crosses the configured threshold and stays
/// silent on subsequent flushes for the lifetime of the writer.
/// Primary writers (`fork_id == None`) never fire it.
///
/// Tested directly against `tick_fork_fragment_observability` so
/// the contract is locked in independently of the broader
/// `flush_to_l1` path (the end-to-end fork-flush path is blocked
/// on Day 10's on-the-fly schema overlay growth).
#[tokio::test]
async fn fork_fragment_warn_fires_once_then_silences() -> Result<()> {
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::fork::ForkId;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
let storage = Arc::new(
StorageManager::new(dir.path().to_str().unwrap(), schema_manager.clone()).await?,
);
let config = UniConfig {
fork_fragment_warn_threshold: 3,
..Default::default()
};
let mut writer =
Writer::new_with_config(storage, schema_manager, 1, config, None, None).await?;
// Primary path: never fires.
for _ in 0..10 {
writer.tick_fork_fragment_observability();
}
assert!(!writer.fork_fragment_warn_fired.load(Ordering::Relaxed));
assert_eq!(writer.fork_flush_count.load(Ordering::Relaxed), 0);
// Fork path: tag and tick. Below threshold → no fire.
writer.fork_id = Some(ForkId::new());
writer.tick_fork_fragment_observability();
writer.tick_fork_fragment_observability();
assert!(!writer.fork_fragment_warn_fired.load(Ordering::Relaxed));
assert_eq!(writer.fork_flush_count.load(Ordering::Relaxed), 2);
// Crossing threshold → fires once.
writer.tick_fork_fragment_observability();
assert!(writer.fork_fragment_warn_fired.load(Ordering::Relaxed));
assert_eq!(writer.fork_flush_count.load(Ordering::Relaxed), 3);
// Subsequent ticks bump the gauge but do not re-fire.
let fired_after = writer.fork_fragment_warn_fired.load(Ordering::Relaxed);
for _ in 0..5 {
writer.tick_fork_fragment_observability();
}
assert_eq!(writer.fork_flush_count.load(Ordering::Relaxed), 8);
assert_eq!(
writer.fork_fragment_warn_fired.load(Ordering::Relaxed),
fired_after
);
Ok(())
}
/// The hot-path mutators must not write to any `Writer` struct field.
/// Phase 2 of the refactor
/// gave them `&self` receivers, which the compiler enforces against
/// direct `self.x = y` assignment — but interior-mutable writes
/// (Mutex/Atomic/OnceLock) still compile. This regression test snapshots
/// every potentially-writable field, calls each hot-path mutator, and
/// asserts no field changed.
///
/// Cold-path methods (`flush_to_l1`, `commit_transaction_l0`,
/// `tick_fork_fragment_observability`) DO mutate fields by design and
/// are intentionally out of scope here.
#[tokio::test]
async fn hot_path_mutators_do_not_change_writer_fields() -> Result<()> {
use crate::storage::manager::StorageManager;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectStorePath;
use uni_common::core::schema::SchemaManager;
let dir = tempdir()?;
let store = Arc::new(LocalFileSystem::new_with_prefix(dir.path())?);
let schema_path = ObjectStorePath::from("schema.json");
let schema_manager =
Arc::new(SchemaManager::load_from_store(store.clone(), &schema_path).await?);
schema_manager.add_label("Person")?;
schema_manager.save().await?;
let storage = Arc::new(
StorageManager::new(dir.path().to_str().unwrap(), schema_manager.clone()).await?,
);
let writer =
Writer::new_with_config(storage, schema_manager, 1, UniConfig::default(), None, None)
.await?;
/// Captures every `Writer` field that *could* be written by a
/// hot-path mutator (i.e., every non-Arc, non-immutable-after-
/// construction field). Arc'd substructures (`l0_manager`,
/// `storage`, etc.) are intentionally not checked — they are
/// re-pointed only at construction.
#[derive(Debug, PartialEq)]
struct Snapshot {
last_flush_time: std::time::Instant,
cached_manifest_some: bool,
fork_flush_count: u64,
fork_fragment_warn_fired: bool,
xervo_runtime_some: bool,
index_rebuild_manager_some: bool,
fork_id: Option<ForkId>,
}
fn snap(w: &Writer) -> Snapshot {
Snapshot {
last_flush_time: *w.last_flush_time.lock(),
cached_manifest_some: w.cached_manifest.lock().is_some(),
fork_flush_count: w.fork_flush_count.load(Ordering::Relaxed),
fork_fragment_warn_fired: w.fork_fragment_warn_fired.load(Ordering::Relaxed),
xervo_runtime_some: w.xervo_runtime.get().is_some(),
index_rebuild_manager_some: w.index_rebuild_manager.get().is_some(),
fork_id: w.fork_id,
}
}
// 1. insert_vertex_with_labels
let before = snap(&writer);
let vid = writer.next_vid().await?;
writer
.insert_vertex_with_labels(vid, Properties::new(), &["Person".to_string()], None)
.await?;
assert_eq!(
snap(&writer),
before,
"insert_vertex_with_labels mutated a Writer field"
);
// 2. insert_vertices_batch
let before = snap(&writer);
let vids = writer.allocate_vids(2).await?;
writer
.insert_vertices_batch(
vids,
vec![Properties::new(), Properties::new()],
vec!["Person".into()],
None,
)
.await?;
assert_eq!(
snap(&writer),
before,
"insert_vertices_batch mutated a Writer field"
);
// 3. delete_vertex
let before = snap(&writer);
writer.delete_vertex(vid, None, None).await?;
assert_eq!(
snap(&writer),
before,
"delete_vertex mutated a Writer field"
);
// (insert_edge / delete_edge are skipped here: their fixture cost is
// disproportionate to the audit's marginal value, and the same
// structural argument plus the compiler-enforced `&self` covers them.)
Ok(())
}
}