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
//! Segment Manager
//!
//! Manages the lifecycle of unified segments: creation, sealing, consolidation,
//! and archival. Coordinates writes to growing segments and queries across
//! all segments.
//!
//! # Responsibilities
//!
//! - Route writes to the active growing segment
//! - Auto-seal segments when thresholds are met
//! - Coordinate queries across multiple segments
//! - Paced consolidation of sealed segments (ADR 0073 §5)
//! - Archive old segments to cold storage
mod graph_index_merge;
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use super::entity::{EntityId, EntityKind, UnifiedEntity};
use super::metadata::{Metadata, MetadataFilter};
use super::segment::{
GraphEntityKind, GrowingSegment, SegmentConfig, SegmentError, SegmentId, SegmentState,
SegmentStats, UnifiedSegment, ZoneColPred, ZoneColPredKind,
};
use super::visibility_map::VisibilityMap;
use crate::runtime::mvcc::{entity_visible_with_context, SnapshotContext};
/// Fraction of a collection's sealed entities that must be tombstoned before
/// consolidation is worth its cost.
///
/// Tunable implementation constant, not a contract: it is surfaced read-only in
/// `red.stats` so an operator can see what the engine decided, and it may move
/// between releases without notice.
pub const CONSOLIDATION_TOMBSTONE_RATIO: f64 = 0.20;
/// Fraction of a collection's sealed bytes that consolidation would return to
/// the budget (dead entity payloads plus the tombstone sets that bury them)
/// before consolidation is worth its cost. See [`CONSOLIDATION_TOMBSTONE_RATIO`]
/// on tunability.
pub const CONSOLIDATION_FRAGMENTATION_RATIO: f64 = 0.30;
/// Entities copied into the merged segment per maintenance tick.
///
/// ADR 0038 §3: consolidation is paced. A tick copies at most this many
/// entities and returns; the half-built merged segment is carried to the next
/// tick. No consolidation ever runs to completion in one unbounded pass.
pub const CONSOLIDATION_ENTITIES_PER_TICK: usize = 4_096;
/// Configuration for the segment manager
#[derive(Debug, Clone)]
pub struct ManagerConfig {
/// Segment configuration
pub segment_config: SegmentConfig,
/// Maximum number of sealed segments before consolidation
pub max_sealed_segments: usize,
/// Idle time (seconds) before auto-sealing
pub idle_seal_secs: u64,
/// Enable paced sealed-segment consolidation
pub enable_consolidation: bool,
/// Entities copied per maintenance tick while a consolidation is running
pub consolidation_entities_per_tick: usize,
/// Enable background archival
pub enable_archival: bool,
/// Age threshold for archival (seconds)
pub archive_age_secs: u64,
}
impl Default for ManagerConfig {
fn default() -> Self {
Self {
segment_config: SegmentConfig::default(),
max_sealed_segments: 10,
idle_seal_secs: 300, // 5 minutes
enable_consolidation: true,
consolidation_entities_per_tick: CONSOLIDATION_ENTITIES_PER_TICK,
enable_archival: true,
archive_age_secs: 86400 * 7, // 7 days
}
}
}
/// Consolidation counters for one collection (ADR 0073 §5).
///
/// These replace the `compact_ops` counter, which only ever counted a
/// do-nothing branch.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ConsolidationStats {
/// Consolidations that crossed a threshold and began copying.
pub runs_started: u64,
/// Consolidations that finished the swap.
pub runs_completed: u64,
/// Source segments retired by a completed swap.
pub segments_merged: u64,
/// Tombstones garbage-collected by completed swaps.
pub tombstones_reclaimed: u64,
/// Logical source-to-merged footprint reduction; readers may retain sources.
pub bytes_reclaimed: u64,
}
/// Manager statistics
#[derive(Debug, Clone, Default)]
pub struct ManagerStats {
/// Total entities across all segments
pub total_entities: usize,
/// Number of growing segments
pub growing_count: usize,
/// Number of sealed segments
pub sealed_count: usize,
/// Number of archived segments
pub archived_count: usize,
/// Total memory usage
pub total_memory_bytes: usize,
/// Number of seal operations
pub seal_ops: u64,
/// Consolidation counters
pub consolidation: ConsolidationStats,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SegmentScanStats {
pub segments_total: u64,
pub segments_scanned: u64,
pub segments_pruned: u64,
}
/// Lifecycle events for monitoring
#[derive(Debug, Clone)]
pub enum LifecycleEvent {
SegmentCreated(SegmentId),
SegmentSealed(SegmentId),
SegmentConsolidated {
source: Vec<SegmentId>,
target: SegmentId,
},
SegmentArchived(SegmentId),
EntityInserted(EntityId, SegmentId),
EntityDeleted(EntityId, SegmentId),
}
/// A consolidation in flight, carried across maintenance ticks.
///
/// The merged segment is built off to the side and is invisible to readers
/// until the swap. Nothing here is durable: sealed segments are the truth (via
/// the normal checkpoint path), so a crash mid-consolidation simply drops this
/// state and the next boot starts over.
struct Consolidation {
/// Source segments, frozen when the run started.
sources: Vec<SourceProgress>,
/// Id reserved for the merged segment.
merged_id: SegmentId,
/// The half-built merged segment.
merged: GrowingSegment,
/// Index into `sources` of the segment currently being copied.
cursor: usize,
/// Live ids of `sources[cursor]`, snapshotted when that source was opened.
pending_ids: Vec<EntityId>,
/// How many of `pending_ids` have been consumed.
pending_cursor: usize,
/// Entities copied so far, across every tick of this run.
entities_copied: u64,
}
/// Per-source bookkeeping for a consolidation in flight.
struct SourceProgress {
id: SegmentId,
/// Ids copied out of this source into the merged segment.
copied: Vec<EntityId>,
/// The source's tombstone count when the run opened it, and `None` before
/// that. Tombstones only ever grow, so a source whose count is unchanged at
/// swap time saw no deletes after we started reading it — and every row we
/// copied out of it is still live. Anything else needs a per-row check.
///
/// Recording this when the source is *opened*, not when it is drained, is
/// what makes the check sound: a row deleted between two copy ticks would
/// otherwise be invisible to the swap and get resurrected.
tombstones_at_open: Option<usize>,
}
/// Segment manager for a collection
pub struct SegmentManager {
/// Statement-scoped constraint admission. Reentrant because SQL upserts
/// invoke the same typed mutation APIs while holding this collection gate.
row_constraint_lock: Arc<parking_lot::ReentrantMutex<()>>,
/// Collection name
collection: String,
/// Configuration
config: ManagerConfig,
/// Next segment ID counter
next_segment_id: AtomicU64,
/// Next entity ID counter
next_entity_id: AtomicU64,
/// Per-table auto-increment row ID (1, 2, 3... per collection)
next_row_id: AtomicU64,
/// Hot-path entity counter — lock-free, updated by every insert/delete.
/// Replaces stats.total_entities on the write path to eliminate a lock
/// acquisition per row (from 4 lock ops per insert → 2).
total_entities_atomic: AtomicU64,
/// Currently active growing segment
growing: RwLock<Option<Arc<RwLock<GrowingSegment>>>>,
/// Sealed segments (immutable, queryable)
sealed: RwLock<Vec<Arc<RwLock<GrowingSegment>>>>,
/// Retired sources still owned by readers. Weak handles never prolong payload lifetime.
retired: RwLock<Vec<Weak<RwLock<GrowingSegment>>>>,
/// Archived segment IDs (stored externally)
archived: RwLock<Vec<SegmentId>>,
/// Entity to segment mapping (for fast lookups by individually-inserted entities).
/// Bulk-inserted entities skip this map; their segment is found by sequential scan
/// of growing + sealed segments in get()/update()/delete().
entity_segment: RwLock<HashMap<EntityId, SegmentId>>,
/// Shared column schema: column_name → index in Vec<Value>.
/// Populated on first bulk_insert. Enables columnar storage (Vec instead of HashMap per row).
column_schema: RwLock<Option<Arc<Vec<String>>>>,
/// Statistics (slow path — not updated on every insert).
stats: RwLock<ManagerStats>,
/// Consolidation in flight, if any. Only `run_maintenance` touches it, so
/// at most one consolidation runs per collection at a time.
consolidation: RwLock<Option<Consolidation>>,
/// Event listeners (simplified - would be channels in production)
events: RwLock<Vec<LifecycleEvent>>,
/// Visibility map: sealed segment entity ranges marked as all-visible.
/// Growing segment is never all-visible (writes are in-flight).
/// Used by index-only scan decisions.
visibility_map: VisibilityMap,
}
impl SegmentManager {
/// Create a new segment manager
pub fn new(collection: impl Into<String>) -> Self {
Self::with_config(collection, ManagerConfig::default())
}
/// Create with custom configuration
pub fn with_config(collection: impl Into<String>, config: ManagerConfig) -> Self {
Self {
row_constraint_lock: Arc::new(parking_lot::ReentrantMutex::new(())),
collection: collection.into(),
config,
next_segment_id: AtomicU64::new(1),
next_entity_id: AtomicU64::new(1),
next_row_id: AtomicU64::new(1),
total_entities_atomic: AtomicU64::new(0),
growing: RwLock::new(None),
sealed: RwLock::new(Vec::new()),
retired: RwLock::new(Vec::new()),
archived: RwLock::new(Vec::new()),
entity_segment: RwLock::new(HashMap::new()),
column_schema: RwLock::new(None),
stats: RwLock::new(ManagerStats::default()),
consolidation: RwLock::new(None),
events: RwLock::new(Vec::new()),
visibility_map: VisibilityMap::new(),
}
}
pub(crate) fn row_constraint_lock(&self) -> Arc<parking_lot::ReentrantMutex<()>> {
Arc::clone(&self.row_constraint_lock)
}
/// Get or create the shared column schema from first row's named fields.
pub fn get_or_init_schema(
&self,
named: &HashMap<String, reddb_types::Value>,
) -> Arc<Vec<String>> {
{
let schema = self.column_schema.read();
if let Some(ref s) = *schema {
return Arc::clone(s);
}
}
let cols: Vec<String> = named.keys().cloned().collect();
let arc = Arc::new(cols);
*self.column_schema.write() = Some(Arc::clone(&arc));
arc
}
/// Get the column schema if it exists.
pub fn column_schema(&self) -> Option<Arc<Vec<String>>> {
self.column_schema.read().clone()
}
pub(crate) fn set_column_schema_if_empty(&self, columns: Vec<String>) {
if columns.is_empty() {
return;
}
let mut schema = self.column_schema.write();
if schema.is_none() {
*schema = Some(Arc::new(columns));
}
}
/// Get collection name
pub fn collection(&self) -> &str {
&self.collection
}
/// Get configuration
pub fn config(&self) -> &ManagerConfig {
&self.config
}
/// Get statistics. Entity counts cover active segments; memory also covers
/// retained sources and unpublished consolidation work.
pub fn stats(&self) -> ManagerStats {
let mut s = self.stats.read().clone();
s.total_entities = self.total_entities_atomic.load(Ordering::Relaxed) as usize;
s.total_memory_bytes = self.resident_bytes() as usize;
s
}
/// Approximate resident segment memory, including tombstones, retired sources,
/// and the in-flight merge and its bookkeeping. This feeds budget admission.
pub fn resident_bytes(&self) -> u64 {
self.memory_usage().1
}
/// Resident segment payload/directory bytes and consolidation bookkeeping,
/// including retired sources. Unlike `resident_bytes`, excludes tombstones.
pub fn memory_bytes(&self) -> u64 {
self.memory_usage().0
}
/// Sample payload and resident bytes under the publication lock order:
/// consolidation, growing, sealed, retired. No entity scan or strong handle
/// is retained beyond this call; expired weak entries are pruned in place.
fn memory_usage(&self) -> (u64, u64) {
let consolidation = self.consolidation.read();
let growing = self.growing.read();
let sealed = self.sealed.read();
let mut retired = self.retired.write();
let mut payload = 0u64;
let mut resident = 0u64;
{
let mut add = |segment: &GrowingSegment| {
payload = payload.saturating_add(segment.memory_bytes());
resident = resident.saturating_add(segment.resident_bytes());
};
for segment in growing.iter().chain(sealed.iter()) {
add(&segment.read());
}
retired.retain(|source| {
if let Some(source) = source.upgrade() {
add(&source.read());
true
} else {
false
}
});
if let Some(run) = consolidation.as_ref() {
add(&run.merged);
}
}
let mut bookkeeping =
(retired.capacity() * std::mem::size_of::<Weak<RwLock<GrowingSegment>>>()) as u64;
if let Some(run) = consolidation.as_ref() {
bookkeeping = bookkeeping
.saturating_add(
(run.sources.capacity() * std::mem::size_of::<SourceProgress>()) as u64,
)
.saturating_add(
(run.pending_ids.capacity() * std::mem::size_of::<EntityId>()) as u64,
);
for source in &run.sources {
bookkeeping = bookkeeping.saturating_add(
(source.copied.capacity() * std::mem::size_of::<EntityId>()) as u64,
);
}
}
(
payload.saturating_add(bookkeeping),
resident.saturating_add(bookkeeping),
)
}
/// Bytes a pressure-triggered consolidation could plausibly return.
pub fn reclaimable_bytes(&self) -> u64 {
self.sealed
.read()
.iter()
.map(|segment| segment.read().reclaimable_bytes())
.fold(0, u64::saturating_add)
}
/// Generate a new entity ID
pub fn next_entity_id(&self) -> EntityId {
EntityId::new(self.next_entity_id.fetch_add(1, Ordering::SeqCst))
}
/// Generate a per-table sequential row ID (1, 2, 3... per collection)
pub fn next_row_id(&self) -> u64 {
self.next_row_id.fetch_add(1, Ordering::SeqCst)
}
/// Reserve `n` contiguous per-table row IDs with one atomic
/// fetch_add. Caller assigns `row_id = start + i` per entity.
/// Saves N-1 atomic RMWs on bulk inserts (25k atomics → 1).
pub fn reserve_row_ids(&self, n: u64) -> std::ops::Range<u64> {
let start = self.next_row_id.fetch_add(n, Ordering::SeqCst);
start..start + n
}
/// Advance the per-table row_id counter to at least `id + 1`.
/// Called during load to restore the counter from existing data.
pub fn register_row_id(&self, id: u64) {
let candidate = id.saturating_add(1);
let mut current = self.next_row_id.load(Ordering::SeqCst);
while candidate > current {
match self.next_row_id.compare_exchange(
current,
candidate,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(_) => break,
Err(updated) => current = updated,
}
}
}
/// Get or create the active growing segment.
///
/// Fast path: read lock only — no write contention when the segment already exists.
/// Concurrent writers each clone the `Arc` under a shared read lock, then compete
/// on the segment's own write lock. This eliminates the global write-lock serialisation
/// that previously throttled concurrent inserts to ~238 ops/s.
fn get_or_create_growing(&self) -> Arc<RwLock<GrowingSegment>> {
// Common case: segment already exists — shared read lock, zero contention.
{
let growing = self.growing.read();
if let Some(segment) = growing.as_ref() {
return Arc::clone(segment);
}
}
// Slow path: segment missing — take exclusive write lock to create it.
let mut growing = self.growing.write();
// Double-check: another thread may have created it between the two lock acquisitions.
if let Some(segment) = growing.as_ref() {
return Arc::clone(segment);
}
let id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
let segment = GrowingSegment::new(id, &self.collection);
let segment_arc = Arc::new(RwLock::new(segment));
*growing = Some(Arc::clone(&segment_arc));
self.emit(LifecycleEvent::SegmentCreated(id));
// Update growing_count in the slow-path stats struct.
// This is the rare segment-creation path — locking is fine here.
self.stats.write().growing_count += 1;
segment_arc
}
/// Insert a new entity
pub fn insert(&self, mut entity: UnifiedEntity) -> Result<EntityId, SegmentError> {
// Check if we need to seal the current segment first
self.maybe_seal_growing()?;
let segment_arc = self.get_or_create_growing();
let mut segment = segment_arc.write();
// Assign entity ID if not already set
if entity.id.raw() == 0 {
entity.id = self.next_entity_id();
}
let entity_id = entity.id;
let segment_id = segment.id();
segment.insert(entity)?;
// Lock-free counter update — eliminates the stats write lock on the hot path.
self.total_entities_atomic.fetch_add(1, Ordering::Relaxed);
// entity_segment map is intentionally NOT updated here.
// update() and update_hot() first probe the growing segment directly
// (growing.contains(entity.id)) before consulting this map, so entities
// that were just inserted are found without entity_segment. The map is
// only consulted for entities that may have been moved to sealed segments,
// which can't be updated anyway (state().is_writable() == false).
// Skipping this write removes one exclusive HashMap lock per insert.
self.emit(LifecycleEvent::EntityInserted(entity_id, segment_id));
Ok(entity_id)
}
/// Restore a snapshot image without allocating a new sequence identity.
pub(crate) fn restore_snapshot_entity(
&self,
entity: UnifiedEntity,
) -> Result<EntityId, SegmentError> {
self.maybe_seal_growing()?;
if self.get(entity.id).is_some() {
return Err(SegmentError::AlreadyExists(entity.id));
}
let segment_arc = self.get_or_create_growing();
let mut segment = segment_arc.write();
let entity_id = entity.id;
let segment_id = segment.id();
// Adoption rebuilds derived indexes and advances the allocator past
// the stored sequence, including gaps and the legitimate value zero.
segment.adopt_entity(entity, None);
self.total_entities_atomic.fetch_add(1, Ordering::Relaxed);
self.emit(LifecycleEvent::EntityInserted(entity_id, segment_id));
Ok(entity_id)
}
/// Insert multiple entities (batch) — sequential, one lock per item.
pub fn insert_batch(
&self,
entities: Vec<UnifiedEntity>,
) -> Result<Vec<EntityId>, SegmentError> {
let mut ids = Vec::with_capacity(entities.len());
for entity in entities {
ids.push(self.insert(entity)?);
}
Ok(ids)
}
/// Turbo bulk insert — single lock acquisition for the entire batch.
/// Skips bloom filter and cross-ref indexing for maximum speed.
pub fn bulk_insert(
&self,
mut entities: Vec<UnifiedEntity>,
) -> Result<Vec<EntityId>, SegmentError> {
// Assign IDs and per-table row_ids.
for entity in &mut entities {
if entity.id.raw() == 0 {
entity.id = self.next_entity_id();
}
if let super::entity::EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
if *row_id == 0 {
*row_id = self.next_row_id();
} else {
self.register_row_id(*row_id);
}
}
}
// Convert named HashMap → positional Vec (compact memory representation)
// The schema (column order) is shared across all rows in the collection.
if let Some(first_row) = entities.first() {
if let super::entity::EntityData::Row(ref row) = first_row.data {
if let Some(ref named) = row.named {
let schema = self.get_or_init_schema(named);
for entity in &mut entities {
if let super::entity::EntityData::Row(ref mut row) = entity.data {
if let Some(named) = row.named.take() {
let mut cols = Vec::with_capacity(schema.len());
for col_name in schema.iter() {
cols.push(
named
.get(col_name)
.cloned()
.unwrap_or(reddb_types::Value::Null),
);
}
row.columns = cols;
row.schema = Some(Arc::clone(&schema));
}
}
}
}
}
}
let segment_arc = self.get_or_create_growing();
let mut segment = segment_arc.write();
let segment_id = segment.id();
// Single call to GrowingSegment.bulk_insert (one lock, no bloom/cross-refs)
let ids = segment.bulk_insert(entities)?;
// Skip entity-segment mapping for bulk inserts (saves ~56 bytes/entity).
// The get() method scans growing+sealed segments directly.
// Lock-free batch counter update.
self.total_entities_atomic
.fetch_add(ids.len() as u64, Ordering::Relaxed);
Ok(ids)
}
/// Get an entity by ID — scans growing then sealed segments.
pub fn get(&self, id: EntityId) -> Option<UnifiedEntity> {
self.get_with(id, Clone::clone)
}
/// Inspect under the segment lock, for example to bound a payload clone.
/// The callback must not re-enter storage or runtime memory admission.
pub(crate) fn get_with<T>(
&self,
id: EntityId,
visit: impl FnOnce(&UnifiedEntity) -> T,
) -> Option<T> {
// Growing segment first (most likely for recent inserts)
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
if let Some(entity) = growing.get(id) {
return Some(visit(entity));
}
}
// Then sealed segments
let sealed = self.sealed.read();
for segment in sealed.iter() {
let seg = segment.read();
if let Some(entity) = seg.get(id) {
return Some(visit(entity));
}
}
None
}
/// Resolve a physical graph node reference without cloning historical payloads.
/// This deliberately ignores MVCC: callers must authorize the visible logical
/// node separately. The callback bounds every segment probe, including misses.
pub(crate) fn graph_node_logical_id(
&self,
id: EntityId,
mut before_segment: impl FnMut() -> bool,
) -> Option<EntityId> {
if let Some(growing_arc) = self.growing.read().as_ref() {
if !before_segment() {
return None;
}
let growing = growing_arc.read();
if let Some(entity) = growing.get(id) {
return matches!(entity.kind, EntityKind::GraphNode(_))
.then(|| entity.logical_id());
}
}
let sealed = self.sealed.read();
for segment in sealed.iter() {
if !before_segment() {
return None;
}
let segment = segment.read();
if let Some(entity) = segment.get(id) {
return matches!(entity.kind, EntityKind::GraphNode(_))
.then(|| entity.logical_id());
}
}
None
}
/// Pin the source inventory across sealing/consolidation. Consumers hydrate
/// IDs through the current manager and run outside all storage locks.
/// Admission is also outside storage locks; a growing inventory retries only
/// its small handle array. Each indexed candidate buffer has a fixed size.
pub(crate) fn visit_graph_index_batches<E>(
&self,
kind: GraphEntityKind,
keys: &[EntityId],
mut before_work: impl FnMut() -> bool,
mut admit: impl FnMut(usize) -> Result<(), E>,
mut consume: impl FnMut(&[EntityId]) -> Result<bool, E>,
) -> Result<bool, E> {
use super::segment::{GraphIndexCursor, SCAN_BATCH_SIZE};
admit(std::mem::size_of::<[EntityId; SCAN_BATCH_SIZE]>())?;
let mut admitted = 0;
let sources = loop {
let count = {
let growing = self.growing.read();
let sealed = self.sealed.read();
sealed.len() + usize::from(growing.is_some())
};
let bytes = count.saturating_mul(std::mem::size_of::<(
Arc<RwLock<GrowingSegment>>,
GraphIndexCursor,
)>());
admit(bytes.saturating_sub(admitted))?;
admitted = admitted.max(bytes);
let mut sources = Vec::with_capacity(count);
let growing = self.growing.read();
let sealed = self.sealed.read();
if sealed.len() + usize::from(growing.is_some()) > sources.capacity() {
continue;
}
for segment in growing.iter().chain(sealed.iter()) {
if !before_work() {
return Ok(false);
}
let view = segment.read();
if !view.may_contain_graph_kind(kind) {
continue;
}
let Some(cursor) = view.graph_index_cursor(kind, keys, &mut before_work) else {
return Ok(false);
};
sources.push((Arc::clone(segment), cursor));
}
break sources;
};
let mut ids = [EntityId::new(0); SCAN_BATCH_SIZE];
for (source, mut cursor) in sources {
while !cursor.finished(keys) {
let mut count = 0;
{
let segment = source.read();
if !segment.may_contain_graph_kind(kind) {
break;
}
if !segment.graph_index_batch(
kind,
keys,
&mut cursor,
&mut before_work,
&mut |id| {
ids[count] = id;
count += 1;
},
) {
return Ok(false);
}
}
if !before_work() || !consume(&ids[..count])? {
return Ok(false);
}
}
}
Ok(true)
}
/// Batch-fetch multiple entities by ID in a single lock acquisition per segment.
///
/// For indexed-scan result sets (up to ~5000 ids from range/bitmap lookup) this
/// is 2-3 lock acquisitions total vs N×3 with individual `get()` calls.
pub fn get_many(&self, ids: &[EntityId]) -> Vec<Option<UnifiedEntity>> {
let mut out: Vec<Option<UnifiedEntity>> = vec![None; ids.len()];
let mut remaining: Vec<usize> = (0..ids.len()).collect(); // indices still unfound
// Growing segment — one read lock for the entire batch.
// Non-blocking first: if a writer is active, fall back to blocking.
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
remaining.retain(|&i| {
if let Some(entity) = growing.get(ids[i]) {
out[i] = Some(entity.clone());
false // remove from remaining
} else {
true // keep — not found yet
}
});
}
if remaining.is_empty() {
return out;
}
// Sealed segments — one read lock per segment
let sealed = self.sealed.read();
for segment in sealed.iter() {
if remaining.is_empty() {
break;
}
let seg = segment.read();
remaining.retain(|&i| {
if let Some(entity) = seg.get(ids[i]) {
out[i] = Some(entity.clone());
false
} else {
true
}
});
}
out
}
/// Visitor-pattern batch fetch. Invokes `f(&UnifiedEntity, usize_index)`
/// for each id that resolves, never cloning the entity.
///
/// Used by scan hot paths (select_range, select_filtered) that
/// materialize each entity into an output record and don't need
/// an owned `UnifiedEntity`. Eliminates ~20% of scan CPU spent in
/// `UnifiedEntity::clone` when `get_batch` is followed by
/// `runtime_table_record_lean(entity)`.
///
/// The closure runs while the segment read lock is held, so it
/// must be short — avoid doing I/O or taking unrelated locks in
/// `f`.
pub fn for_each_id<F>(&self, ids: &[EntityId], mut f: F)
where
F: FnMut(usize, &UnifiedEntity),
{
// Thread-local scratch buffer for the "pending" index list.
// Previous code allocated a fresh `Vec<usize>` of capacity
// N on every call — 4200 × 1000 queries / scenario on the
// select_range bench path. Take-and-restore pattern (vs
// RefCell::borrow_mut) so user closures that recurse into
// another `for_each_id` don't panic on a re-borrow; worst
// case they allocate a fresh buffer and we lose the caching
// win for that nested call.
thread_local! {
static REMAINING_SCRATCH: std::cell::Cell<Vec<usize>> =
const { std::cell::Cell::new(Vec::new()) };
}
let mut remaining: Vec<usize> = REMAINING_SCRATCH.with(|cell| cell.take());
remaining.clear();
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
for (i, id) in ids.iter().enumerate() {
if let Some(entity) = growing.get(*id) {
f(i, entity);
} else {
remaining.push(i);
}
}
} else {
remaining.reserve(ids.len());
remaining.extend(0..ids.len());
}
if !remaining.is_empty() {
let sealed = self.sealed.read();
for segment in sealed.iter() {
if remaining.is_empty() {
break;
}
let seg = segment.read();
remaining.retain(|&i| {
if let Some(entity) = seg.get(ids[i]) {
f(i, entity);
false
} else {
true
}
});
}
}
REMAINING_SCRATCH.with(|cell| cell.set(remaining));
}
/// Scan all segments for an entity
fn scan_for_entity(&self, id: EntityId) -> Option<UnifiedEntity> {
// Check growing
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
if let Some(entity) = growing.get(id) {
return Some(entity.clone());
}
}
// Check sealed
let sealed = self.sealed.read();
for segment in sealed.iter() {
if let Some(entity) = segment.get(id) {
return Some(entity.clone());
}
}
None
}
fn find_sealed_segment_arc(&self, id: EntityId) -> Option<Arc<RwLock<GrowingSegment>>> {
let sealed = self.sealed.read();
sealed
.iter()
.find(|segment_arc| segment_arc.read().contains(id))
.map(Arc::clone)
}
fn rewrite_sealed_entity_into_growing(
&self,
entity: UnifiedEntity,
metadata: Option<&Metadata>,
) -> Result<(), SegmentError> {
let entity_id = entity.id;
let sealed_arc = self
.find_sealed_segment_arc(entity_id)
.ok_or(SegmentError::NotFound(entity_id))?;
let metadata_to_apply = {
let mut sealed = sealed_arc.write();
let existing_metadata = sealed.get_metadata(entity_id);
if !sealed.force_delete(entity_id) {
return Err(SegmentError::NotFound(entity_id));
}
metadata.cloned().or(existing_metadata)
};
let growing_arc = self.get_or_create_growing();
let growing_id = {
let mut growing = growing_arc.write();
growing.insert(entity)?;
if let Some(metadata) = metadata_to_apply {
growing.set_metadata(entity_id, metadata)?;
}
growing.id()
};
self.entity_segment.write().insert(entity_id, growing_id);
Ok(())
}
/// Update an entity
pub fn update(&self, entity: UnifiedEntity) -> Result<(), SegmentError> {
let entity_id = entity.id;
let mut entity = Some(entity);
// Try growing segment directly (covers bulk-inserted entities without entity_segment map)
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.contains(entity_id) && growing.state().is_writable() {
return growing.update(entity.take().expect("entity already moved"));
}
}
// Try entity_segment mapping for individually inserted entities
let segment_id = self.entity_segment.read().get(&entity_id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.id() == seg_id && growing.state().is_writable() {
return growing.update(entity.take().expect("entity already moved"));
}
}
}
if let Some(entity) = entity.take() {
return self.rewrite_sealed_entity_into_growing(entity, None);
}
Err(SegmentError::NotFound(entity_id))
}
/// Update an entity and, optionally, replace its metadata while holding
/// the segment write lock only once.
pub fn update_with_metadata(
&self,
entity: UnifiedEntity,
metadata: Option<&Metadata>,
) -> Result<(), SegmentError> {
let entity_id = entity.id;
let mut entity = Some(entity);
// Try growing segment directly (covers bulk-inserted entities without entity_segment map)
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.contains(entity_id) && growing.state().is_writable() {
growing.update(entity.take().expect("entity already moved"))?;
if let Some(metadata) = metadata {
growing.set_metadata(entity_id, metadata.clone())?;
}
return Ok(());
}
}
// Try entity_segment mapping for individually inserted entities
let segment_id = self.entity_segment.read().get(&entity_id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.id() == seg_id && growing.state().is_writable() {
growing.update(entity.take().expect("entity already moved"))?;
if let Some(metadata) = metadata {
growing.set_metadata(entity_id, metadata.clone())?;
}
return Ok(());
}
}
}
if let Some(entity) = entity.take() {
return self.rewrite_sealed_entity_into_growing(entity, metadata);
}
Err(SegmentError::NotFound(entity_id))
}
/// HOT-update: like update but skips index work for unchanged columns.
/// `modified_columns` is the list of column names actually changed by the
/// UPDATE statement — lets us skip pk_index and cross_ref when safe.
pub fn update_hot(
&self,
entity: UnifiedEntity,
modified_columns: &[String],
) -> Result<(), SegmentError> {
let entity_id = entity.id;
let mut entity = Some(entity);
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.contains(entity_id) && growing.state().is_writable() {
return growing.update_hot(
entity.take().expect("entity already moved"),
modified_columns,
);
}
}
let segment_id = self.entity_segment.read().get(&entity_id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.id() == seg_id && growing.state().is_writable() {
return growing.update_hot(
entity.take().expect("entity already moved"),
modified_columns,
);
}
}
}
if let Some(entity) = entity.take() {
return self.rewrite_sealed_entity_into_growing(entity, None);
}
Err(SegmentError::NotFound(entity_id))
}
/// HOT-update an entity and, optionally, replace its metadata while
/// holding the segment write lock only once.
pub fn update_hot_with_metadata(
&self,
entity: UnifiedEntity,
modified_columns: &[String],
metadata: Option<&Metadata>,
) -> Result<(), SegmentError> {
let entity_id = entity.id;
let mut entity = Some(entity);
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.contains(entity_id) && growing.state().is_writable() {
growing.update_hot(
entity.take().expect("entity already moved"),
modified_columns,
)?;
if let Some(metadata) = metadata {
growing.set_metadata(entity_id, metadata.clone())?;
}
return Ok(());
}
}
let segment_id = self.entity_segment.read().get(&entity_id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.id() == seg_id && growing.state().is_writable() {
growing.update_hot(
entity.take().expect("entity already moved"),
modified_columns,
)?;
if let Some(metadata) = metadata {
growing.set_metadata(entity_id, metadata.clone())?;
}
return Ok(());
}
}
}
if let Some(entity) = entity.take() {
return self.rewrite_sealed_entity_into_growing(entity, metadata);
}
Err(SegmentError::NotFound(entity_id))
}
/// Batch HOT-update multiple entities while holding the growing-segment
/// write lock only once when possible.
pub fn update_hot_batch_with_metadata<'a, I>(&self, items: I) -> Result<(), SegmentError>
where
I: IntoIterator<Item = (&'a UnifiedEntity, &'a [String], Option<&'a Metadata>)>,
{
let items: Vec<(&UnifiedEntity, &[String], Option<&Metadata>)> =
items.into_iter().collect();
if items.is_empty() {
return Ok(());
}
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.state().is_writable() {
match growing.update_hot_batch_with_metadata(items.iter().copied()) {
Ok(()) => return Ok(()),
Err(SegmentError::NotFound(_)) => {}
Err(other) => return Err(other),
}
}
}
for (entity, modified_columns, metadata) in items {
self.update_hot_with_metadata(entity.clone(), modified_columns, metadata)?;
}
Ok(())
}
/// Delete an entity
pub fn delete(&self, id: EntityId) -> Result<bool, SegmentError> {
// Fast path: probe the growing segment directly — covers entities inserted via
// insert() which no longer writes to entity_segment, and bulk-inserted entities.
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.contains(id) && growing.state().is_writable() {
let seg_id = growing.id();
let deleted = growing.delete(id)?;
if deleted {
self.entity_segment.write().remove(&id);
self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
}
return Ok(deleted);
}
}
// Fallback: check entity_segment map (populated for older insert() paths
// or entities that were in a previous growing segment).
let segment_id = self.entity_segment.read().get(&id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.id() == seg_id && growing.state().is_writable() {
let deleted = growing.delete(id)?;
if deleted {
self.entity_segment.write().remove(&id);
self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
}
return Ok(deleted);
}
}
}
// Fallback: entity is in a sealed segment (bulk-inserted, not in entity_segment map).
// Single write-lock per segment to avoid TOCTOU race between contains() and force_delete().
{
let sealed = self.sealed.read();
for segment_arc in sealed.iter() {
let mut seg = segment_arc.write();
let seg_id = seg.id();
if seg.contains(id) {
let deleted = seg.force_delete(id);
drop(seg);
if deleted {
self.entity_segment.write().remove(&id);
self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
}
return Ok(deleted);
}
}
}
Ok(false)
}
pub fn delete_batch(&self, ids: &[EntityId]) -> Result<Vec<EntityId>, SegmentError> {
if ids.is_empty() {
return Ok(Vec::new());
}
let mut deleted_ids = Vec::with_capacity(ids.len());
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.state().is_writable() {
let seg_id = growing.id();
let deleted = growing.delete_batch(ids)?;
if !deleted.is_empty() {
{
let mut entity_segment = self.entity_segment.write();
for id in &deleted {
entity_segment.remove(id);
}
}
self.total_entities_atomic
.fetch_sub(deleted.len() as u64, Ordering::Relaxed);
for id in &deleted {
self.emit(LifecycleEvent::EntityDeleted(*id, seg_id));
}
deleted_ids.extend(deleted);
}
}
}
if deleted_ids.len() == ids.len() {
return Ok(deleted_ids);
}
let deleted_set: std::collections::HashSet<EntityId> =
deleted_ids.iter().copied().collect();
for &id in ids {
if deleted_set.contains(&id) {
continue;
}
if self.delete(id)? {
deleted_ids.push(id);
}
}
Ok(deleted_ids)
}
/// Get metadata for an entity
pub fn get_metadata(&self, id: EntityId) -> Option<Metadata> {
// Fast path: probe growing segment directly (no entity_segment needed).
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
if growing.contains(id) {
return growing.get_metadata(id);
}
}
// Fallback: entity_segment map (for pre-existing or sealed entities)
let segment_id = self.entity_segment.read().get(&id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
if growing.id() == seg_id {
return growing.get_metadata(id);
}
}
let sealed = self.sealed.read();
for segment in sealed.iter() {
if segment.id() == seg_id {
return segment.get_metadata(id);
}
}
}
if let Some(segment_arc) = self.find_sealed_segment_arc(id) {
return segment_arc.read().get_metadata(id);
}
None
}
/// Set metadata for an entity
pub fn set_metadata(&self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
// Fast path: probe growing segment directly — covers entities inserted via
// insert() which no longer writes to entity_segment.
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.contains(id) && growing.state().is_writable() {
return growing.set_metadata(id, metadata);
}
}
// Fallback: entity_segment map (sealed or pre-atomic-path entities)
let segment_id = self.entity_segment.read().get(&id).copied();
if let Some(seg_id) = segment_id {
if let Some(growing_arc) = self.growing.read().as_ref() {
let mut growing = growing_arc.write();
if growing.id() == seg_id && growing.state().is_writable() {
return growing.set_metadata(id, metadata);
}
}
}
if let Some(entity) = self.get(id) {
return self.rewrite_sealed_entity_into_growing(entity, Some(&metadata));
}
Err(SegmentError::NotFound(id))
}
/// Check if growing segment should be sealed
fn maybe_seal_growing(&self) -> Result<(), SegmentError> {
let should_seal = {
let growing_opt = self.growing.read();
if let Some(growing_arc) = growing_opt.as_ref() {
let growing = growing_arc.read();
growing.should_seal(&self.config.segment_config)
|| growing.idle_secs() >= self.config.idle_seal_secs
} else {
false
}
};
if should_seal {
self.seal_current()?;
}
Ok(())
}
/// Seal the current growing segment
pub fn seal_current(&self) -> Result<SegmentId, SegmentError> {
// Keep topology publication atomic for cursors that capture growing
// and sealed under the same lock order: growing, then sealed.
let mut growing_slot = self.growing.write();
if let Some(growing_arc) = growing_slot.take() {
let mut growing = growing_arc.write();
let seg_id = growing.id();
let entity_count = growing.stats().entity_count as u64;
// Seal it
growing.seal()?;
// Move to sealed list (we need to extract it from the Arc)
drop(growing); // Release write lock
// In a real implementation, we'd convert to SealedSegment here
// For now, we keep it as-is since GrowingSegment implements UnifiedSegment
self.sealed.write().push(growing_arc);
drop(growing_slot);
// Mark sealed segment pages all-visible — they're now immutable
self.mark_sealed_pages_visible(entity_count);
// Update stats
{
let mut stats = self.stats.write();
stats.growing_count = stats.growing_count.saturating_sub(1);
stats.sealed_count += 1;
stats.seal_ops += 1;
}
self.emit(LifecycleEvent::SegmentSealed(seg_id));
return Ok(seg_id);
}
Err(SegmentError::InvalidState(SegmentState::Sealed))
}
/// Force seal (for testing/manual control)
pub fn force_seal(&self) -> Result<Option<SegmentId>, SegmentError> {
let has_growing = self.growing.read().is_some();
if has_growing {
Ok(Some(self.seal_current()?))
} else {
Ok(None)
}
}
/// Fraction of "pages" in sealed segments that are marked all-visible.
///
/// Sealed segments are immutable so all their rows are safe for
/// index-only scans. The growing segment is never counted (writes
/// may be in-flight). Uses `rows_per_page = 256` (matching 8 KB pages
/// with ~32-byte rows).
///
/// Returns a value in `[0.0, 1.0]`. 1.0 when all sealed rows are
/// visible; 0.0 when there are no sealed segments.
pub fn all_visible_fraction(&self) -> f64 {
const ROWS_PER_PAGE: u32 = 256;
let sealed = self.sealed.read();
if sealed.is_empty() {
return 0.0;
}
let mut total_pages: u64 = 0;
for seg_arc in sealed.iter() {
let seg = seg_arc.read();
let entity_count = seg.stats().entity_count as u64;
let pages = entity_count.div_ceil(ROWS_PER_PAGE as u64);
total_pages += pages;
}
if total_pages == 0 {
return 0.0;
}
let visible = self.visibility_map.all_visible_count();
(visible as f64 / total_pages as f64).min(1.0)
}
/// Mark all pages of newly sealed segments as all-visible in the
/// visibility map. Called internally after `seal_current`.
fn mark_sealed_pages_visible(&self, seg_entity_count: u64) {
const ROWS_PER_PAGE: u32 = 256;
let existing_visible = self.visibility_map.all_visible_count();
// Append pages starting after the last known visible page
let start_page = existing_visible as u32;
let new_pages = seg_entity_count.div_ceil(ROWS_PER_PAGE as u64);
let end_page = start_page + new_pages as u32;
self.visibility_map.mark_range_visible(start_page, end_page);
}
/// Probe a unique-key lookup in each segment under the same entity
/// locks used by scans and writes. Lookup state is rebuilt lazily after
/// recovery, consolidation, or a key-changing mutation.
pub(crate) fn find_unique_key_conflict(
&self,
columns: &[Vec<String>],
key_index: usize,
signatures: &[String],
exclude_id: Option<EntityId>,
reserves_key: &impl Fn(&UnifiedEntity) -> bool,
) -> Option<EntityId> {
if let Some(growing) = self.growing.read().as_ref() {
if let Some(id) = growing.read().find_unique_key_conflict(
columns,
key_index,
signatures,
exclude_id,
reserves_key,
) {
return Some(id);
}
}
for segment in self.sealed.read().iter() {
if let Some(id) = segment.read().find_unique_key_conflict(
columns,
key_index,
signatures,
exclude_id,
reserves_key,
) {
return Some(id);
}
}
None
}
/// Iterate over all entities in-place without collecting into a Vec.
///
/// The callback receives a reference to each entity. Return `true` to
/// continue iteration, `false` to stop early (e.g. when a LIMIT is reached).
/// This avoids the allocation and cloning overhead of `query_all`.
pub fn for_each_entity<F>(&self, callback: F)
where
F: FnMut(&UnifiedEntity) -> bool,
{
self.for_each_entity_in_segments(|_| true, || true, callback);
}
fn for_each_entity_in_segments<F>(
&self,
segment_filter: impl Fn(&GrowingSegment) -> bool,
mut before_segment: impl FnMut() -> bool,
mut callback: F,
) where
F: FnMut(&UnifiedEntity) -> bool,
{
// Growing segment — direct iteration (no Box<dyn>)
// Try non-blocking read first; fall back to blocking only when a writer
// is actively holding the write lock (rare in read-heavy workloads).
if let Some(growing_arc) = self.growing.read().as_ref() {
if !before_segment() {
return;
}
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
if segment_filter(&growing) && !growing.for_each_fast(&mut callback) {
return;
}
}
// Sealed segments
let sealed = self.sealed.read();
for segment_arc in sealed.iter() {
if !before_segment() {
return;
}
let segment = segment_arc.read();
if segment_filter(&segment) && !segment.for_each_fast(&mut callback) {
return;
}
}
}
/// Parallel fold across all entities. Each sealed segment is
/// processed on its own rayon task; the growing segment stays on
/// the caller thread (its read lock is briefly held).
///
/// - `init` builds a fresh accumulator per thread.
/// - `fold` mutates an accumulator with one entity at a time.
/// - `reduce` combines two accumulators into one.
///
/// The returned value is the reduction of every per-thread
/// accumulator. Use this for aggregate-shape workloads (GROUP BY)
/// where per-thread partial state can be merged cheaply.
///
/// NOTE: when there are 0 or 1 sealed segments, the parallel path
/// is skipped and the work runs sequentially to avoid rayon
/// overhead on tiny tables.
pub fn fold_entities_parallel<T, FInit, FFold, FReduce>(
&self,
init: FInit,
fold: FFold,
reduce: FReduce,
) -> T
where
T: Send,
FInit: Fn() -> T + Send + Sync,
FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
FReduce: Fn(T, T) -> T + Send + Sync,
{
use rayon::prelude::*;
// Growing segment — always sequential (single writer lock,
// usually small working set).
let mut acc = init();
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
growing.for_each_fast(|entity| {
acc = fold(std::mem::replace(&mut acc, init()), entity);
true
});
}
// Sealed segments — snapshot the Arc list under the read lock,
// then drop the lock so rayon workers can fan out without
// blocking writers.
let segments: Vec<_> = {
let sealed = self.sealed.read();
sealed.iter().cloned().collect()
};
if segments.len() <= 1 {
for seg_arc in &segments {
let seg = seg_arc.read();
seg.for_each_fast(|entity| {
acc = fold(std::mem::replace(&mut acc, init()), entity);
true
});
}
return acc;
}
let sealed_acc = segments
.into_par_iter()
.map(|seg_arc| {
let mut local = init();
let seg = seg_arc.read();
seg.for_each_fast(|entity| {
local = fold(std::mem::replace(&mut local, init()), entity);
true
});
local
})
.reduce(&init, &reduce);
reduce(acc, sealed_acc)
}
/// Zone-map-aware iteration across all segments.
///
/// Like `for_each_entity`, but checks `zone_preds` against each segment's
/// column zone maps before iterating. Segments where any predicate can
/// definitively prove no rows match are skipped entirely.
///
/// `zone_preds`: slice of `(column_name, ZoneColPred)` extracted from the WHERE clause.
/// Empty slice → same behaviour as `for_each_entity` (no pruning).
pub fn for_each_entity_zoned<F>(&self, zone_preds: &[(&str, ZoneColPred<'_>)], mut callback: F)
where
F: FnMut(&UnifiedEntity) -> bool,
{
let _ = self.for_each_entity_zoned_with_stats(zone_preds, &mut callback);
}
pub fn for_each_entity_zoned_with_stats<F>(
&self,
zone_preds: &[(&str, ZoneColPred<'_>)],
mut callback: F,
) -> SegmentScanStats
where
F: FnMut(&UnifiedEntity) -> bool,
{
let mut scan_stats = SegmentScanStats::default();
// Growing segment — never skip (it's receiving writes, zones are partial).
// Try a non-blocking read first: if a writer is currently inserting
// (holding the write lock), try_read() returns None and we fall back to
// the blocking read. In low-contention workloads (reads far outnumber
// writes) the try_read() almost always succeeds and readers never stall.
if let Some(growing_arc) = self.growing.read().as_ref() {
scan_stats.segments_total += 1;
scan_stats.segments_scanned += 1;
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
if !growing.for_each_fast(&mut callback) {
return scan_stats;
}
}
// Sealed segments — check zone maps before iterating
let sealed = self.sealed.read();
for segment_arc in sealed.iter() {
scan_stats.segments_total += 1;
let segment = segment_arc.read();
if !zone_preds.is_empty() && segment.can_skip_zone_preds(zone_preds) {
scan_stats.segments_pruned += 1;
continue; // entire segment pruned
}
scan_stats.segments_scanned += 1;
if !segment.for_each_fast(&mut callback) {
return scan_stats;
}
}
scan_stats
}
/// Zone-map-aware parallel query.
///
/// Like `query_all` but applies `zone_preds` on the main thread to
/// prune sealed segments before spawning workers — segments that
/// provably contain no matching rows are skipped entirely.
///
/// Zone check runs single-threaded (it reads per-segment metadata,
/// not row data), so it's cheap. Surviving segments are then scanned
/// in parallel using `std::thread::scope` when there are > 1 of them.
pub fn query_all_zoned<F>(
&self,
zone_preds: &[(&str, ZoneColPred<'_>)],
filter: F,
) -> Vec<UnifiedEntity>
where
F: Fn(&UnifiedEntity) -> bool + Sync,
{
self.query_all_zoned_with_stats(zone_preds, filter).0
}
pub fn query_all_zoned_with_stats<F>(
&self,
zone_preds: &[(&str, ZoneColPred<'_>)],
filter: F,
) -> (Vec<UnifiedEntity>, SegmentScanStats)
where
F: Fn(&UnifiedEntity) -> bool + Sync,
{
let mut results = Vec::new();
let mut scan_stats = SegmentScanStats::default();
// Growing segment — always scan, no zone skip (zones are partial).
// Non-blocking try_read() avoids stalling behind in-progress inserts.
if let Some(growing_arc) = self.growing.read().as_ref() {
scan_stats.segments_total += 1;
scan_stats.segments_scanned += 1;
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
results.extend(growing.iter().filter(|e| filter(e)).cloned());
}
// Sealed segments: zone-prune on main thread, then scan in parallel.
let sealed = self.sealed.read();
// Collect only the segments that survive zone-predicate pruning.
let surviving: Vec<_> = sealed
.iter()
.filter(|seg_arc| {
scan_stats.segments_total += 1;
if zone_preds.is_empty() {
scan_stats.segments_scanned += 1;
return true;
}
let seg = seg_arc.read();
if seg.can_skip_zone_preds(zone_preds) {
scan_stats.segments_pruned += 1;
false
} else {
scan_stats.segments_scanned += 1;
true
}
})
.collect();
let use_parallel = surviving.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
if use_parallel {
let filter_ref = &filter;
let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
surviving
.iter()
.map(|segment| {
s.spawn(move || {
segment
.read()
.iter()
.filter(|e| filter_ref(e))
.cloned()
.collect::<Vec<_>>()
})
})
.collect::<Vec<_>>()
.into_iter()
.map(|handle| handle.join().unwrap_or_default())
.collect()
});
for batch in segment_results {
results.extend(batch);
}
} else {
for segment_arc in surviving {
let seg = segment_arc.read();
results.extend(seg.iter().filter(|e| filter(e)).cloned());
}
}
(results, scan_stats)
}
/// Visibility predicate for the `scan_*` family. `Some` delegates to the
/// canonical `entity_visible_with_context`; `None` supports low-level
/// callers that intentionally scan without a statement snapshot and keeps
/// the documented resolver fallback — moderation gate plus hiding
/// superseded physical versions — instead of showing every version.
fn scan_entity_visible(snapshot: Option<&SnapshotContext>, entity: &UnifiedEntity) -> bool {
match snapshot {
Some(ctx) => entity_visible_with_context(Some(ctx), entity),
None => {
!crate::runtime::ai::moderation::entity_moderation_hidden(entity)
&& entity.xmax == 0
}
}
}
/// Scan every segment under an explicit MVCC snapshot.
///
/// Visibility is evaluated while each segment iterator is active, before
/// the caller's filter. Unlike the raw iteration methods, this entry point
/// does not consult thread-local snapshot state, so it preserves the same
/// view when invoked from a different thread.
pub fn scan<F>(&self, snapshot: Option<&SnapshotContext>, filter: F) -> Vec<UnifiedEntity>
where
F: Fn(&UnifiedEntity) -> bool + Sync,
{
self.query_all(|entity| Self::scan_entity_visible(snapshot, entity) && filter(entity))
}
/// Collect visible graph items, pruning only under the segment read guard.
pub(crate) fn scan_graph_kind(
&self,
snapshot: Option<&SnapshotContext>,
kind: GraphEntityKind,
) -> Vec<UnifiedEntity> {
self.query_all_in_segments(
|segment| segment.may_contain_graph_kind(kind),
|entity| Self::scan_entity_visible(snapshot, entity) && kind.matches(&entity.kind),
)
}
/// Visit visible candidates in segments that may contain the requested kind.
/// Non-graph items in those segments still reach the callback so work budgets
/// charge every inspected visible candidate. RLS must run outside this callback.
/// `before_segment` runs even for pruned segments; false stops the entire scan.
pub(crate) fn scan_graph_candidates_for_each<F>(
&self,
snapshot: Option<&SnapshotContext>,
kind: GraphEntityKind,
before_segment: impl FnMut() -> bool,
mut callback: F,
) where
F: FnMut(&UnifiedEntity) -> bool,
{
self.for_each_entity_in_segments(
|segment| segment.may_contain_graph_kind(kind),
before_segment,
|entity| !Self::scan_entity_visible(snapshot, entity) || callback(entity),
);
}
/// Visit every entity visible under an explicit MVCC snapshot.
///
/// Returning `false` from `callback` stops the scan early. Hidden entities
/// never reach the callback and therefore cannot stop the scan.
pub fn scan_for_each<F>(&self, snapshot: Option<&SnapshotContext>, mut callback: F)
where
F: FnMut(&UnifiedEntity) -> bool,
{
self.for_each_entity(|entity| {
!Self::scan_entity_visible(snapshot, entity) || callback(entity)
});
}
/// Capture segment membership and append boundaries, then hydrate bounded
/// batches. The consumer runs outside topology and segment locks, so scoring
/// and RLS may re-enter storage and writers can progress between batches.
/// Retired sources pin positions only; hydration uses current segments so
/// mutations after consolidation are visible to the snapshot predicate.
pub(crate) fn scan_batches(
&self,
snapshot: Option<&SnapshotContext>,
mut before_work: impl FnMut() -> bool,
mut consume: impl FnMut(&[UnifiedEntity]) -> bool,
) -> bool {
let segments = {
let growing = self.growing.read();
let sealed = self.sealed.read();
let mut segments = Vec::with_capacity(sealed.len() + usize::from(growing.is_some()));
for segment in growing.iter().chain(sealed.iter()) {
if !before_work() {
return false;
}
let cursor = segment.read().scan_cursor();
segments.push((Arc::clone(segment), cursor));
}
segments
};
let mut ids = Vec::new();
let mut batch = Vec::new();
for (segment, mut cursor) in segments {
while !cursor.finished() {
ids.clear();
batch.clear();
let batch_size = cursor.remaining().min(super::segment::SCAN_BATCH_SIZE);
ids.reserve_exact(batch_size);
batch.reserve_exact(batch_size);
{
let segment = segment.read();
if !segment.scan_batch(&mut cursor, &mut before_work, &mut |id| ids.push(id)) {
return false;
}
}
// Sources can retire between batches. Consult authoritative storage
// after releasing the source guard, just as the former ID-list scan did.
if !before_work() {
return false;
}
self.for_each_id(&ids, |_, entity| {
if Self::scan_entity_visible(snapshot, entity) {
batch.push(entity.clone());
}
});
if !before_work() {
return false;
}
if !consume(&batch) {
return false;
}
}
}
true
}
/// Fold entities visible under an explicit MVCC snapshot in parallel.
pub fn scan_fold_parallel<T, FInit, FFold, FReduce>(
&self,
snapshot: Option<&SnapshotContext>,
init: FInit,
fold: FFold,
reduce: FReduce,
) -> T
where
T: Send,
FInit: Fn() -> T + Send + Sync,
FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
FReduce: Fn(T, T) -> T + Send + Sync,
{
self.fold_entities_parallel(
init,
|acc, entity| {
if Self::scan_entity_visible(snapshot, entity) {
fold(acc, entity)
} else {
acc
}
},
reduce,
)
}
/// Visit zone-map candidates visible under an explicit MVCC snapshot.
pub fn scan_for_each_zoned_with_stats<F>(
&self,
snapshot: Option<&SnapshotContext>,
zone_preds: &[(&str, ZoneColPred<'_>)],
mut callback: F,
) -> SegmentScanStats
where
F: FnMut(&UnifiedEntity) -> bool,
{
self.for_each_entity_zoned_with_stats(zone_preds, |entity| {
!Self::scan_entity_visible(snapshot, entity) || callback(entity)
})
}
/// Collect zone-map candidates visible under an explicit MVCC snapshot.
pub fn scan_zoned_with_stats<F>(
&self,
snapshot: Option<&SnapshotContext>,
zone_preds: &[(&str, ZoneColPred<'_>)],
filter: F,
) -> (Vec<UnifiedEntity>, SegmentScanStats)
where
F: Fn(&UnifiedEntity) -> bool + Sync,
{
self.query_all_zoned_with_stats(zone_preds, |entity| {
Self::scan_entity_visible(snapshot, entity) && filter(entity)
})
}
/// Query across all segments. Uses parallel scanning for sealed segments
/// when more than one sealed segment exists.
pub fn query_all<F>(&self, filter: F) -> Vec<UnifiedEntity>
where
F: Fn(&UnifiedEntity) -> bool + Sync,
{
self.query_all_in_segments(|_| true, filter)
}
fn query_all_in_segments<F>(
&self,
segment_filter: impl Fn(&GrowingSegment) -> bool + Sync,
filter: F,
) -> Vec<UnifiedEntity>
where
F: Fn(&UnifiedEntity) -> bool + Sync,
{
let mut results = Vec::new();
// Query growing segment — try non-blocking read first (avoids stalling
// behind an in-progress insert; falls back to blocking if writer is active).
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = if let Some(g) = growing_arc.try_read() {
g
} else {
growing_arc.read()
};
if segment_filter(&growing) {
results.extend(growing.iter().filter(|e| filter(e)).cloned());
}
}
// Query sealed segments — parallel when multiple exist AND multi-core
let sealed = self.sealed.read();
let use_parallel = sealed.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
if use_parallel {
let filter_ref = &filter;
let segment_filter_ref = &segment_filter;
let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
sealed
.iter()
.map(|segment| {
s.spawn(move || {
let segment = segment.read();
if segment_filter_ref(&segment) {
segment
.iter()
.filter(|e| filter_ref(e))
.cloned()
.collect::<Vec<_>>()
} else {
Vec::new()
}
})
})
.collect::<Vec<_>>()
.into_iter()
.map(|handle| handle.join().unwrap_or_default())
.collect()
});
for batch in segment_results {
results.extend(batch);
}
} else {
for segment in sealed.iter() {
let seg = segment.read();
if segment_filter(&seg) {
results.extend(seg.iter().filter(|e| filter(e)).cloned());
}
}
}
results
}
/// Probe exact segment membership for a key without materializing matching entities.
///
/// Returns `false` only when every consulted segment proves absence.
/// Missing segment state is conservative and returns `true`.
pub fn bloom_may_contain_key(&self, key: &[u8]) -> bool {
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
if growing.may_contain_exact_key(key) {
return true;
}
} else {
return true;
}
let sealed = self.sealed.read();
for segment_arc in sealed.iter() {
let segment = segment_arc.read();
if segment.may_contain_exact_key(key) {
return true;
}
}
false
}
/// Filter by metadata across all segments
pub fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
let mut results = Vec::new();
// Growing segment
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
results.extend(growing.filter_metadata(filters));
}
// Sealed segments
let sealed = self.sealed.read();
for segment in sealed.iter() {
results.extend(segment.filter_metadata(filters));
}
results
}
/// Get entities by kind
pub fn get_by_kind(&self, kind: &str) -> Vec<UnifiedEntity> {
let mut results = Vec::new();
// Growing segment
if let Some(growing_arc) = self.growing.read().as_ref() {
let growing = growing_arc.read();
for entity in growing.iter_kind(kind) {
results.push(entity.clone());
}
}
// Sealed segments. Iterate through the read guard, not the
// `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` — that one cannot
// hand out references across the lock, so it returns an empty iterator
// and every sealed entity was silently missing from the result.
let sealed = self.sealed.read();
for segment_arc in sealed.iter() {
let segment = segment_arc.read();
for entity in segment.iter_kind(kind) {
results.push(entity.clone());
}
}
results
}
/// Count entities
pub fn count(&self) -> usize {
self.total_entities_atomic.load(Ordering::Relaxed) as usize
}
/// Get all segment IDs
pub fn segment_ids(&self) -> Vec<SegmentId> {
let mut ids = Vec::new();
if let Some(growing_arc) = self.growing.read().as_ref() {
ids.push(growing_arc.read().id());
}
let sealed = self.sealed.read();
for segment in sealed.iter() {
ids.push(segment.id());
}
ids.extend(self.archived.read().iter().copied());
ids
}
/// Emit a lifecycle event.
///
/// Perf: this used to push onto a `RwLock<Vec<LifecycleEvent>>`
/// on every insert / delete / seal. Nobody consumes that vec
/// today (no subscription API, `drain_events` has no callers),
/// so the write lock + push was pure tax — and the vec grew
/// unbounded in long-running processes.
///
/// Current behaviour: no-op. If we ever want the hooks back,
/// replace this with a bounded channel or an actual subscriber
/// registry; the callers (`insert`, `delete`, `maybe_seal_growing`)
/// already pass well-typed events.
#[inline]
#[allow(clippy::unused_self)]
fn emit(&self, _event: LifecycleEvent) {}
/// Drain events. Kept for API compatibility; always returns
/// empty because `emit` no longer buffers.
pub fn drain_events(&self) -> Vec<LifecycleEvent> {
std::mem::take(&mut *self.events.write())
}
/// Run maintenance (would be called periodically in production)
pub fn run_maintenance(&self) -> Result<(), SegmentError> {
// Auto-seal idle segments
self.maybe_seal_growing()?;
if self.config.enable_consolidation {
self.consolidation_tick();
}
Ok(())
}
// ========================================================================
// Consolidation — ADR 0073 §5
// ========================================================================
/// One paced step of sealed-segment consolidation.
///
/// Starts a run when a threshold has been crossed, copies at most
/// `consolidation_entities_per_tick` live entities into the merged segment,
/// and swaps once every source has been drained. Returns without finishing
/// otherwise — the half-built merged segment waits for the next tick.
fn consolidation_tick(&self) {
// Drop the read guard before `start_consolidation` takes the write
// guard: `parking_lot` locks are not reentrant.
let running = self.consolidation.read().is_some();
if !running && !self.start_consolidation() {
return;
}
// Keep the accounting guard through publication: the merged allocation
// must never disappear between the in-flight and active inventories.
let mut guard = self.consolidation.write();
let Some(run) = guard.as_mut() else {
return;
};
self.copy_bounded(run);
if run.cursor >= run.sources.len() {
if let Some(run) = guard.take() {
self.finish_consolidation(run);
}
}
}
/// Evaluate the trigger and, when it fires, open a consolidation run.
///
/// Returns `true` when a run was started.
fn start_consolidation(&self) -> bool {
let sources = self.select_candidates();
self.start_consolidation_from_sources(sources)
}
fn start_consolidation_from_sources(&self, sources: Vec<SegmentId>) -> bool {
if sources.len() < 2 && !self.candidates_carry_tombstones(&sources) {
return false;
}
let merged_id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
let merged = GrowingSegment::new(merged_id, &self.collection);
*self.consolidation.write() = Some(Consolidation {
sources: sources
.into_iter()
.map(|id| SourceProgress {
id,
copied: Vec::new(),
tombstones_at_open: None,
})
.collect(),
merged_id,
merged,
cursor: 0,
pending_ids: Vec::new(),
pending_cursor: 0,
entities_copied: 0,
});
self.stats.write().consolidation.runs_started += 1;
true
}
/// Run one paced consolidation tick because admission pressure needs
/// reclaimable bytes, even if the background thresholds have not fired.
///
/// Returns true when the call started or advanced a consolidation run.
pub fn pressure_consolidation_tick(&self) -> bool {
if !self.config.enable_consolidation {
return false;
}
let running = self.consolidation.read().is_some();
if !running {
let sources = self.dirty_sealed_segments();
if !self.start_consolidation_from_sources(sources) {
return false;
}
}
self.consolidation_tick();
true
}
/// Which sealed segments this collection should merge, if any.
///
/// Three thresholds, any of which arms consolidation:
///
/// * **sealed-segment count** above `max_sealed_segments` — every sealed
/// segment merges, which is what that knob always claimed to do.
/// * **tombstone ratio** — dead entities over total entities across the
/// sealed set, past [`CONSOLIDATION_TOMBSTONE_RATIO`].
/// * **fragmentation** — reclaimable bytes over held bytes, past
/// [`CONSOLIDATION_FRAGMENTATION_RATIO`].
///
/// The count trigger takes every sealed segment; the two budget triggers
/// take only the segments that actually carry tombstones, so a clean
/// segment is never rewritten for nothing.
fn select_candidates(&self) -> Vec<SegmentId> {
let sealed = self.sealed.read();
if sealed.is_empty() {
return Vec::new();
}
if sealed.len() > self.config.max_sealed_segments {
return sealed.iter().map(|segment| segment.read().id()).collect();
}
let mut live = 0usize;
let mut tombstones = 0usize;
let mut held = 0u64;
let mut reclaimable = 0u64;
let mut dirty = Vec::new();
for segment_arc in sealed.iter() {
let segment = segment_arc.read();
live += segment.live_entity_count();
tombstones += segment.tombstone_count();
held += segment.resident_bytes();
reclaimable += segment.reclaimable_bytes();
if segment.tombstone_count() > 0 {
dirty.push(segment.id());
}
}
let total = live + tombstones;
let tombstone_ratio = if total == 0 {
0.0
} else {
tombstones as f64 / total as f64
};
let fragmentation = if held == 0 {
0.0
} else {
reclaimable as f64 / held as f64
};
if tombstone_ratio >= CONSOLIDATION_TOMBSTONE_RATIO
|| fragmentation >= CONSOLIDATION_FRAGMENTATION_RATIO
{
return dirty;
}
Vec::new()
}
fn dirty_sealed_segments(&self) -> Vec<SegmentId> {
self.sealed
.read()
.iter()
.filter_map(|segment_arc| {
let segment = segment_arc.read();
(segment.reclaimable_bytes() > 0).then(|| segment.id())
})
.collect()
}
/// A single candidate is still worth merging when it carries tombstones —
/// the merge drops them. A single clean candidate is not.
fn candidates_carry_tombstones(&self, sources: &[SegmentId]) -> bool {
if sources.is_empty() {
return false;
}
let sealed = self.sealed.read();
sealed.iter().any(|segment_arc| {
let segment = segment_arc.read();
sources.contains(&segment.id()) && segment.tombstone_count() > 0
})
}
fn sealed_segment(&self, id: SegmentId) -> Option<Arc<RwLock<GrowingSegment>>> {
let sealed = self.sealed.read();
sealed
.iter()
.find(|segment| segment.read().id() == id)
.map(Arc::clone)
}
/// Copy at most one tick's worth of live entities into the merged segment.
///
/// The per-tick bound is the pacing contract: a tick's cost is O(bound),
/// independent of how many entities the run still has to move.
fn copy_bounded(&self, run: &mut Consolidation) {
let mut budget = self.config.consolidation_entities_per_tick;
while budget > 0 && run.cursor < run.sources.len() {
let source_id = run.sources[run.cursor].id;
let Some(source_arc) = self.sealed_segment(source_id) else {
// The source vanished. Only consolidation removes sealed
// segments and it is single-threaded per collection, so this
// cannot happen today — skip it rather than resurrect its rows.
run.cursor += 1;
run.pending_ids.clear();
run.pending_cursor = 0;
continue;
};
if run.sources[run.cursor].tombstones_at_open.is_none() {
let source = source_arc.read();
run.pending_ids = source.live_entity_ids();
run.pending_cursor = 0;
run.sources[run.cursor].tombstones_at_open = Some(source.tombstone_count());
}
{
let source = source_arc.read();
while budget > 0 && run.pending_cursor < run.pending_ids.len() {
let id = run.pending_ids[run.pending_cursor];
run.pending_cursor += 1;
budget -= 1;
// Tombstoned between the snapshot and now — it must not be
// resurrected into the merged segment.
let Some(entity) = source.get(id) else {
continue;
};
let metadata = source.get_metadata(id);
run.merged.adopt_entity(entity.clone(), metadata);
run.sources[run.cursor].copied.push(id);
run.entities_copied += 1;
}
}
if run.pending_cursor >= run.pending_ids.len() {
run.cursor += 1;
run.pending_ids.clear();
run.pending_cursor = 0;
}
}
}
/// Atomically replace the source segments with the merged one.
///
/// The `sealed` write lock is the boundary: a reader holds the read lock
/// for the whole of its scan, so it observes either the old set or the new
/// set, never a gap and never both copies of a row.
fn finish_consolidation(&self, mut run: Consolidation) {
let mut sealed = self.sealed.write();
let mut positions = Vec::with_capacity(run.sources.len());
for source in &run.sources {
if let Some(index) = sealed
.iter()
.position(|segment| segment.read().id() == source.id)
{
positions.push(index);
}
}
if positions.is_empty() {
return;
}
positions.sort_unstable();
// Rows deleted from a source after we copied them must not come back.
// A source whose tombstone count is unchanged saw no deletes while the
// merge ran, so its copied rows need no per-row check.
let mut stale = Vec::new();
for source in &run.sources {
let Some(source_arc) = sealed
.iter()
.find(|segment| segment.read().id() == source.id)
else {
continue;
};
let segment = source_arc.read();
if source.tombstones_at_open == Some(segment.tombstone_count()) {
continue;
}
stale.extend(
source
.copied
.iter()
.copied()
.filter(|id| !segment.contains(*id)),
);
}
for id in stale {
run.merged.evict_entity(id);
}
let reclaimed_bytes: u64 = positions
.iter()
.map(|&index| sealed[index].read().resident_bytes())
.sum();
let reclaimed_tombstones: u64 = positions
.iter()
.map(|&index| sealed[index].read().tombstone_count() as u64)
.sum();
if run.merged.seal().is_err() {
return;
}
let merged_bytes = run.merged.resident_bytes();
let merged_arc = Arc::new(RwLock::new(run.merged));
{
let mut retired = self.retired.write();
retired.retain(|source| source.strong_count() > 0);
for &index in positions.iter().rev() {
let source = sealed.remove(index);
if Arc::strong_count(&source) > 1 {
retired.push(Arc::downgrade(&source));
}
}
}
let insert_at = positions[0].min(sealed.len());
sealed.insert(insert_at, Arc::clone(&merged_arc));
drop(sealed);
// Remap the entity→segment hints that pointed at the retired sources.
let source_ids: Vec<SegmentId> = run.sources.iter().map(|source| source.id).collect();
{
let mut entity_segment = self.entity_segment.write();
for segment_id in entity_segment.values_mut() {
if source_ids.contains(segment_id) {
*segment_id = run.merged_id;
}
}
}
{
let mut stats = self.stats.write();
stats.sealed_count = stats
.sealed_count
.saturating_sub(positions.len())
.saturating_add(1);
let consolidation = &mut stats.consolidation;
consolidation.runs_completed += 1;
consolidation.segments_merged += positions.len() as u64;
consolidation.tombstones_reclaimed += reclaimed_tombstones;
consolidation.bytes_reclaimed += reclaimed_bytes.saturating_sub(merged_bytes);
}
self.emit(LifecycleEvent::SegmentConsolidated {
source: source_ids,
target: run.merged_id,
});
}
/// Entities copied by the consolidation currently in flight, or `None` when
/// none is running. Exposed for the pacing tests.
#[cfg(test)]
fn consolidation_progress(&self) -> Option<u64> {
self.consolidation
.read()
.as_ref()
.map(|run| run.entities_copied)
}
}
// Implement the Arc<RwLock<GrowingSegment>> as UnifiedSegment
// This is needed because we store growing segments in the sealed list after sealing
impl UnifiedSegment for Arc<RwLock<GrowingSegment>> {
fn id(&self) -> SegmentId {
self.read().id()
}
fn state(&self) -> SegmentState {
self.read().state()
}
fn collection(&self) -> &str {
// This is a limitation - we'd need to store collection in the Arc wrapper
"unknown"
}
fn stats(&self) -> SegmentStats {
self.read().stats()
}
fn entity_count(&self) -> usize {
self.read().entity_count()
}
fn contains(&self, id: EntityId) -> bool {
self.read().contains(id)
}
fn get(&self, id: EntityId) -> Option<&UnifiedEntity> {
// This is tricky with RwLock - we can't return a reference
// In production, we'd use a different approach
None
}
fn get_mut(&mut self, _id: EntityId) -> Option<&mut UnifiedEntity> {
None
}
fn insert(&mut self, entity: UnifiedEntity) -> Result<EntityId, SegmentError> {
self.write().insert(entity)
}
fn update(&mut self, entity: UnifiedEntity) -> Result<(), SegmentError> {
self.write().update(entity)
}
fn update_hot(
&mut self,
entity: UnifiedEntity,
modified_columns: &[String],
) -> Result<(), SegmentError> {
self.write().update_hot(entity, modified_columns)
}
fn delete(&mut self, id: EntityId) -> Result<bool, SegmentError> {
self.write().delete(id)
}
fn get_metadata(&self, id: EntityId) -> Option<Metadata> {
self.read().get_metadata(id)
}
fn set_metadata(&mut self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
self.write().set_metadata(id, metadata)
}
fn seal(&mut self) -> Result<(), SegmentError> {
self.write().seal()
}
fn should_seal(&self, config: &SegmentConfig) -> bool {
self.read().should_seal(config)
}
fn iter(&self) -> Box<dyn Iterator<Item = &UnifiedEntity> + '_> {
// Cannot return iterator with RwLock
Box::new(std::iter::empty())
}
fn iter_kind(&self, _kind_filter: &str) -> Box<dyn Iterator<Item = &UnifiedEntity> + '_> {
Box::new(std::iter::empty())
}
fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
self.read().filter_metadata(filters)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
use crate::runtime::mvcc::SnapshotContext;
use crate::storage::transaction::snapshot::{Snapshot, SnapshotManager};
use crate::storage::unified::entity::{EntityData, EntityKind, RowData};
use reddb_types::Value;
#[test]
fn bounded_scan_survives_sealing_consolidation_and_new_writes() {
let manager = SegmentManager::with_config(
"vectors",
ManagerConfig {
max_sealed_segments: 1,
consolidation_entities_per_tick: 10_000,
..Default::default()
},
);
for part in 0..3 {
manager
.bulk_insert(
(1..=300)
.map(|offset| {
UnifiedEntity::vector(
EntityId::new(part * 300 + offset),
"vectors",
vec![1.0, 0.0],
)
})
.collect(),
)
.expect("batch");
if part < 2 {
manager.force_seal().expect("seal");
}
}
let original_growing = manager.growing.read().as_ref().expect("growing").clone();
let mut changed = false;
let mut seen = Vec::new();
assert!(manager.scan_batches(
None,
|| true,
|batch| {
assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
assert!(
manager.growing.try_write().is_some(),
"consumer holds no topology guard"
);
assert!(
original_growing.try_write().is_some(),
"consumer holds no segment guard"
);
for entity in batch {
assert!(manager.get(entity.id).is_some(), "reentrant storage lookup");
seen.push(entity.id.raw());
}
if !changed {
changed = true;
manager.force_seal().expect("seal during scan");
manager
.insert(UnifiedEntity::vector(
EntityId::new(5000),
"vectors",
vec![1.0, 0.0],
))
.expect("new write");
drain_maintenance(&manager);
assert!(manager.stats().consolidation.runs_completed > 0);
assert!(manager
.delete(EntityId::new(1))
.expect("delete after source retirement"));
assert!(manager.get(EntityId::new(1)).is_none());
}
true
}
));
seen.sort_unstable();
assert_eq!(
seen,
(2..=900).collect::<Vec<_>>(),
"no duplicate, missing or late candidates"
);
let mut after = Vec::new();
assert!(manager.scan_batches(
None,
|| true,
|batch| {
after.extend(batch.iter().map(|entity| entity.id.raw()));
true
}
));
after.sort_unstable();
let mut expected: Vec<_> = (2..=900).collect();
expected.push(5000);
assert_eq!(after, expected, "adopted entities have scan positions");
}
#[test]
fn bounded_scan_applies_snapshot_to_relocated_versions() {
for (consolidate, bulk) in [(false, false), (false, true), (true, false), (true, true)] {
let manager = SegmentManager::with_config(
"vectors",
ManagerConfig {
max_sealed_segments: 1,
..Default::default()
},
);
for ids in [[1, 2], [3, 4]] {
let entities = ids.map(|id| {
let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
entity.set_xmin(3);
entity
});
if bulk {
manager
.bulk_insert(entities.into())
.expect("initial versions");
} else {
for entity in entities {
manager.insert(entity).expect("initial version");
}
}
manager.force_seal().expect("seal source");
}
let snapshot = SnapshotContext {
snapshot: Snapshot {
xid: 10,
in_progress: HashSet::new(),
},
manager: Arc::new(SnapshotManager::new()),
own_xids: HashSet::new(),
requires_index_fallback: false,
serializable_reader: None,
};
let mut changed = false;
let mut seen = Vec::new();
assert!(manager.scan_batches(
Some(&snapshot),
|| true,
|batch| {
seen.extend(batch.iter().map(|entity| entity.id.raw()));
if !changed {
changed = true;
if consolidate {
drain_maintenance(&manager);
assert!(manager.stats().consolidation.runs_completed > 0);
}
for (id, xmax) in [(3, 8), (4, 12)] {
let mut entity =
manager.get(EntityId::new(id)).expect("retained version");
entity.set_xmax(xmax);
manager
.update(entity)
.expect("update after source retirement");
}
}
true
}
));
seen.sort_unstable();
assert_eq!(seen, vec![1, 2, 4], "snapshot uses authoritative xmax");
let mut again = Vec::new();
assert!(manager.scan_batches(
Some(&snapshot),
|| true,
|batch| {
again.extend(batch.iter().map(|entity| entity.id.raw()));
true
}
));
again.sort_unstable();
assert_eq!(
again,
vec![1, 2, 4],
"old slots do not duplicate relocated versions"
);
let mut current = Vec::new();
assert!(manager.scan_batches(
None,
|| true,
|batch| {
current.extend(batch.iter().map(|entity| entity.id.raw()));
true
}
));
current.sort_unstable();
assert_eq!(
current,
vec![1, 2],
"current view excludes both deleted versions"
);
}
}
#[test]
fn bounded_scan_keeps_flat_and_hash_positions_through_mutation() {
let manager = SegmentManager::new("mixed");
let vector = |id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![1.0]);
manager
.bulk_insert((1..=300).map(vector).collect())
.expect("flat");
manager.insert(vector(500)).expect("hash insert");
manager
.bulk_insert(vec![vector(502), vector(505)])
.expect("gapped bulk");
manager.delete(EntityId::new(2)).expect("flat delete");
manager.delete(EntityId::new(505)).expect("hash delete");
let mut changed = false;
let mut seen = Vec::new();
assert!(manager.scan_batches(
None,
|| true,
|batch| {
seen.extend(batch.iter().map(|entity| entity.id.raw()));
if !changed {
changed = true;
manager
.insert(vector(700))
.expect("append after cursor boundary");
manager
.update(UnifiedEntity::graph_node(
EntityId::new(500),
"mixed",
"Node",
HashMap::new(),
))
.expect("structural update");
}
true
}
));
seen.sort_unstable();
let mut expected: Vec<_> = (1..=300).filter(|id| *id != 2).collect();
expected.extend([500, 502]);
assert_eq!(seen, expected);
}
#[test]
fn bounded_scan_preserves_snapshot_and_discards_interrupted_batches() {
let manager = SegmentManager::new("vectors");
let mut entities = Vec::new();
for (id, xmin, xmax) in [(1, 3, 12), (2, 12, 0), (3, 3, 0), (4, 3, 4)] {
let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
entity.set_xmin(xmin);
entity.set_xmax(xmax);
entities.push(entity);
}
manager.bulk_insert(entities).expect("versions");
manager.force_seal().expect("seal");
let snapshot = SnapshotContext {
snapshot: Snapshot {
xid: 10,
in_progress: HashSet::from([4]),
},
manager: Arc::new(SnapshotManager::new()),
own_xids: HashSet::new(),
requires_index_fallback: false,
serializable_reader: None,
};
let mut work = 0;
let mut callbacks = 0;
assert!(!manager.scan_batches(
Some(&snapshot),
|| {
work += 1;
work <= 2
},
|_| {
callbacks += 1;
true
}
));
assert_eq!(callbacks, 0, "a stopped batch is not consumed");
for (view, expected) in [(Some(&snapshot), vec![1, 3, 4]), (None, vec![2, 3])] {
let mut seen = Vec::new();
assert!(manager.scan_batches(
view,
|| true,
|batch| {
seen.extend(batch.iter().map(|entity| entity.id.raw()));
true
}
));
seen.sort_unstable();
assert_eq!(seen, expected);
}
}
#[test]
fn test_manager_basic() {
let manager = SegmentManager::new("test_collection");
let entity = UnifiedEntity::table_row(
manager.next_entity_id(),
"users",
1,
vec![Value::text("Alice".to_string())],
);
let id = manager.insert(entity).unwrap();
assert!(manager.get(id).is_some());
assert_eq!(manager.count(), 1);
}
#[test]
fn graph_pruning_preserves_physical_versions_and_charges_only_selected_segments() {
let manager = Arc::new(SegmentManager::new("mixed"));
manager
.bulk_insert(
(1..=128)
.map(|id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![]))
.collect(),
)
.expect("vector-only segment");
manager.force_seal().expect("seal vectors");
let mut old =
UnifiedEntity::graph_node(EntityId::new(200), "mixed", "person", Default::default());
old.set_xmin(3);
old.set_xmax(12);
let mut new =
UnifiedEntity::graph_node(EntityId::new(201), "mixed", "person", Default::default());
new.set_xmin(12);
let edge = UnifiedEntity::graph_edge(
EntityId::new(202),
"mixed",
"a",
"b",
1.0,
Default::default(),
);
manager
.bulk_insert(vec![old, new, edge])
.expect("physical graph versions");
manager.force_seal().expect("seal graph");
manager
.insert(UnifiedEntity::graph_node(
EntityId::new(203),
"mixed",
"person",
Default::default(),
))
.expect("growing node");
let snapshot = SnapshotContext {
snapshot: Snapshot {
xid: 10,
in_progress: HashSet::new(),
},
manager: Arc::new(SnapshotManager::new()),
own_xids: HashSet::new(),
requires_index_fallback: false,
serializable_reader: None,
};
std::thread::spawn(move || {
for view in [None, Some(&snapshot)] {
for kind in [GraphEntityKind::Node, GraphEntityKind::Edge] {
let expected: HashSet<_> = manager
.scan(view, |item| kind.matches(&item.kind))
.into_iter()
.map(|item| item.id)
.collect();
let actual: HashSet<_> = manager
.scan_graph_kind(view, kind)
.into_iter()
.map(|item| item.id)
.collect();
assert_eq!(actual, expected);
let mut visited = 0;
let mut candidates = HashSet::new();
manager.scan_graph_candidates_for_each(
view,
kind,
|| true,
|item| {
visited += 1;
if kind.matches(&item.kind) {
candidates.insert(item.id);
}
true
},
);
assert_eq!(candidates, expected);
assert_eq!(
visited,
if matches!(kind, GraphEntityKind::Node) {
3
} else {
2
}
);
}
}
let ids: HashSet<_> = manager
.scan_graph_kind(Some(&snapshot), GraphEntityKind::Node)
.into_iter()
.map(|item| item.id.raw())
.collect();
assert_eq!(ids, HashSet::from([200, 203]));
let ids: HashSet<_> = manager
.scan_graph_kind(None, GraphEntityKind::Node)
.into_iter()
.map(|item| item.id.raw())
.collect();
assert_eq!(ids, HashSet::from([201, 203]));
let mut visits = 0;
manager.scan_graph_candidates_for_each(
None,
GraphEntityKind::Node,
|| true,
|_| {
visits += 1;
false
},
);
assert_eq!(
visits, 1,
"early termination must also stop subsequent segments"
);
})
.join()
.expect("snapshot worker");
}
#[test]
fn snapshot_scan_applies_table_driven_visibility_on_fresh_thread() {
let manager = Arc::new(SegmentManager::new("accounts"));
let cases = [
("legacy row", 0, 0, true),
("committed creator", 3, 0, true),
("future creator", 11, 0, false),
("in-progress creator", 4, 0, false),
("committed deleter", 3, 7, false),
("future deleter", 3, 11, true),
("in-progress deleter", 3, 4, true),
];
for (index, (_, xmin, xmax, _)) in cases.iter().enumerate() {
let row_id = index as u64 + 1;
let mut entity = UnifiedEntity::table_row(
EntityId::new(row_id),
"accounts",
row_id,
vec![Value::Integer(row_id as i64)],
);
entity.set_xmin(*xmin);
entity.set_xmax(*xmax);
manager.insert(entity).unwrap();
}
let snapshot = SnapshotContext {
snapshot: Snapshot {
xid: 10,
in_progress: HashSet::from([4]),
},
manager: Arc::new(SnapshotManager::new()),
own_xids: HashSet::new(),
requires_index_fallback: false,
serializable_reader: None,
};
let raw_visible_row_ids: HashSet<u64> = manager
.query_all(|entity| entity_visible_with_context(Some(&snapshot), entity))
.into_iter()
.filter_map(|entity| match entity.kind {
EntityKind::TableRow { row_id, .. } => Some(row_id),
_ => None,
})
.collect();
let scanned = std::thread::spawn(move || manager.scan(Some(&snapshot), |_| true))
.join()
.unwrap();
let visible_row_ids: HashSet<u64> = scanned
.into_iter()
.filter_map(|entity| match entity.kind {
EntityKind::TableRow { row_id, .. } => Some(row_id),
_ => None,
})
.collect();
assert_eq!(visible_row_ids, raw_visible_row_ids);
for (index, (name, _, _, expected_visible)) in cases.iter().enumerate() {
let row_id = index as u64 + 1;
assert_eq!(
visible_row_ids.contains(&row_id),
*expected_visible,
"{name} visibility mismatch"
);
}
}
#[test]
fn frameless_scan_hides_superseded_versions_and_moderated_rows() {
// A `None` snapshot is the autocommit / prepared-fast-path read: it
// must keep the resolver fallback (xmax == 0), never show every
// version, and never panic (issue #2136 review).
let manager = SegmentManager::new("accounts");
let mut live =
UnifiedEntity::table_row(EntityId::new(1), "accounts", 1, vec![Value::Integer(1)]);
live.set_xmin(2);
live.set_xmax(0);
manager.insert(live).unwrap();
let mut superseded =
UnifiedEntity::table_row(EntityId::new(2), "accounts", 2, vec![Value::Integer(2)]);
superseded.set_xmin(2);
superseded.set_xmax(9);
manager.insert(superseded).unwrap();
let rows: Vec<u64> = manager
.scan(None, |_| true)
.into_iter()
.filter_map(|entity| match entity.kind {
EntityKind::TableRow { row_id, .. } => Some(row_id),
_ => None,
})
.collect();
assert_eq!(
rows,
vec![1],
"frameless scan must hide superseded versions"
);
}
#[test]
fn query_scan_callers_use_snapshot_api_for_visibility() {
let table = include_str!("../../runtime/query_exec/table.rs");
let aggregate = include_str!("../../runtime/query_exec/aggregate.rs");
assert_eq!(
table.matches(".for_each_entity(|entity|").count(),
1,
"only the visibility-independent schema inspection may use the raw table iterator"
);
assert!(!table.contains(".query_all_zoned_with_stats("));
assert!(!table.contains(".for_each_entity_zoned_with_stats("));
assert!(!table.contains("TableRowMvccReadResolver::captured"));
assert!(!aggregate.contains("TableRowMvccReadResolver"));
assert!(!aggregate.contains(".for_each_entity("));
assert!(!aggregate.contains(".fold_entities_parallel("));
}
#[test]
fn remaining_visibility_scan_callers_use_snapshot_api() {
let aggregate_pushdown =
include_str!("../../runtime/query_exec/aggregate_pushdown_dispatch.rs");
let ask = include_str!("../../runtime/ask_pipeline.rs");
let dml = include_str!("../../runtime/impl_dml.rs");
let dml_targets = include_str!("../../runtime/dml_target_scan.rs");
let events = include_str!("../../runtime/impl_events.rs");
let graph_commands = include_str!("../../runtime/impl_graph_commands.rs");
let graph_dsl = include_str!("../../runtime/graph_dsl.rs");
let graph_tvf = include_str!("../../runtime/graph_tvf.rs");
let kv = include_str!("../../runtime/impl_kv.rs");
let queue = include_str!("../../runtime/impl_queue.rs");
let primary_queue = include_str!("../../runtime/primary_queue_store.rs");
let record_search = include_str!("../../runtime/record_search.rs");
let search = include_str!("../../runtime/impl_search.rs");
let vector = include_str!("../../runtime/query_exec/vector.rs");
assert!(!aggregate_pushdown.contains("TableRowMvccReadResolver"));
assert!(!aggregate_pushdown.contains(".for_each_entity("));
assert!(!ask.contains("for entity in manager.query_all(|_| true)"));
assert!(!dml.contains("let entities = manager.query_all(|_| true);"));
// The DML target scan keeps raw iteration on purpose: its
// visibility is kind-conditional (live table rows at the tip
// version, everything else under the snapshot), which the uniform
// scan API cannot express. `candidate_visible` is the single gate.
assert_eq!(
dml_targets
.matches("self.candidate_visible(snapshot.as_ref(), entity)")
.count(),
2,
"both raw DML iterations must route through candidate_visible"
);
// The event-backfill dedup set is deliberately visibility-free:
// it must include consumed messages or backfill re-enqueues them.
assert_eq!(
events.matches("manager.query_all(").count(),
1,
"only the visibility-free backfill dedup may use query_all"
);
assert!(!graph_commands.contains("TableRowMvccReadResolver"));
assert!(!graph_dsl.contains("entity_visible_with_context(snap_ctx.as_ref(), e)"));
assert!(!graph_tvf.contains("entity_visible_with_context(snap_ctx.as_ref(), &entity)"));
assert!(!kv.contains("TableRowMvccReadResolver"));
assert!(!queue.contains("entity_visible_with_context(snap_ctx.as_ref(), entity)"));
assert!(!primary_queue.contains("entity_visible_with_context(snap_ctx.as_ref(), entity)"));
assert!(!record_search.contains("TableRowMvccReadResolver"));
assert!(!search.contains("for entity in manager.query_all(|_| true)"));
assert!(!vector.contains("manager.query_all("));
}
/// Strip `#[cfg(test)] mod … { … }` blocks so the raw-iteration gate
/// only sees production code. Blocks are matched at column zero and
/// closed by brace balance, which is why a file may carry a test
/// module in the middle and still keep production code after it.
fn production_source(src: &str) -> String {
let mut kept: Vec<&str> = Vec::new();
let lines: Vec<&str> = src.lines().collect();
let mut idx = 0;
while idx < lines.len() {
let starts_test_mod = lines[idx].starts_with("#[cfg(test)]")
&& lines
.get(idx + 1)
.is_some_and(|next| next.starts_with("mod "));
if !starts_test_mod {
kept.push(lines[idx]);
idx += 1;
continue;
}
idx += 1;
let mut depth: isize = 0;
while idx < lines.len() {
depth += lines[idx].matches('{').count() as isize;
depth -= lines[idx].matches('}').count() as isize;
idx += 1;
if depth <= 0 {
break;
}
}
}
kept.join("\n")
}
/// Count raw (visibility-bypassing) iteration entry points.
fn raw_iteration_sites(src: &str) -> usize {
src.matches("query_all(").count()
+ src.matches(".for_each_entity").count()
+ src.matches("fold_entities_parallel(").count()
}
#[test]
fn raw_iteration_confined_to_maintenance_allowlist() {
// The query paths migrated by Spec #2107 batches 1 and 2. Inside
// this perimeter raw iteration is maintenance-only: it bypasses
// MVCC visibility entirely, so every remaining site is either an
// internal catalog/bookkeeping read that must observe all physical
// versions, or one of the three exceptions the batch reviews
// documented. A new raw-iteration site changes the count and fails
// this gate — route it through `SegmentManager::scan*` instead.
let allowlist: &[(&str, &str, usize, &str)] = &[
(
"runtime/query_exec/table.rs",
include_str!("../../runtime/query_exec/table.rs"),
1,
"documented exception: schema inspection (does the collection ever \
observe these fields?) is visibility-independent",
),
(
"runtime/query_exec/aggregate.rs",
include_str!("../../runtime/query_exec/aggregate.rs"),
0,
"fully migrated by batch 1",
),
(
"runtime/query_exec/aggregate_pushdown_dispatch.rs",
include_str!("../../runtime/query_exec/aggregate_pushdown_dispatch.rs"),
0,
"fully migrated by batch 1",
),
(
"runtime/query_exec/vector.rs",
include_str!("../../runtime/query_exec/vector.rs"),
0,
"fully migrated by batch 2",
),
(
"runtime/ask_pipeline.rs",
include_str!("../../runtime/ask_pipeline.rs"),
0,
"fully migrated by batch 2",
),
(
"runtime/impl_dml.rs",
include_str!("../../runtime/impl_dml.rs"),
1,
"documented exception: ON CONFLICT resolves a unique key against \
physical versions on purpose. A snapshot scan cannot see a row an \
uncommitted concurrent writer already holds the key for, which is \
exactly the case that must raise a serialization conflict rather \
than insert a duplicate; the same pass reaps index entries left by \
aborted writers. \
TODO(#2263 follow-up): narrow the candidates through the unique \
index instead of walking the collection",
),
(
"runtime/dml_target_scan.rs",
include_str!("../../runtime/dml_target_scan.rs"),
2,
"documented exception: kind-conditional visibility the uniform scan \
API cannot express; both iterations gate on candidate_visible",
),
(
"runtime/impl_events.rs",
include_str!("../../runtime/impl_events.rs"),
1,
"documented exception: backfill dedup must include consumed messages, \
so it is deliberately visibility-free",
),
(
"runtime/impl_graph_commands.rs",
include_str!("../../runtime/impl_graph_commands.rs"),
0,
"native node properties resolve one snapshot-visible, RLS-admitted version",
),
(
"runtime/graph_dsl.rs",
include_str!("../../runtime/graph_dsl.rs"),
1,
"remaining legacy debt: unused edge-property helper; search expansion \
now uses snapshot visitors and RLS-gated hydration",
),
(
"runtime/graph_tvf.rs",
include_str!("../../runtime/graph_tvf.rs"),
0,
"fully migrated by batch 2",
),
(
"runtime/impl_kv.rs",
include_str!("../../runtime/impl_kv.rs"),
4,
"two non-versioned-collection fallbacks (the versioned arms scan under \
the captured snapshot). Vault reads use snapshot scans. Offline vault \
export preserves all \
physical versions across tenants; restore's emptiness check must reject \
every physical row, including versions invisible to a snapshot",
),
(
"runtime/impl_queue.rs",
include_str!("../../runtime/impl_queue.rs"),
10,
"maintenance: red_queue_meta bookkeeping (config, groups, acks, \
pending, dedup TTL reaper, gauge counts) — queue message bodies are \
read through scan. \
TODO(#2138 follow-up): QUEUE PENDING projects meta rows to clients",
),
(
"runtime/primary_queue_store.rs",
include_str!("../../runtime/primary_queue_store.rs"),
3,
"maintenance: generic red_queue_meta read/delete helpers and the \
next-position allocator, which must not collide with rows invisible \
to the writer's snapshot",
),
(
"runtime/record_search.rs",
include_str!("../../runtime/record_search.rs"),
0,
"fully migrated by batch 2",
),
(
"runtime/search_graph.rs",
include_str!("../../runtime/search_graph.rs"),
0,
"search graph preparation uses snapshot visitors and gated hydration",
),
(
"runtime/impl_search.rs",
include_str!("../../runtime/impl_search.rs"),
1,
"maintenance: ask-audit retention sweep must see every physical row",
),
];
for (path, src, allowed, reason) in allowlist {
let found = raw_iteration_sites(&production_source(src));
assert_eq!(
found, *allowed,
"{path}: {found} raw-iteration sites, allowlist permits {allowed} \
({reason}). Raw iteration bypasses MVCC visibility — use \
SegmentManager::scan / scan_for_each / scan_fold_parallel / \
scan_zoned_with_stats, or extend the allowlist with a maintenance \
justification."
);
}
}
#[test]
fn explicit_snapshot_scan_ignores_ambient_thread_local() {
let manager = Arc::new(SegmentManager::new("accounts"));
// (xmin, xmax) — mix of committed, in-progress and future writers.
let versions = [(0, 0), (3, 0), (11, 0), (4, 0), (3, 7), (3, 11), (3, 4)];
for (index, (xmin, xmax)) in versions.iter().enumerate() {
let row_id = index as u64 + 1;
let mut entity = UnifiedEntity::table_row(
EntityId::new(row_id),
"accounts",
row_id,
vec![Value::Integer(row_id as i64)],
);
entity.set_xmin(*xmin);
entity.set_xmax(*xmax);
manager.insert(entity).unwrap();
}
let explicit = SnapshotContext {
snapshot: Snapshot {
xid: 10,
in_progress: HashSet::from([4]),
},
manager: Arc::new(SnapshotManager::new()),
own_xids: HashSet::new(),
requires_index_fallback: false,
serializable_reader: None,
};
// A decoy statement frame that would hide almost everything if the
// scan ever consulted ambient state instead of its argument.
let decoy = SnapshotContext {
snapshot: Snapshot {
xid: 1,
in_progress: HashSet::new(),
},
manager: Arc::new(SnapshotManager::new()),
own_xids: HashSet::new(),
requires_index_fallback: false,
serializable_reader: None,
};
let row_ids = |entities: Vec<UnifiedEntity>| -> HashSet<u64> {
entities
.into_iter()
.filter_map(|entity| match entity.kind {
EntityKind::TableRow { row_id, .. } => Some(row_id),
_ => None,
})
.collect()
};
let guard = crate::runtime::execution_context::CurrentSnapshotGuard::install(decoy);
let on_installing_thread = row_ids(manager.scan(Some(&explicit), |_| true));
drop(guard);
let spawned_manager = Arc::clone(&manager);
let spawned_snapshot = explicit.clone();
let on_fresh_thread = std::thread::spawn(move || {
row_ids(spawned_manager.scan(Some(&spawned_snapshot), |_| true))
})
.join()
.unwrap();
assert_eq!(
on_installing_thread, on_fresh_thread,
"an explicit snapshot must produce the same visible set on any thread"
);
assert_eq!(on_installing_thread, HashSet::from([1, 2, 6, 7]));
// The raw iterators are the maintenance contract: no visibility
// filtering at all, on any thread, regardless of installed frames.
let raw_manager = Arc::clone(&manager);
let raw_count = std::thread::spawn(move || raw_manager.query_all(|_| true).len())
.join()
.unwrap();
assert_eq!(
raw_count,
versions.len(),
"raw iteration must expose every physical version"
);
}
#[test]
fn bloom_may_contain_key_probes_inserted_rid_bytes() {
let manager = SegmentManager::new("test_collection");
let entity = UnifiedEntity::table_row(
manager.next_entity_id(),
"users",
1,
vec![Value::text("Alice".to_string())],
);
let id = manager.insert(entity).unwrap();
assert!(manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
assert!(manager.bloom_may_contain_key(id.raw().to_string().as_bytes()));
assert!(!manager.bloom_may_contain_key(&u64::MAX.to_le_bytes()));
assert!(manager.delete(id).unwrap());
assert!(!manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
}
#[test]
fn zoned_scan_reports_pruned_segments_and_preserves_results() {
let config = ManagerConfig {
segment_config: SegmentConfig {
max_entities: 2,
..Default::default()
},
..Default::default()
};
let manager = SegmentManager::with_config("events", config);
for (idx, value) in [10, 20, 100, 110, 200].into_iter().enumerate() {
let row = RowData::with_names(vec![Value::Integer(value)], vec!["ts".to_string()]);
let entity = UnifiedEntity::new(
manager.next_entity_id(),
EntityKind::TableRow {
table: "events".into(),
row_id: (idx + 1) as u64,
},
EntityData::Row(row),
);
manager.insert(entity).unwrap();
}
let full = manager.query_all(|entity| match &entity.data {
EntityData::Row(row) => matches!(row.get_field("ts"), Some(Value::Integer(100))),
_ => false,
});
let probe = Value::Integer(100);
let (pruned, stats) =
manager.query_all_zoned_with_stats(&[("ts", ZoneColPred::Eq(&probe))], |entity| {
match &entity.data {
EntityData::Row(row) => {
matches!(row.get_field("ts"), Some(Value::Integer(100)))
}
_ => false,
}
});
assert_eq!(pruned.len(), full.len());
assert_eq!(pruned[0].id, full[0].id);
assert_eq!(stats.segments_total, 3);
assert_eq!(stats.segments_scanned, 2);
assert_eq!(stats.segments_pruned, 1);
}
#[test]
fn test_manager_auto_seal() {
let config = ManagerConfig {
segment_config: SegmentConfig {
max_entities: 2,
..Default::default()
},
..Default::default()
};
let manager = SegmentManager::with_config("test", config);
// Insert first entity
manager
.insert(UnifiedEntity::vector(
manager.next_entity_id(),
"v",
vec![0.1],
))
.unwrap();
// Insert second entity (triggers seal check)
manager
.insert(UnifiedEntity::vector(
manager.next_entity_id(),
"v",
vec![0.2],
))
.unwrap();
// Insert third entity (should trigger auto-seal of first segment)
manager
.insert(UnifiedEntity::vector(
manager.next_entity_id(),
"v",
vec![0.3],
))
.unwrap();
let stats = manager.stats();
assert_eq!(stats.total_entities, 3);
}
#[test]
fn test_manager_delete() {
let manager = SegmentManager::new("test");
let id = manager
.insert(UnifiedEntity::vector(
manager.next_entity_id(),
"v",
vec![0.1],
))
.unwrap();
assert!(manager.get(id).is_some());
assert!(manager.delete(id).unwrap());
assert!(manager.get(id).is_none());
}
#[test]
fn test_manager_metadata() {
let manager = SegmentManager::new("test");
let id = manager
.insert(UnifiedEntity::table_row(
manager.next_entity_id(),
"hosts",
1,
vec![Value::text("192.168.1.1".to_string())],
))
.unwrap();
let mut meta = Metadata::new();
meta.set(
"os",
super::super::metadata::MetadataValue::String("linux".to_string()),
);
manager.set_metadata(id, meta).unwrap();
let retrieved = manager.get_metadata(id).unwrap();
assert!(retrieved.has("os"));
}
#[test]
fn test_manager_query_by_kind() {
let manager = SegmentManager::new("test");
manager
.insert(UnifiedEntity::table_row(
manager.next_entity_id(),
"hosts",
1,
vec![],
))
.unwrap();
manager
.insert(UnifiedEntity::vector(
manager.next_entity_id(),
"embeddings",
vec![0.1],
))
.unwrap();
manager
.insert(UnifiedEntity::table_row(
manager.next_entity_id(),
"hosts",
2,
vec![],
))
.unwrap();
let rows = manager.get_by_kind("table");
assert_eq!(rows.len(), 2);
let vectors = manager.get_by_kind("vector");
assert_eq!(vectors.len(), 1);
}
// ========================================================================
// Consolidation — ADR 0073 §5
// ========================================================================
/// A manager whose sealed set never trips the count trigger, so tests can
/// exercise the tombstone/fragmentation triggers in isolation.
fn consolidating_manager(entities_per_tick: usize) -> SegmentManager {
SegmentManager::with_config(
"test",
ManagerConfig {
max_sealed_segments: 1_000,
consolidation_entities_per_tick: entities_per_tick,
..Default::default()
},
)
}
/// Bulk-load `count` rows into a fresh segment and seal it. Bulk-inserted
/// entities land in flat storage, where a tombstone keeps its payload
/// resident — which is the memory consolidation reclaims.
fn seal_bulk_segment(manager: &SegmentManager, count: usize) -> Vec<EntityId> {
let entities: Vec<UnifiedEntity> = (0..count)
.map(|i| {
UnifiedEntity::table_row(
manager.next_entity_id(),
"users",
i as u64,
vec![Value::Integer(i as i64), Value::text(format!("row-{i}"))],
)
})
.collect();
let ids = manager.bulk_insert(entities).expect("bulk insert");
manager.force_seal().expect("seal");
ids
}
fn live_ids(manager: &SegmentManager) -> Vec<u64> {
let mut ids: Vec<u64> = manager
.query_all(|_| true)
.into_iter()
.map(|entity| entity.id.raw())
.collect();
ids.sort_unstable();
ids
}
fn drain_maintenance(manager: &SegmentManager) -> usize {
let mut ticks = 0;
while manager.consolidation.read().is_some() || ticks == 0 {
manager.run_maintenance().expect("maintenance");
ticks += 1;
assert!(ticks < 1_000, "consolidation failed to converge");
}
ticks
}
#[test]
fn graph_index_batches_pin_sources_and_hydrate_current_after_consolidation() {
let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
let ids = manager
.bulk_insert(
(1..=1024)
.map(|id| {
UnifiedEntity::graph_edge(
EntityId::new(id),
"step",
"2000",
"3000",
1.0,
HashMap::new(),
)
})
.collect(),
)
.expect("edges");
manager.force_seal().expect("seal");
for id in ids.iter().take(300) {
manager.delete(*id).expect("fragment source");
}
let source = Arc::downgrade(&manager.sealed.read()[0]);
let mut seen = Vec::new();
let mut changed = false;
let mut metadata_bytes = 0;
assert!(manager.visit_graph_index_batches(GraphEntityKind::Edge, &[EntityId::new(2000)],
|| true,
|bytes| { metadata_bytes += bytes; Ok::<_, ()>(()) },
|batch| {
assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
assert!(manager.growing.try_write().is_some(), "no growing topology guard");
assert!(manager.sealed.try_write().is_some(), "no sealed topology guard");
assert!(source.upgrade().expect("source pinned").try_write().is_some(), "no source guard");
if !changed {
changed = true;
drain_maintenance(&manager);
assert!(manager.stats().consolidation.runs_completed > 0);
assert!(source.upgrade().is_some(), "retired cursor source remains pinned");
let mut updated = manager.get(EntityId::new(1024)).expect("future edge");
if let EntityKind::GraphEdge(edge) = &mut updated.kind { edge.weight = 2000; }
manager.update(updated).expect("update authoritative merged copy");
}
for id in batch {
let entity = manager.get(*id).expect("hydrate current manager");
if id.raw() == 1024 {
assert!(matches!(&entity.kind, EntityKind::GraphEdge(edge) if edge.weight == 2000));
}
seen.push(id.raw());
}
Ok(true)
}).expect("cursor"));
assert_eq!(seen, (301..=1024).collect::<Vec<_>>());
assert!(
source.upgrade().is_none(),
"finished cursor releases retired source"
);
assert!(
metadata_bytes < 4096,
"fixed ID buffer plus source handles: {metadata_bytes}"
);
}
#[test]
fn graph_index_batches_propagate_admission_and_cancel_before_partial_delivery() {
let manager = SegmentManager::new("graph");
manager
.bulk_insert(
(1..=1024)
.map(|id| {
UnifiedEntity::graph_edge(
EntityId::new(id),
"step",
"2000",
"3000",
1.0,
HashMap::new(),
)
})
.collect(),
)
.expect("edges");
let mut delivered = 0;
let denied = manager.visit_graph_index_batches(
GraphEntityKind::Edge,
&[EntityId::new(2000)],
|| true,
|_| Err("out of memory"),
|ids| {
delivered += ids.len();
Ok(true)
},
);
assert_eq!(denied, Err("out of memory"));
assert_eq!(delivered, 0);
let mut work = 0;
assert!(!manager
.visit_graph_index_batches(
GraphEntityKind::Edge,
&[EntityId::new(2000)],
|| {
work += 1;
work < 100
},
|_| Ok::<_, ()>(()),
|ids| {
delivered += ids.len();
Ok(true)
}
)
.expect("cancelled cursor"));
assert_eq!(
delivered, 0,
"cancelled partial batch cannot reach consumer"
);
assert!(!manager
.visit_graph_index_batches(
GraphEntityKind::Edge,
&[EntityId::new(2000)],
|| true,
|_| Ok::<_, ()>(()),
|ids| {
delivered += ids.len();
Ok(false)
}
)
.expect("consumer stop"));
assert_eq!(delivered, super::super::segment::SCAN_BATCH_SIZE);
}
#[test]
fn retained_memory_tracks_two_readers_until_the_last_cursor_finishes() {
let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
let ids = seal_bulk_segment(&manager, 100);
for id in ids.iter().take(40) {
manager.delete(*id).expect("delete before scan");
}
let source_bytes = manager.resident_bytes();
let source = Arc::downgrade(&manager.sealed.read()[0]);
std::thread::scope(|scope| {
let (ready, waiting) = std::sync::mpsc::channel();
let (release_first, first_wait) = std::sync::mpsc::channel();
let (release_last, last_wait) = std::sync::mpsc::channel();
let reader = |resume: std::sync::mpsc::Receiver<()>,
ready: std::sync::mpsc::Sender<()>| {
assert!(manager.scan_batches(
None,
|| true,
|_| {
ready.send(()).expect("signal captured cursor");
let _ = resume.recv();
true
}
));
};
let ready_first = ready.clone();
let first = scope.spawn(move || reader(first_wait, ready_first));
let last = scope.spawn(move || reader(last_wait, ready));
for _ in 0..2 {
waiting
.recv_timeout(std::time::Duration::from_secs(10))
.expect("reader ready");
}
drain_maintenance(&manager);
assert!(
source.upgrade().is_some(),
"both cursors pin the retired source"
);
let active_bytes = manager.sealed.read()[0].read().resident_bytes();
let held = manager.resident_bytes();
assert!(
held >= active_bytes + source_bytes,
"retired source remains resident"
);
release_first.send(()).expect("release first reader");
first.join().expect("first reader");
assert_eq!(
manager.resident_bytes(),
held,
"one reader still pins the source"
);
release_last.send(()).expect("release last reader");
last.join().expect("last reader");
assert!(
source.upgrade().is_none(),
"accounting must not retain payloads"
);
assert_eq!(held - manager.resident_bytes(), source_bytes);
assert_eq!(
manager.stats().total_memory_bytes as u64,
manager.resident_bytes()
);
});
}
#[test]
fn retained_memory_gates_runtime_growth_until_the_cursor_is_cancelled() {
use crate::storage::memory_pools::MemoryPool;
use crate::{RedDBOptions, RedDBRuntime};
let budget = 128 * 1024;
let runtime =
RedDBRuntime::with_options(RedDBOptions::in_memory().with_memory_budget(budget))
.expect("runtime");
runtime
.db()
.store()
.create_collection("test")
.expect("collection");
let manager = runtime
.db()
.store()
.get_collection("test")
.expect("manager");
let ids = seal_bulk_segment(&manager, 100);
for id in ids.iter().take(40) {
manager.delete(*id).expect("delete before scan");
}
let source_bytes = manager.resident_bytes();
let mut growth = 0;
let mut held_used = 0;
assert!(!manager.scan_batches(
None,
|| true,
|_| {
drain_maintenance(&manager);
runtime.refresh_memory_accounting();
// Other collections (including the runtime catalog) share this
// arena, so derive headroom from the complete runtime sample.
held_used = runtime.memory_accounting().total_used_bytes();
growth = budget
.checked_sub(held_used)
.expect("fixture fits while the cursor is open")
+ source_bytes / 2;
assert!(growth > 0);
assert!(
runtime
.admit_non_evictable_growth(
MemoryPool::SegmentArena,
"growth with pinned source",
growth,
)
.is_err(),
"retained source must participate in runtime admission"
);
false
}
));
runtime.refresh_memory_accounting();
assert_eq!(
held_used - runtime.memory_accounting().total_used_bytes(),
source_bytes
);
let _reservation = runtime
.admit_non_evictable_growth(
MemoryPool::SegmentArena,
"growth after cursor cancellation",
growth,
)
.expect("the same growth fits once the cursor releases its source");
}
#[test]
fn retained_memory_includes_an_inflight_consolidation_copy() {
let manager = consolidating_manager(1);
let ids = seal_bulk_segment(&manager, 100);
for id in ids.iter().take(40) {
manager.delete(*id).expect("delete");
}
let before = manager.resident_bytes();
assert!(manager.pressure_consolidation_tick());
let copied = manager
.consolidation
.read()
.as_ref()
.expect("paced merge")
.merged
.resident_bytes();
assert!(copied > 0);
assert!(
manager.resident_bytes() >= before + copied,
"unpublished copy consumes memory"
);
drain_maintenance(&manager);
assert!(
manager.resident_bytes() < before,
"completed merge releases the old storage"
);
}
#[test]
fn delete_heavy_workload_reclaims_tombstoned_memory_and_counts_it() {
let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
let ids = seal_bulk_segment(&manager, 100);
let bytes_before_delete = manager.resident_bytes();
// 40% tombstones — past CONSOLIDATION_TOMBSTONE_RATIO.
for id in ids.iter().take(40) {
assert!(manager.delete(*id).expect("delete"));
}
// Tombstones cost memory: the payload stays resident in flat storage
// and the tombstone set grows.
let bytes_with_tombstones = manager.resident_bytes();
assert!(bytes_with_tombstones > bytes_before_delete);
let survivors = live_ids(&manager);
assert_eq!(survivors.len(), 60);
drain_maintenance(&manager);
let stats = manager.stats();
assert_eq!(stats.consolidation.runs_started, 1);
assert_eq!(stats.consolidation.runs_completed, 1);
assert_eq!(stats.consolidation.segments_merged, 1);
assert_eq!(stats.consolidation.tombstones_reclaimed, 40);
assert!(stats.consolidation.bytes_reclaimed > 0);
// The reclaimed memory is at least the tombstoned entities' share.
let bytes_after = manager.resident_bytes();
assert!(
bytes_after <= bytes_before_delete,
"consolidation must return the tombstones' memory: {bytes_after} > {bytes_before_delete}"
);
assert_eq!(
bytes_with_tombstones - bytes_after,
stats.consolidation.bytes_reclaimed
);
assert_eq!(stats.total_memory_bytes, bytes_after as usize);
assert_eq!(live_ids(&manager), survivors);
assert_eq!(manager.sealed.read().len(), 1);
assert_eq!(manager.sealed.read()[0].read().tombstone_count(), 0);
}
#[test]
fn query_results_are_identical_before_during_and_after_consolidation() {
let manager = consolidating_manager(3);
let ids = seal_bulk_segment(&manager, 20);
seal_bulk_segment(&manager, 20);
for id in ids.iter().take(10) {
assert!(manager.delete(*id).expect("delete"));
}
let before = live_ids(&manager);
let survivor = *ids.last().expect("at least one row");
let tombstoned = ids[0];
// Every mid-tick observation matches the pre-consolidation snapshot:
// point reads, full scans, and the kind index (rebuilt by the merge).
let mut mid_tick_observations = 0;
while manager.consolidation.read().is_some() || mid_tick_observations == 0 {
manager.run_maintenance().expect("maintenance");
assert_eq!(live_ids(&manager), before);
assert!(manager.get(survivor).is_some());
assert!(manager.get(tombstoned).is_none());
assert_eq!(manager.get_by_kind("table").len(), before.len());
mid_tick_observations += 1;
assert!(mid_tick_observations < 1_000);
}
assert!(
mid_tick_observations > 2,
"expected the run to span several ticks, saw {mid_tick_observations}"
);
assert_eq!(live_ids(&manager), before);
assert!(manager.get(survivor).is_some());
assert!(manager.get(tombstoned).is_none());
assert_eq!(manager.get_by_kind("table").len(), before.len());
}
#[test]
fn get_by_kind_reaches_sealed_segments() {
let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
let ids = seal_bulk_segment(&manager, 5);
assert!(manager.delete(ids[0]).expect("delete"));
// The sealed list is walked through the segment read guard; the
// `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` cannot hand out
// references across the lock and yields nothing.
assert_eq!(manager.get_by_kind("table").len(), 4);
assert_eq!(manager.get_by_kind("vector").len(), 0);
}
#[test]
fn consolidation_is_paced_by_the_per_tick_entity_bound() {
const PER_TICK: usize = 4;
let manager = consolidating_manager(PER_TICK);
let ids = seal_bulk_segment(&manager, 60);
for id in ids.iter().take(30) {
assert!(manager.delete(*id).expect("delete"));
}
// First tick opens the run and copies exactly one bound's worth.
manager.run_maintenance().expect("maintenance");
assert_eq!(manager.consolidation_progress(), Some(PER_TICK as u64));
// Each subsequent tick advances by no more than the bound, and the run
// is still in flight — it never completes in one unbounded pass.
let mut previous = PER_TICK as u64;
let mut ticks = 1;
while let Some(copied) = manager.consolidation_progress() {
assert!(
copied - previous <= PER_TICK as u64,
"tick copied {} entities, bound is {PER_TICK}",
copied - previous
);
previous = copied;
manager.run_maintenance().expect("maintenance");
ticks += 1;
assert!(ticks < 100);
}
// 30 survivors at 4 per tick: the run cannot have finished before the
// eighth tick.
assert!(ticks >= 8, "consolidation completed in only {ticks} ticks");
assert_eq!(manager.stats().consolidation.runs_completed, 1);
assert_eq!(live_ids(&manager).len(), 30);
}
#[test]
fn sealed_segment_count_above_the_limit_triggers_a_merge() {
let manager = SegmentManager::with_config(
"test",
ManagerConfig {
max_sealed_segments: 3,
..Default::default()
},
);
for _ in 0..4 {
seal_bulk_segment(&manager, 5);
}
assert_eq!(manager.sealed.read().len(), 4);
let before = live_ids(&manager);
drain_maintenance(&manager);
// The knob finally does what it claimed: the sealed set collapses even
// though not a single row was deleted.
assert_eq!(manager.sealed.read().len(), 1);
assert_eq!(manager.stats().consolidation.segments_merged, 4);
assert_eq!(manager.stats().consolidation.tombstones_reclaimed, 0);
assert_eq!(live_ids(&manager), before);
}
#[test]
fn a_clean_sealed_set_below_the_limit_is_never_consolidated() {
let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
seal_bulk_segment(&manager, 10);
seal_bulk_segment(&manager, 10);
for _ in 0..5 {
manager.run_maintenance().expect("maintenance");
}
assert_eq!(manager.stats().consolidation.runs_started, 0);
assert_eq!(manager.sealed.read().len(), 2);
}
#[test]
fn concurrent_readers_never_observe_a_missing_or_duplicated_entity() {
use std::sync::atomic::AtomicBool;
let manager = Arc::new(consolidating_manager(2));
let ids = seal_bulk_segment(&manager, 40);
seal_bulk_segment(&manager, 40);
for id in ids.iter().take(20) {
assert!(manager.delete(*id).expect("delete"));
}
let expected = live_ids(&manager);
let stop = Arc::new(AtomicBool::new(false));
let readers: Vec<_> = (0..4)
.map(|_| {
let manager = Arc::clone(&manager);
let stop = Arc::clone(&stop);
let expected = expected.clone();
std::thread::spawn(move || {
let mut scans = 0u64;
// Do-while: every reader scans at least once even when the
// drain finishes before this thread is first scheduled.
loop {
let mut seen: Vec<u64> = manager
.query_all(|_| true)
.into_iter()
.map(|entity| entity.id.raw())
.collect();
seen.sort_unstable();
// Sorting is not enough: a duplicated row would keep
// the set equal but change the length.
assert_eq!(seen, expected, "reader saw a torn sealed set");
scans += 1;
if stop.load(Ordering::Relaxed) {
break;
}
}
scans
})
})
.collect();
drain_maintenance(&manager);
stop.store(true, Ordering::Relaxed);
for reader in readers {
let scans = reader.join().expect("reader thread");
assert!(scans > 0, "reader never got to scan");
}
assert_eq!(manager.stats().consolidation.runs_completed, 1);
assert_eq!(live_ids(&manager), expected);
}
#[test]
fn a_row_deleted_mid_consolidation_is_not_resurrected_by_the_swap() {
let manager = consolidating_manager(4);
let ids = seal_bulk_segment(&manager, 20);
for id in ids.iter().take(6) {
assert!(manager.delete(*id).expect("delete"));
}
// Copy the first bound's worth, then delete a row we just copied.
manager.run_maintenance().expect("maintenance");
assert_eq!(manager.consolidation_progress(), Some(4));
let doomed = ids[6];
assert!(manager.delete(doomed).expect("delete"));
let expected = live_ids(&manager);
drain_maintenance(&manager);
assert!(manager.get(doomed).is_none(), "deleted row came back");
assert_eq!(live_ids(&manager), expected);
}
#[test]
fn discarding_an_in_flight_consolidation_leaves_the_data_untouched() {
let manager = consolidating_manager(3);
let ids = seal_bulk_segment(&manager, 30);
for id in ids.iter().take(12) {
assert!(manager.delete(*id).expect("delete"));
}
let before = live_ids(&manager);
let sealed_before: Vec<SegmentId> = manager
.sealed
.read()
.iter()
.map(|segment| segment.read().id())
.collect();
manager.run_maintenance().expect("maintenance");
manager.run_maintenance().expect("maintenance");
assert!(manager.consolidation.read().is_some());
// A crash between ticks drops the half-built merged segment. Sealed
// segments are the durable truth, so nothing was lost — and the run is
// simply started over.
*manager.consolidation.write() = None;
assert_eq!(live_ids(&manager), before);
let sealed_after: Vec<SegmentId> = manager
.sealed
.read()
.iter()
.map(|segment| segment.read().id())
.collect();
assert_eq!(sealed_after, sealed_before);
assert_eq!(manager.stats().consolidation.runs_completed, 0);
drain_maintenance(&manager);
assert_eq!(live_ids(&manager), before);
assert_eq!(manager.stats().consolidation.runs_completed, 1);
}
#[test]
fn consolidation_preserves_entity_payload_metadata_and_sequence() {
let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
// Metadata must be attached before the seal: `set_metadata` on a sealed
// row rewrites it into the growing segment, which would take it out of
// the segment under test.
let entities: Vec<UnifiedEntity> = (0..10)
.map(|i| {
UnifiedEntity::table_row(
manager.next_entity_id(),
"users",
i as u64,
vec![Value::Integer(i as i64)],
)
})
.collect();
let ids = manager.bulk_insert(entities).expect("bulk insert");
let mut meta = Metadata::new();
meta.set(
"os",
super::super::metadata::MetadataValue::String("linux".to_string()),
);
manager.set_metadata(ids[9], meta).expect("set metadata");
manager.force_seal().expect("seal");
assert!(manager.delete(ids[0]).expect("delete"));
assert!(manager.delete(ids[1]).expect("delete"));
assert!(manager.delete(ids[2]).expect("delete"));
let before: Vec<UnifiedEntity> = {
let mut entities = manager.query_all(|_| true);
entities.sort_by_key(|entity| entity.id.raw());
entities
};
drain_maintenance(&manager);
let after: Vec<UnifiedEntity> = {
let mut entities = manager.query_all(|_| true);
entities.sort_by_key(|entity| entity.id.raw());
entities
};
let columns = |entity: &UnifiedEntity| match &entity.data {
super::super::entity::EntityData::Row(row) => row.columns.clone(),
_ => Vec::new(),
};
assert_eq!(before.len(), after.len());
for (old, new) in before.iter().zip(after.iter()) {
assert_eq!(old.id, new.id);
assert_eq!(columns(old), columns(new));
assert_eq!(
old.sequence_id, new.sequence_id,
"merge must not re-issue sequence ids"
);
}
assert!(manager
.get_metadata(ids[9])
.expect("metadata survives the merge")
.has("os"));
}
#[test]
#[ignore = "lifecycle events intentionally no-op since the emit-channel refactor; drain_events returns empty — see SegmentManager::emit"]
fn test_lifecycle_events() {
let manager = SegmentManager::new("test");
manager
.insert(UnifiedEntity::vector(
manager.next_entity_id(),
"v",
vec![0.1],
))
.unwrap();
let events = manager.drain_events();
// Should have: SegmentCreated, EntityInserted
assert!(events
.iter()
.any(|e| matches!(e, LifecycleEvent::SegmentCreated(_))));
assert!(events
.iter()
.any(|e| matches!(e, LifecycleEvent::EntityInserted(_, _))));
}
}