surrealdb-core 3.3.1

A scalable, distributed, collaborative, document-graph database, for the realtime web
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
use std::any::TypeId;
use std::borrow::Cow;
#[cfg(not(target_family = "wasm"))]
use std::collections::HashMap;
#[cfg(not(target_family = "wasm"))]
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::{self, Display};
#[cfg(storage)]
use std::path::PathBuf;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Poll, ready};
use std::time::Duration;

#[allow(unused_imports)]
use anyhow::bail;
use anyhow::{Context as _, Result, ensure};
use arc_swap::ArcSwap;
use async_channel::Sender;
use bytes::{Bytes, BytesMut};
use common::time::{Instant, sleep, timeout, timeout_at};
use futures::{Future, Stream};
use rand::Rng;
use rand::distr::{Alphanumeric, SampleString};
use reblessive::TreeStack;
use surrealdb_cnf::ConfigMap;
use surrealdb_cnf::dynamic::DynamicConfiguration;
use surrealdb_datastore::triggers::CommitTriggers;
use surrealdb_datastore::values::graph::GraphFoldScope;
use surrealdb_kvs::TransactionType::*;
use surrealdb_kvs::{DestroyRange, DestroyRangeHandle, TransactionType};
use surrealdb_types::{AuthError, Error as TypesError, SurrealValue, object};
#[cfg(not(target_family = "wasm"))]
use tokio::spawn;
use tokio_util::sync::CancellationToken;
use tracing::{debug, instrument, trace, warn};
use uuid::Uuid;

use super::tx::Transaction;
use super::version::{MajorVersion, MigrationRecord, StorageVersion, VersionHistoryEntry};
use super::{INDEX_COMPACTION_QUEUE_BATCH_SIZE, migration};
use crate::api::err::ApiError;
use crate::api::invocation::process_api_request;
use crate::api::request::ApiRequest;
use crate::api::response::ApiResponse;
use crate::buc::manager::BucketsManager;
use crate::catalog::providers::{
	CatalogProvider, DatabaseProvider, NamespaceProvider, NodeProvider, RootProvider,
	TableProvider, UserProvider,
};
use crate::catalog::{Index, NodeLiveQuery};
use crate::config::RuntimeConfig;
use crate::ctx::{CancelHandle, Context, FrozenContext};
#[cfg(feature = "jwks")]
use crate::dbs::capabilities::NetTarget;
use crate::dbs::capabilities::{
	ArbitraryQueryTarget, EvalQueryTarget, ExperimentalTarget, MethodTarget, RouteTarget,
};
use crate::dbs::node::{Node, Timestamp};
use crate::dbs::{
	Capabilities, DurableSession, Executor, MessageBroker, Options, QueryResult,
	QueryResultBuilder, QueryStreamItem, QueryStreamJob, Session, TopLevelStatement,
	durable_session, restore_session,
};
use crate::doc::process_next_events_batch;
use crate::err::{EngineError, Error};
use crate::exe::FlowResultExt as _;
use crate::exec::Error as ExecError;
use crate::exec::config::ExecConfig;
use crate::exec::function::FunctionRegistry;
use crate::expr::model::get_model_path;
use crate::expr::statements::define::DefineKind;
use crate::expr::statements::{DefineModelStatement, DefineStatement, DefineUserStatement};
use crate::expr::user::UserDuration;
use crate::expr::{Base, Expr, Idiom, Literal, LogicalPlan, TopLevelExpr};
#[cfg(feature = "http")]
use crate::http::HttpClient;
use crate::iam::{Action, Auth, PolicyError, Resource, ResourceKind, Role, ScramCredential};
use crate::idx::IndexKeyBase;
use crate::idx::index::IndexOperation;
use crate::idx::trees::hnsw::index::HnswCompactionOutcome;
use crate::idx::trees::store::IndexStores;
use crate::key::reclaim::{Expunge, ReclaimKind, ReclaimState};
use crate::key::schema::{
	BootstrapKey, DbRoot, DocKeyPrefix, DocLookupIdentityPrefix, DocLookupPrefix, DocPendingPrefix,
	GraphFoldDirPrefix, GraphFoldKey, GraphFoldPrefix, IdxRoot, IndexCompactionIxPrefix,
	IndexCompactionKey, IndexCompactionPrefix, MigrationKey, MigrationPrefix, NodeKey,
	NodeLiveQueryKey, NodeLiveQueryPrefix, NsRoot, ReclaimKey, ReclaimPrefix, SessionKey,
	SessionPrefix, StorageVersionKey, SubscriptionKey, VersionHistoryPrefix, VersionKey,
};
use crate::key::{
	AnyRange, KVKey, KVKeyDecode, KVSubspace, KVValue, Key, KeyRange, RawRange, Resumable,
};
use crate::kvs::cache::ds::DatastoreCache;
use crate::kvs::clock::SystemClock;
use crate::kvs::index::{IndexBuilder, build_owner_is_live, build_owner_is_live_locked};
use crate::kvs::paging::{PageCompanion, PagedDelete, PagedOutcome};
use crate::kvs::request::{Dialect, QueryRequest, QuerySource};
use crate::kvs::sequences::Sequences;
use crate::kvs::slowlog::SlowLog;
use crate::kvs::tasklease::{LeaseHandler, TaskLeaseType};
#[cfg(test)]
use crate::kvs::testing::{
	NonRetryableErrorSite, RetryableConflictSite, maybe_inject_non_retryable_error,
	maybe_inject_retryable_conflict,
};
use crate::kvs::{
	CHANGEFEED_GC_PASS_KEY_BUDGET, DatastoreError, Direction, NORMAL_BATCH_SIZE,
	RECLAIM_BATCH_SIZE, RECLAIM_PASS_ENTRY_QUOTA, RECLAIM_PASS_KEY_BUDGET, TransactionFactory,
	is_retryable_transaction_conflict,
};
use crate::lq::LiveQueryRouter;
use crate::observe::ExecutionObserver;
use crate::options::EngineOptions;
use crate::sql::Ast;
#[cfg(feature = "surrealism")]
use crate::surrealism::cache::SurrealismCache;
use crate::syn::parser::{ParserSettings, StatementStream};
use crate::syn::{ParseError, ParserConfig};
use crate::types::{PublicNotification, PublicValue, PublicVariables};
use crate::val::{MAX_VALUE_DEPTH, convert_value_to_public_value};
use crate::{CommunityComposer, syn};

mod builder;
pub(crate) mod config;

pub use builder::Builder;
pub use config::LiveQueryEngine;

const TARGET: &str = "surrealdb::core::kvs::ds";
const NODE_DELETE_TIMEOUT: Duration = Duration::from_secs(60);

/// How long [`Datastore::shutdown`] waits for the maintenance tasks to finish
/// their in-flight pass before giving up on a clean stop.
///
/// A pass is left to finish because the storage engine shutdown that follows
/// refuses every commit, so an interrupted pass fails rather than completes.
/// That cannot be an unbounded wait: an async event runs user-defined
/// SurrealQL, whose duration nothing here bounds, so a single non-terminating
/// event would otherwise hold shutdown open forever. On expiry the remaining
/// handles are dropped and shutdown proceeds; the abandoned pass then has its
/// commits refused, which is the same outcome as a crash at that instant.
const MAINTENANCE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);

/// How long [`Datastore::retry_bootstrap`] waits for storage to become able to
/// serve the version bootstrap before giving up.
///
/// Sized to outlast the cluster formation of a distributed backend, which is
/// the condition it exists to wait out. The server's own
/// `SURREAL_STARTUP_OPERATION_TIMEOUT` is a shorter ceiling by default and is
/// the knob an operator reaches for; this bound only stops an embedder that has
/// no such ceiling from waiting forever.
const BOOTSTRAP_RETRY_BUDGET: Duration = Duration::from_secs(120);

/// How long one bootstrap attempt may run before it is abandoned and retried.
const BOOTSTRAP_RETRY_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(10);

/// The gap before the first bootstrap retry, doubled on each further attempt up
/// to [`BOOTSTRAP_RETRY_MAX_BACKOFF`].
const BOOTSTRAP_RETRY_MIN_BACKOFF: Duration = Duration::from_millis(100);

/// The longest gap between two bootstrap attempts.
const BOOTSTRAP_RETRY_MAX_BACKOFF: Duration = Duration::from_secs(5);

/// How many times the back-off may double, which is as many as it takes to
/// reach [`BOOTSTRAP_RETRY_MAX_BACKOFF`] from
/// [`BOOTSTRAP_RETRY_MIN_BACKOFF`].
const BOOTSTRAP_RETRY_MAX_DOUBLINGS: u32 = 6;

// Capping the exponent is only sound while the cap still reaches the ceiling:
// stop short of it and the back-off would silently settle below its documented
// maximum if either bound were retuned.
const _: () = assert!(
	BOOTSTRAP_RETRY_MIN_BACKOFF.as_millis() << BOOTSTRAP_RETRY_MAX_DOUBLINGS
		>= BOOTSTRAP_RETRY_MAX_BACKOFF.as_millis(),
	"the bootstrap back-off cannot double its way up to its own ceiling"
);

/// How often a bootstrap that is still retrying reports that it is still going.
///
/// The cadence is on the log, not on the retries: attempts run as fast as the
/// back-off allows, and one in every interval is reported.
const BOOTSTRAP_RETRY_LOG_INTERVAL: Duration = Duration::from_secs(5);

/// The role assigned to the initial user created when starting the server with
/// credentials for the first time
const INITIAL_USER_ROLE: &str = "owner";

/// Whether a reclaim pass emptied the prefix it was given.
///
/// `Complete` licenses the caller to retire the queue entry. `Incomplete` means
/// the entry's durable resume cursor has advanced but keys remain, so the entry
/// must stay queued for a later pass to finish — retiring it then would orphan
/// the remainder with nothing left to find it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ReclaimOutcome {
	Complete,
	Incomplete,
	/// The queue entry was deleted by someone else while the reclaim was
	/// running, withdrawing the claim that the prefix is orphaned. Nothing more
	/// may be deleted from it.
	Cancelled,
	/// The task lease passed to another node mid-reclaim. Like `Incomplete` for
	/// this entry, but the pass itself must stop rather than move on to the next
	/// entry: a lease check is throttled to one datastore read per maintenance
	/// period, so the reclaim consumed the read a fresh check here would depend
	/// on and that check would report the lease held without asking.
	LeaseLost,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ShutdownNodeDeleteOutcome {
	Archived,
	Failed,
	TimedOut,
}

async fn await_node_step<T, Fut>(
	deadline: Instant,
	timeout_duration: Duration,
	canceller: Option<&CancellationToken>,
	step: Fut,
) -> Result<T>
where
	Fut: Future<Output = Result<T>>,
{
	if let Some(canceller) = canceller {
		tokio::select! {
			biased;
			_ = canceller.cancelled() => bail!(EngineError::QueryCancelled),
			result = timeout_at(deadline, step) => match result {
				Ok(result) => result,
				Err(_) => bail!(EngineError::QueryTimedout(timeout_duration)),
			},
		}
	} else {
		match timeout_at(deadline, step).await {
			Ok(result) => result,
			Err(_) => bail!(EngineError::QueryTimedout(timeout_duration)),
		}
	}
}

async fn await_node_tx_step<T, Fut>(
	txn: &Transaction,
	deadline: Instant,
	timeout_duration: Duration,
	canceller: Option<&CancellationToken>,
	step: Fut,
) -> Result<T>
where
	Fut: Future<Output = Result<T>>,
{
	let result = if let Some(canceller) = canceller {
		tokio::select! {
			biased;
			_ = canceller.cancelled() => {
				let _ = txn.cancel().await;
				bail!(EngineError::QueryCancelled);
			}
			result = timeout_at(deadline, step) => result,
		}
	} else {
		timeout_at(deadline, step).await
	};

	match result {
		Ok(Ok(value)) => Ok(value),
		Ok(Err(e)) => {
			let _ = txn.cancel().await;
			Err(e)
		}
		Err(_) => {
			let _ = txn.cancel().await;
			bail!(EngineError::QueryTimedout(timeout_duration))
		}
	}
}

fn archive_node_for_shutdown(
	timeout_duration: Duration,
	result: Result<()>,
) -> ShutdownNodeDeleteOutcome {
	match result {
		Ok(()) => ShutdownNodeDeleteOutcome::Archived,
		Err(e) => {
			if matches!(crate::err::engine_error(&e), Some(EngineError::QueryTimedout(_))) {
				warn!(
					target: TARGET,
					timeout = ?timeout_duration,
					"Timed out archiving node during shutdown; continuing shutdown"
				);
				return ShutdownNodeDeleteOutcome::TimedOut;
			}

			warn!(
				target: TARGET,
				error = %e,
				"Failed to archive node during shutdown; continuing shutdown"
			);
			ShutdownNodeDeleteOutcome::Failed
		}
	}
}

/// The underlying datastore instance which stores the dataset.
pub struct Datastore {
	transaction_factory: TransactionFactory,
	/// Cancellation for this datastore's own background work, tripped by
	/// [`Self::shutdown`].
	shutdown: CancellationToken,
	/// Handles for this datastore's maintenance tasks, so [`Self::shutdown`]
	/// can wait for them to stop.
	///
	/// A datastore is not a working database without them — index compaction,
	/// tombstone reclaim, changefeed GC, index-build recovery and the cluster
	/// heartbeat all live there — so the builder starts them rather than
	/// leaving it to the embedder. `None` for a datastore built with
	/// [`Builder::without_maintenance_tasks`](self::builder::Builder::without_maintenance_tasks),
	/// until [`Self::start_maintenance_tasks`] is called on it.
	maintenance: parking_lot::Mutex<Option<crate::kvs::tasks::Tasks>>,
	/// The cadences the maintenance tasks run at, kept so
	/// [`Self::start_maintenance_tasks`] starts them on the same schedule the
	/// builder was given rather than on whatever its caller passes in.
	engine_options: EngineOptions,
	/// Serialises [`Self::shutdown`] across the holders of this datastore.
	///
	/// The sequence has to run start to finish for exactly one caller at a time:
	/// it stops the maintenance tasks *before* closing the storage engine, and a
	/// second caller that skipped straight to the storage shutdown would close
	/// the engine out from under a pass the first caller is still waiting on.
	/// Later callers therefore block here and observe the completed sequence.
	shutdown_lock: tokio::sync::Mutex<()>,
	/// The unique id of this datastore, used in notifications.
	id: Uuid,
	/// Whether this process created the datastore's storage.
	///
	/// Latched by [`Self::check_version`], because the underlying signal is
	/// one-shot: it comes from writing the version key, and a caller that
	/// retries after a later failure would otherwise see the key already there
	/// and be told the datastore is pre-existing.
	created_here: std::sync::atomic::AtomicBool,
	/// Whether authentication is enabled on this datastore.
	auth_enabled: bool,
	/// The maximum duration timeout for running multiple statements in a query.
	dynamic_configuration: DynamicConfiguration,
	/// The slow log configuration determining when a query should be logged
	slow_log: Option<SlowLog>,
	/// The maximum duration timeout for running multiple statements in a
	/// transaction.
	transaction_timeout: Option<Duration>,
	/// The security and feature capabilities for this datastore.
	capabilities: ArcSwap<Capabilities>,
	/// Broker used to deliver live-query notifications after their write commits.
	///
	/// `Some` iff live-query subscribers exist for this datastore (the broker owns the sender
	/// half of the notification channel internally). `None` disables live-query work entirely
	/// at the executor boundary.
	live_query_broker: Option<Arc<dyn MessageBroker>>,
	/// Per-node live-query router state (the tail cursor over the `lqe`
	/// keyspace). Only used when `config.datastore.live_query_engine` is
	/// `Router`, where the router is the sole notification delivery path. See
	/// [`crate::lq`].
	live_query_router: Arc<LiveQueryRouter>,
	/// Public HTTP endpoint this datastore publishes on its `Node` catalog row so other
	/// cluster members can route cross-node messages (e.g. live-query relay) to it.
	/// `None` in deployments that don't expose such an endpoint.
	http_endpoint: Option<String>,
	// The index store cache
	index_stores: IndexStores,
	// The cross transaction cache
	cache: Arc<DatastoreCache>,
	/// Cache of generated GraphQL schemas, shared across every transport that
	/// serves GraphQL: the HTTP `/graphql` route, GraphQL-over-WebSocket
	/// subscriptions, the `graphql` RPC method, and the MCP `graphql` tool.
	/// Keyed by `(ns, db, config, schema-fingerprint)` so DDL changes invalidate
	/// it automatically.
	#[cfg(all(feature = "graphql", not(target_family = "wasm")))]
	graphql_schema_cache: crate::graphql::cache::GraphQLSchemaCache,
	/// Registry of built-in scalar, aggregate, projection and index
	/// functions, along with the method-dispatch table. Built once when the
	/// datastore is constructed and shared across all transactions via the
	/// `Arc`. The executor clones this `Arc` onto the `RootContext` of every
	/// statement rather than rebuilding the registry, which is otherwise the
	/// single biggest per-query cost.
	function_registry: Arc<FunctionRegistry>,
	// The index asynchronous builder
	index_builder: IndexBuilder,
	#[cfg(storage)]
	// The temporary directory
	temporary_directory: Option<Arc<PathBuf>>,
	// Map of bucket connections
	buckets: BucketsManager,
	// The sequences
	sequences: Sequences,
	// The surrealism cache
	#[cfg(feature = "surrealism")]
	surrealism_cache: Arc<SurrealismCache>,
	/// When `true`, surrealism modules are loaded lazily on first use
	/// instead of being eagerly compiled at startup.
	#[cfg(feature = "surrealism")]
	lazy_surrealism: bool,
	/// Post-commit wake-ups shared with every transaction: async event
	/// processing, and index compaction so the compactor runs on the write
	/// instead of waiting out its interval.
	triggers: Arc<CommitTriggers>,
	/// The per-layer configuration every query executed on this datastore
	/// reaches through its context, plus the datastore's own knobs.
	config: Arc<RuntimeConfig>,
	/// The parser depth limits applied to every query text parsed for this
	/// datastore. Shared with the transports, which decode request bodies
	/// against the same limits.
	parser_config: Arc<ParserConfig>,
	// Http client used to make requests.
	#[cfg(feature = "http")]
	http_client: ArcSwap<HttpClient>,
	/// Observer invoked on significant events. Defaults to [`NoopObserver`].
	observer: Arc<dyn ExecutionObserver>,
}

pub(crate) use surrealdb_kvs::{Metrics, TransactionBuilder};

/// Transaction-builder construction result with router startup state.
///
/// The datastore consumes `builder`; server startup threads `router_state` into
/// the router factory so embedders can make immutable handles available to
/// their HTTP routes without process globals.
pub struct TransactionBuilderParts<S> {
	/// Transaction builder consumed by the datastore.
	pub builder: Box<dyn TransactionBuilder>,
	/// Immutable router startup state produced by the composer.
	pub router_state: S,
}

impl<S> TransactionBuilderParts<S> {
	/// Construct transaction-builder parts with router startup state.
	pub fn new(builder: Box<dyn TransactionBuilder>, router_state: S) -> Self {
		Self {
			builder,
			router_state,
		}
	}
}

impl TransactionBuilderParts<()> {
	/// Construct transaction-builder parts for composers without router state.
	pub fn without_router_state(builder: Box<dyn TransactionBuilder>) -> Self {
		Self::new(builder, ())
	}
}

/// Factory that parses a datastore path and returns a concrete `TransactionBuilder`.
///
/// Implementations can decide how to interpret connection strings (e.g. "memory",
/// "rocksdb:...", "tikv:...") and which clock to use. This lets the CLI and
/// server be generic over different storage backends without hard-coding them.
///
/// The `path_valid` helper is used by the CLI to validate the path early and
/// provide better error messages before starting the runtime.
pub trait TransactionBuilderFactory: Send + Sync + 'static {
	/// Immutable state threaded into router construction after datastore startup.
	type RouterState: Clone + Send + Sync + 'static;

	/// Create a new transaction builder for the datastore.
	///
	/// # Parameters
	/// - `path`: Database connection path string
	/// - `canceller`: Token for graceful shutdown and cancellation of long-running operations
	fn new_transaction_builder(
		&self,
		path: &str,
		canceller: CancellationToken,
		config: ConfigMap,
	) -> impl Future<Output = Result<TransactionBuilderParts<Self::RouterState>>> + Send;

	/// Validate a datastore path string.
	fn path_valid(&self, v: &str) -> Result<String>;

	/// Returns the stable datastore node id used for live-query ownership metadata.
	///
	/// Composers that run SurrealDB inside a clustered product should return a deterministic
	/// value so remote writers can route notifications back to the node that owns each
	/// subscriber connection.
	fn datastore_node_id(&self) -> Option<[u8; 16]> {
		None
	}

	/// Creates the broker that receives buffered live-query notifications after commit.
	///
	/// The default broker is local-only and preserves community behaviour. Clustered composers
	/// can return a broker that forwards remote targets without changing transaction results on
	/// delivery failure.
	fn live_query_broker(&self, channel: Sender<PublicNotification>) -> Arc<dyn MessageBroker> {
		crate::dbs::LocalMessageBroker::new(channel)
	}

	/// Public HTTP endpoint this datastore should publish for cross-node messaging.
	///
	/// Clustered composers surface their local node's endpoint here so the [`Datastore`]
	/// can record it on the `Node` catalog row, making it discoverable by peer nodes
	/// (e.g. for the live-query relay). Returns `None` in single-node and shared-backend
	/// deployments that don't expose a cross-node messaging endpoint.
	fn http_endpoint(&self) -> Option<String> {
		None
	}
}

impl TransactionBuilderFactory for CommunityComposer {
	type RouterState = ();

	async fn new_transaction_builder(
		&self,
		path: &str,
		canceller: CancellationToken,
		config: ConfigMap,
	) -> Result<TransactionBuilderParts<Self::RouterState>> {
		let builder = surrealdb_kvs_any::Backends::community()
			.new_transaction_builder(path, canceller, config)
			.await?;
		Ok(TransactionBuilderParts::without_router_state(builder))
	}

	fn path_valid(&self, v: &str) -> Result<String> {
		Ok(surrealdb_kvs_any::Backends::community().path_valid(v)?)
	}
}

impl Display for Datastore {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(self.transaction_factory.backend_name())
	}
}

/// One reclaim queue entry in the running for this pass's key budget.
///
/// Ordered by how long the entry has been waiting — oldest observation first,
/// and the queue's key order between entries observed in the same millisecond so
/// selection is deterministic. Held in a max-heap capped at
/// [`RECLAIM_PASS_ENTRY_QUOTA`], where "greatest" is the newest and so the first
/// to lose its place.
struct ReclaimCandidate {
	/// When the reclaim task first observed the entry. Zero only where the grace
	/// is disabled, in which case every candidate ties and key order decides.
	observed_ms: u64,
	/// The queue key, as the scan returned it.
	key: Vec<u8>,
	/// The state read during the walk, carrying the resume cursor the delete
	/// continues from.
	state: ReclaimState,
}

impl Ord for ReclaimCandidate {
	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
		self.observed_ms.cmp(&other.observed_ms).then_with(|| self.key.cmp(&other.key))
	}
}

impl PartialOrd for ReclaimCandidate {
	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl PartialEq for ReclaimCandidate {
	fn eq(&self, other: &Self) -> bool {
		self.cmp(other) == std::cmp::Ordering::Equal
	}
}

impl Eq for ReclaimCandidate {}

impl Datastore {
	pub fn builder() -> Builder {
		Builder::new()
	}

	async fn retry_index_operation_conflict(
		err: &anyhow::Error,
		operation: impl Into<String>,
	) -> bool {
		if is_retryable_transaction_conflict(err) {
			let operation = operation.into();
			debug!(
				target: TARGET,
				operation = %operation,
				error = %err,
				"retryable index operation conflict, retrying"
			);
			sleep(Duration::from_millis(100)).await;
			true
		} else {
			false
		}
	}

	async fn cancel_and_retry_index_operation_conflict(
		txn: &Transaction,
		err: &anyhow::Error,
		operation: impl Into<String>,
	) -> bool {
		let _ = txn.cancel().await;
		Self::retry_index_operation_conflict(err, operation).await
	}

	/// Creates a new datastore instance
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use surrealdb_core::kvs::Datastore;
	/// # use anyhow::Error;
	/// # #[tokio::main]
	/// # async fn main() -> Result<(),Error> {
	/// let ds = Datastore::new("memory").await?;
	/// # Ok(())
	/// # }
	/// ```
	///
	/// Or to create a file-backed store:
	///
	/// ```rust,no_run
	/// # use surrealdb_core::kvs::Datastore;
	/// # use anyhow::Error;
	/// # #[tokio::main]
	/// # async fn main() -> Result<(),Error> {
	/// let ds = Datastore::new("surrealkv://temp.skv").await?;
	/// # Ok(())
	/// # }
	/// ```
	///
	/// Or to connect to a tikv-backed distributed store:
	///
	/// ```rust,no_run
	/// # use surrealdb_core::kvs::Datastore;
	/// # use anyhow::Error;
	/// # #[tokio::main]
	/// # async fn main() -> Result<(),Error> {
	/// let ds = Datastore::new("tikv://127.0.0.1:2379").await?;
	/// # Ok(())
	/// # }
	/// ```
	/// The datastore is returned shared, because it starts background
	/// maintenance tasks that hold a [`Weak`](std::sync::Weak) reference to it.
	/// Because those tasks write, this also settles the datastore's storage
	/// version before any of them starts, so the datastore is handed back
	/// already stamped; [`Self::check_version`] is still what checks that this
	/// build can read what was found, and what runs any migrations owed.
	///
	/// Use [`Builder::without_maintenance_tasks`] for a quiescent datastore, or
	/// for one whose tasks start later under the caller's own ordering.
	pub async fn new(path: &str) -> Result<Arc<Self>> {
		Builder::new().build_with_path(path).await
	}

	/// Registers metrics for the current datastore flavor if supported.
	///
	/// This will return a list of available metrics and their descriptions.
	pub fn register_metrics(&self) -> Option<Metrics> {
		self.transaction_factory.register_metrics()
	}

	/// Collects a specific u64 metric by name if supported by the datastore flavor.
	///
	/// - `metric`: The name of the metric to collect.
	pub fn collect_u64_metric(&self, metric: &str) -> Option<u64> {
		self.transaction_factory.collect_u64_metric(metric)
	}

	/// The currently installed observer. Cheap to clone; internal handle is
	/// an `Arc`.
	///
	/// Exposed so higher layers (server, SDK) can emit transport-layer events
	/// such as session connect/disconnect that the core engine never sees.
	pub fn observer(&self) -> &Arc<dyn ExecutionObserver> {
		&self.observer
	}

	/// Create a new datastore with the same persistent data (inner), with
	/// flushed cache. Simulating a server restart
	///
	/// The restarted datastore carries **no** maintenance tasks: it is returned
	/// unshared, so there is nothing for a task to hold a `Weak` to. Callers
	/// that need them call [`Self::start_maintenance_tasks`] once they have
	/// shared it.
	pub fn restart(self) -> Self {
		self.buckets.clear();
		Self {
			shutdown: CancellationToken::new(),
			maintenance: parking_lot::Mutex::new(None),
			engine_options: self.engine_options,
			shutdown_lock: tokio::sync::Mutex::new(()),
			id: self.id,
			auth_enabled: self.auth_enabled,
			dynamic_configuration: DynamicConfiguration::default(),
			slow_log: self.slow_log,
			transaction_timeout: self.transaction_timeout,
			capabilities: ArcSwap::new(self.capabilities.load_full()),
			live_query_broker: self.live_query_broker,
			// Fresh router cursor: a restarted node re-establishes its baseline.
			live_query_router: Arc::new(LiveQueryRouter::new()),
			http_endpoint: self.http_endpoint,
			index_stores: IndexStores::new(
				self.config.idx.hnsw_cache_size,
				self.config.idx.diskann_cache_size,
				self.config.idx.graph_resolve_cache_size,
				self.config.idx.segment_dictionary_path.clone(),
			),
			index_builder: IndexBuilder::new(self.transaction_factory.clone()),
			#[cfg(storage)]
			temporary_directory: self.temporary_directory,
			cache: Arc::new(DatastoreCache::new(self.config.datastore.datastore_cache_size)),
			#[cfg(all(feature = "graphql", not(target_family = "wasm")))]
			graphql_schema_cache: crate::graphql::cache::GraphQLSchemaCache::default(),
			function_registry: Arc::new(FunctionRegistry::with_builtins()),
			buckets: self.buckets,
			sequences: Sequences::new(self.transaction_factory.clone(), self.id),
			transaction_factory: self.transaction_factory,
			created_here: std::sync::atomic::AtomicBool::new(false),
			triggers: self.triggers,
			#[cfg(feature = "surrealism")]
			surrealism_cache: Arc::new(SurrealismCache::new(
				self.config.surrealism.surrealism_cache_size,
			)),
			#[cfg(feature = "surrealism")]
			lazy_surrealism: self.lazy_surrealism,
			#[cfg(feature = "http")]
			http_client: self.http_client,
			observer: self.observer,
			config: self.config,
			parser_config: self.parser_config,
		}
	}

	/// Create a test-only datastore facade that shares the same durable KV engine
	/// while resetting process-local state.
	///
	/// This lets unit tests model two SurrealDB compute nodes connected to the
	/// same storage backend without starting an external service. The cloned
	/// facade deliberately reuses the transaction factory, but gets its own node
	/// id, index builder, index stores, datastore cache, sequences, and other
	/// process-local caches. Tests that exercise cluster liveness should call
	/// [`Self::insert_node`] for both the original datastore and the fork.
	#[cfg(test)]
	#[cfg_attr(not(feature = "kv-mem"), allow(dead_code))]
	pub(crate) fn fork_for_test_with_node_id(&self, id: Uuid) -> Self {
		let transaction_factory = self.transaction_factory.clone();
		Self {
			// A fork is unshared, so it carries no maintenance tasks.
			shutdown: CancellationToken::new(),
			maintenance: parking_lot::Mutex::new(None),
			engine_options: self.engine_options,
			shutdown_lock: tokio::sync::Mutex::new(()),
			id,
			auth_enabled: self.auth_enabled,
			dynamic_configuration: self.dynamic_configuration.clone(),
			slow_log: self.slow_log.clone(),
			transaction_timeout: self.transaction_timeout,
			capabilities: ArcSwap::new(self.capabilities.load_full()),
			live_query_broker: self.live_query_broker.clone(),
			// A fork models a separate node, so it gets its own router cursor.
			live_query_router: Arc::new(LiveQueryRouter::new()),
			http_endpoint: self.http_endpoint.clone(),
			index_stores: IndexStores::new(
				self.config.idx.hnsw_cache_size,
				self.config.idx.diskann_cache_size,
				self.config.idx.graph_resolve_cache_size,
				self.config.idx.segment_dictionary_path.clone(),
			),
			index_builder: IndexBuilder::new(transaction_factory.clone()),
			#[cfg(storage)]
			temporary_directory: self.temporary_directory.clone(),
			cache: Arc::new(DatastoreCache::new(self.config.datastore.datastore_cache_size)),
			#[cfg(all(feature = "graphql", not(target_family = "wasm")))]
			graphql_schema_cache: crate::graphql::cache::GraphQLSchemaCache::default(),
			function_registry: Arc::new(FunctionRegistry::with_builtins()),
			buckets: self.buckets.clone(),
			sequences: Sequences::new(transaction_factory.clone(), id),
			transaction_factory,
			created_here: std::sync::atomic::AtomicBool::new(false),
			triggers: Arc::clone(&self.triggers),
			#[cfg(feature = "surrealism")]
			surrealism_cache: Arc::new(SurrealismCache::new(
				self.config.surrealism.surrealism_cache_size,
			)),
			#[cfg(feature = "surrealism")]
			lazy_surrealism: self.lazy_surrealism,
			#[cfg(feature = "http")]
			http_client: ArcSwap::new(self.http_client.load_full()),
			observer: Arc::clone(&self.observer),
			config: Arc::clone(&self.config),
			parser_config: Arc::clone(&self.parser_config),
		}
	}

	/// Set the node id for this datastore.
	pub fn with_node_id(mut self, id: Uuid) -> Self {
		self.id = id;
		self
	}

	/// Set a global transaction timeout for this Datastore
	pub fn with_transaction_timeout(mut self, duration: Option<Duration>) -> Self {
		self.transaction_timeout = duration;
		self
	}

	/// Get the configured transaction timeout, if any
	pub(crate) fn transaction_timeout(&self) -> Option<Duration> {
		self.transaction_timeout
	}

	/// The configured write-cardinality limit for statement transactions
	/// (`transaction_max_write_keys`), or `None` when the guard is disabled.
	pub(crate) fn transaction_max_write_keys(&self) -> Option<std::num::NonZeroU64> {
		std::num::NonZeroU64::new(self.transaction_factory.max_write_keys())
	}

	/// Get the configured global query timeout, if any.
	///
	/// This is the deadline set by `--query-timeout` /
	/// `SURREAL_QUERY_TIMEOUT`. Beyond being applied as an executor deadline
	/// in [`Self::setup_ctx`], the transports reuse this value as a
	/// wall-clock guard so a non-yielding hang (or engine work not bounded by
	/// the deadline) still terminates the request. A return value of `None`
	/// means no timeout is enforced.
	pub fn query_timeout(&self) -> Option<Duration> {
		self.dynamic_configuration.get_query_timeout()
	}

	/// Returns the broker used to flush live-query notifications after commit.
	pub(crate) fn live_query_broker(&self) -> Option<Arc<dyn MessageBroker>> {
		self.live_query_broker.clone()
	}

	/// Looks up the public HTTP endpoint that the cluster member with `node_id`
	/// has published on its `Node` catalog row.
	///
	/// Returns `Ok(None)` when the row exists but no endpoint is set, or when
	/// no such node has registered. Used by clustered live-query relays to
	/// resolve the target node's address at delivery time without consulting
	/// any in-memory cluster topology.
	pub async fn lookup_node_endpoint(&self, node_id: Uuid) -> Result<Option<String>> {
		let txn = self.transaction(Read).await?;
		let key = NodeKey {
			nd: node_id,
		};
		let res = txn.get_key(&key, None).await?;
		// Always cancel a read transaction; we don't write through it.
		let _ = txn.cancel().await;
		Ok(res.and_then(|node: Node| node.http_endpoint))
	}

	#[cfg(storage)]
	/// Set a temporary directory for ordering of large result sets
	pub fn with_temporary_directory(mut self, path: Option<PathBuf>) -> Self {
		self.temporary_directory = path.map(Arc::new);
		self
	}

	/// Configure whether surrealism modules are loaded lazily on first use
	/// rather than eagerly at startup.
	#[cfg(feature = "surrealism")]
	pub fn with_lazy_surrealism(mut self, lazy: bool) -> Self {
		self.lazy_surrealism = lazy;
		self
	}

	/// Returns `true` if surrealism modules are loaded lazily.
	#[cfg(feature = "surrealism")]
	pub fn is_lazy_surrealism(&self) -> bool {
		self.lazy_surrealism
	}

	pub fn index_store(&self) -> &IndexStores {
		&self.index_stores
	}

	/// Is authentication enabled for this Datastore?
	pub fn is_auth_enabled(&self) -> bool {
		self.auth_enabled
	}

	pub fn id(&self) -> Uuid {
		self.id
	}

	/// Does the datastore allow excecuting an RPC method?
	///
	/// Dispatch enforces this itself, so a transport does not have to. It is
	/// public so a transport can also *report* the answer ahead of time: the
	/// gRPC service advertises the methods an operator has denied, so a client
	/// can avoid calls it already knows will be refused.
	pub fn allows_rpc_method(&self, method_target: &MethodTarget) -> bool {
		self.capabilities.load().allows_rpc_method(method_target)
	}

	/// Does the datastore allow requesting an HTTP route?
	/// This function needs to be public to allow access from the CLI crate.
	pub fn allows_http_route(&self, route_target: &RouteTarget) -> bool {
		self.capabilities.load().allows_http_route(route_target)
	}

	/// Is the user allowed to query?
	pub fn allows_query_by_subject(&self, subject: impl Into<ArbitraryQueryTarget>) -> bool {
		self.capabilities.load().allows_query(&subject.into())
	}

	/// Is the user allowed to invoke the `eval::*` functions?
	pub fn allows_eval_query_by_subject(&self, subject: impl Into<EvalQueryTarget>) -> bool {
		self.capabilities.load().allows_eval_query(&subject.into())
	}

	/// Does the datastore allow connections to a network target?
	#[cfg(feature = "jwks")]
	pub(crate) fn allows_network_target(&self, net_target: &NetTarget) -> bool {
		self.capabilities.load().allows_network_target(net_target)
	}

	/// The datastore's current capabilities snapshot.
	pub fn get_capabilities(&self) -> Arc<Capabilities> {
		self.capabilities.load_full()
	}

	/// Replace the datastore's capabilities at runtime.
	///
	/// The swap is atomic and lock-free. In-flight queries keep the snapshot
	/// they captured when they started (the executor clones the `Arc` once at
	/// query start), so only queries begun after this call observe the new
	/// capabilities. This cannot exceed what the binary was compiled to
	/// support — a capability whose machinery is not compiled in stays inert
	/// regardless of what is set here.
	///
	/// When the `http` feature is enabled this also rebuilds the outbound HTTP
	/// client so its redirect and DNS net filter track the new `allow_net` /
	/// `deny_net`. Without that, a runtime net *tightening* would be enforced on
	/// a request's initial URL (checked against the live snapshot) but not on
	/// redirect hops, whose filter is baked in at client construction. Building
	/// the client can fail, hence the `Result`; on failure the capabilities are
	/// left unchanged.
	pub fn set_capabilities(&self, capabilities: Capabilities) -> anyhow::Result<()> {
		#[cfg(feature = "http")]
		let http_client = HttpClient::new(
			capabilities.allow_net.clone(),
			capabilities.deny_net.clone(),
			&self.config.http,
		)?;
		self.capabilities.store(Arc::new(capabilities));
		#[cfg(feature = "http")]
		self.http_client.store(Arc::new(http_client));
		Ok(())
	}

	#[cfg(feature = "jwks")]
	pub(crate) fn cache(&self) -> &Arc<DatastoreCache> {
		&self.cache
	}

	/// The function registry every query on this datastore resolves names
	/// through. Handed to the executor, which seats it on the `RootContext`
	/// of each statement.
	pub(crate) fn function_registry(&self) -> &Arc<FunctionRegistry> {
		&self.function_registry
	}

	pub(super) fn clock_now(&self) -> Timestamp {
		SystemClock::new().now()
	}

	/// Verifies the datastore's storage version and applies any data migrations
	/// it owes, returning that version and whether this process created the
	/// datastore.
	///
	/// **Call this before serving any query against a datastore that may
	/// predate this build.** A datastore is not fully readable until its
	/// migrations have run: [`Datastore::new`] and the builder do not call this,
	/// so an embedder that skips it against pre-3.3 storage sees sequences that
	/// appear not to exist — which `DEFINE SEQUENCE ... IF NOT EXISTS` will then
	/// recreate, resetting an allocator that has already issued values.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn check_version(&self) -> Result<(MajorVersion, bool)> {
		let (version, is_new) = self.settle_storage_version().await?;
		// Check we are running the latest version
		if !version.is_latest() {
			bail!(DatastoreError::OutdatedStorageVersion {
				expected: MajorVersion::latest().into(),
				actual: version.into(),
			});
		}
		// `get_version` reports a datastore as new only on the start that wrote
		// `!v`. Everything below can fail transiently and be retried by the
		// caller, and that retry finds the key present — so the flag is latched on
		// the datastore rather than re-derived, or a caller keying default
		// namespace creation off it would silently skip that on the second pass.
		let is_new =
			self.created_here.fetch_or(is_new, std::sync::atomic::Ordering::SeqCst) || is_new;
		// Bring the datastore's semantic version stamp up to this build, applying
		// any data migrations the gap between the two calls for. Not wrapped in
		// `retry`, which caps each attempt at ten seconds: a migration may run for
		// much longer, and the driver handles contention itself through a task
		// lease.
		migration::run(self, is_new).await?;
		// Everything ok
		Ok((version, is_new))
	}

	/// Settles the datastore's major storage version, stamping it if it carries
	/// none, and reports whether this call was the one that stamped it.
	///
	/// The marker half of [`Self::check_version`], separated because the builder
	/// owes it before it starts any writer but must not do the rest: the
	/// migrations that follow the gate run under a lease with no bound on how
	/// long they take, which is not something a constructor may hold a caller
	/// for.
	///
	/// Retries because the storage layer may not be able to serve a transaction
	/// yet, and because concurrent instances conflict over the version key.
	/// Callers that want the gate — the check that this build can read what it
	/// found — want [`Self::check_version`].
	pub(crate) async fn settle_storage_version(&self) -> Result<(MajorVersion, bool)> {
		Self::retry_bootstrap("Check version", || self.get_version()).await
	}

	/// The full semantic version the datastore has been advanced to.
	///
	/// `None` for a datastore last written before 3.3, the release that
	/// introduced the stamp. Its major version is still available from
	/// [`Self::get_version`].
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn storage_version(&self) -> Result<Option<StorageVersion>> {
		let txn = self.transaction(Read).await?;
		let version = catch!(txn, txn.get_key(&StorageVersionKey {}, None).await);
		txn.cancel().await?;
		Ok(version)
	}

	/// Every version this datastore has been advanced to, oldest first.
	///
	/// One entry per version transition, not per startup: a node that starts
	/// against a datastore already stamped at its own version adds nothing.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn version_history(&self) -> Result<Vec<VersionHistoryEntry>> {
		let txn = self.transaction(Read).await?;
		let range = catch!(txn, VersionHistoryPrefix {}.range());
		let entries = catch!(txn, txn.getr(range, None).await);
		txn.cancel().await?;
		Ok(entries.into_iter().map(|(_, entry)| entry).collect())
	}

	/// Every data migration applied to this datastore, in the order they were
	/// declared.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	/// Paired with the ledger id the entry was filed under, which is a
	/// migration's identity; the name in the record is documentation and may be
	/// reworded between releases.
	pub async fn applied_migrations(&self) -> Result<Vec<(u32, MigrationRecord)>> {
		Ok(self
			.applied_migration_ids()
			.await?
			.into_iter()
			.filter_map(|(id, record)| record.map(|r| (id, r)))
			.collect())
	}

	/// Every applied migration's ledger id, with its record when that record is
	/// readable by this build.
	///
	/// A record written in a revision this build does not know decodes to
	/// `None` rather than failing the call. The id comes from the key, and the
	/// key's presence is what marks a migration as applied — so a record this
	/// build cannot read must still be reportable, since that is exactly the
	/// state a downgrade needs to be told about.
	pub async fn applied_migration_ids(&self) -> Result<Vec<(u32, Option<MigrationRecord>)>> {
		let txn = self.transaction(Read).await?;
		let range = catch!(txn, MigrationPrefix {}.range());
		let rows = catch!(txn, txn.getr_raw(range, None).await);
		txn.cancel().await?;
		rows.into_iter()
			.map(|(key, value)| {
				let id = MigrationKey::decode_key(&key)?.id;
				Ok((id, MigrationRecord::kv_decode_value(&value, ()).ok()))
			})
			.collect()
	}

	/// Reads the datastore's major storage version, stamping it on a datastore
	/// that carries none, and reports whether this call was the one that
	/// stamped it.
	///
	/// # What `!v`'s absence means
	///
	/// `!v` was introduced in 2.0, so a datastore that holds data but no `!v`
	/// was either written by a build that predates it — a genuine v1 store,
	/// which must be refused as out of date — or created by a later build whose
	/// bootstrap was interrupted after something else wrote but before `!v`
	/// landed. Nothing in the bytes tells those apart, so the second case
	/// records itself: [`BootstrapKey`] is committed before `!v` and removed in
	/// the same transaction that writes it, and its presence is what licenses
	/// this call to complete the interrupted bootstrap instead of refusing it.
	/// Without it, `MajorVersion::v1()` is the only safe reading, and an
	/// interrupted bootstrap would be stamped v1 permanently.
	///
	/// # Ordering
	///
	/// The sentinel is only a fallback: nothing may write to a datastore before
	/// its version is settled. That ordering is structural — the builder settles
	/// the version before it starts any maintenance task, and a caller that
	/// starts them itself does so after this has run (see
	/// [`Datastore::start_maintenance_tasks`]). The sentinel is what keeps a
	/// writer that escapes it anyway — a future job, a storage engine with keys
	/// of its own — from turning a fresh datastore into an unstartable one.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn get_version(&self) -> Result<(MajorVersion, bool)> {
		#[cfg(test)]
		maybe_inject_non_retryable_error(NonRetryableErrorSite::VersionBootstrapBegin, self.id)?;
		// Start a new writeable transaction
		let txn = self.transaction(Write).await?.enclose();
		// Create the key where the version is stored
		let key = VersionKey {};
		// Check if a version is already set in storage
		if let Some(val) = catch!(txn, txn.get_key(&key, None).await) {
			// We didn't write anything, so just rollback
			catch!(txn, txn.cancel().await);
			// Return the current version
			return Ok((val, false));
		}
		// No version is set. Either nothing has ever stamped this datastore, or
		// a previous start began stamping it and did not finish.
		if let Some(target) = catch!(txn, txn.get_key(&BootstrapKey {}, None).await) {
			// An interrupted bootstrap left the sentinel behind, so whatever is
			// in storage was written by a versioned build and no pre-versioning
			// layout can be present: the sentinel is only ever written after the
			// probe below has found the datastore empty, and from that moment
			// the only writers are versioned builds, none of which can serve a
			// query until this call has passed. That is what licenses completing
			// the job rather than refusing it — but not at just any version.
			//
			// The two directions are not symmetric. Finishing a bootstrap an
			// *older* build began is sound at this build's own version: the
			// residue such a build can leave is cluster state a newer build
			// reads, and no user data can exist to owe a migration, because
			// serving a query requires the stamp this call has not yet written.
			// Finishing one a *newer* build began is not: stamping the datastore
			// down a major version would pass this build's own gate against
			// bytes it may not understand, and would leave the build that
			// started the job reading back a stamp it refuses. So that case is
			// declined without writing, which keeps the sentinel intact for the
			// build that can finish it, and returns the target so the gate above
			// reports what is actually on disk.
			if u16::from(target) > MajorVersion::LATEST {
				catch!(txn, txn.cancel().await);
				warn!(
					target: TARGET,
					target = u16::from(target),
					running = MajorVersion::LATEST,
					"This datastore's initialisation was begun by a newer version of SurrealDB \
					and can only be completed by it. Run that version, or use a clean storage \
					directory if this is intended to be a new instance."
				);
				return Ok((target, false));
			}
			let version = MajorVersion::latest();
			warn!(
				target: TARGET,
				target = u16::from(target),
				version = u16::from(version),
				"Completing a datastore initialisation that a previous start left unfinished."
			);
			catch!(txn, txn.replace_key(&key, &version).await);
			catch!(txn, txn.del_key(&BootstrapKey {}).await);
			catch!(txn, txn.commit().await);
			return Ok((version, true));
		}
		// Fetch any key at all, other than the version keys themselves. This has
		// to span the whole byte space rather than the declared root: the point
		// of the probe is data this release does not describe, which by
		// definition need not sit under `/`. Finding any such key means the
		// store predates versioning and must not be stamped as current.
		let range = RawRange::every_key_after(&VersionKey {}.encode_key()?);
		let keys = catch!(txn, txn.keys_raw(range, 1, 0, None).await);
		if !keys.is_empty() {
			// There were keys in storage, so this is an upgrade.
			// Log the first key found for diagnostic purposes.
			warn!(
				target: TARGET,
				first_key = ?keys.first().map(|k| format!("{:?}", k)),
				"No version key found but existing data detected in storage. \
				This storage contains data from a previous SurrealDB version. \
				The server will not start until the data is migrated or removed."
			);
			let version = MajorVersion::v1();
			catch!(txn, txn.replace_key(&key, &version).await);
			catch!(txn, txn.commit().await);
			return Ok((version, true));
		}
		// The datastore is empty, so this start is creating it. Claim it with the
		// sentinel in a transaction of its own: the two writes cannot share one,
		// because the whole point is for the sentinel to outlive a failure of the
		// stamp below. The sentinel sorts before `!v` and so below the probe
		// above, which is what keeps a datastore holding nothing else reading as
		// empty rather than as data of unknown provenance.
		let version = MajorVersion::latest();
		catch!(txn, txn.set_key(&BootstrapKey {}, &version).await);
		catch!(txn, txn.commit().await);
		// Stamp the version and retire the sentinel. Should this fail, the next
		// attempt takes the resume branch above and finishes the job.
		#[cfg(test)]
		maybe_inject_non_retryable_error(NonRetryableErrorSite::VersionBootstrapStamp, self.id)?;
		self.finish_bootstrap(version).await
	}

	/// Stamps `!v` and retires the sentinel, completing a bootstrap this node
	/// claimed.
	///
	/// Re-reads `!v` rather than writing over it blindly, for two reasons that
	/// both come from this being a second transaction. Another node may have
	/// claimed the same empty datastore, seen this node's sentinel and finished
	/// the job in between, in which case this node did not create the datastore
	/// and must not report that it did — two nodes both returning `is_new` have
	/// both of them creating the default namespace, and the loser fails startup
	/// on a namespace that already exists. And reading the key in the same
	/// transaction that writes it is what arms a write conflict on backends that
	/// detect one, which a blind replace would not.
	pub(crate) async fn finish_bootstrap(
		&self,
		version: MajorVersion,
	) -> Result<(MajorVersion, bool)> {
		let key = VersionKey {};
		let txn = self.transaction(Write).await?.enclose();
		if let Some(existing) = catch!(txn, txn.get_key(&key, None).await) {
			catch!(txn, txn.cancel().await);
			return Ok((existing, false));
		}
		catch!(txn, txn.replace_key(&key, &version).await);
		catch!(txn, txn.del_key(&BootstrapKey {}).await);
		catch!(txn, txn.commit().await);
		Ok((version, true))
	}

	// --------------------------------------------------
	// Initialisation functions
	// --------------------------------------------------

	/// Setup the initial cluster access credentials
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn initialise_credentials(&self, user: &str, pass: &str) -> Result<()> {
		// Retry because concurrent instances may conflict when creating the root user
		Self::retry("Initialise credentials", || self.initialise_credentials_attempt(user, pass))
			.await
	}

	/// Single attempt to create the root user if none exists.
	/// Separated from `initialise_credentials` so it can be wrapped in the retry loop.
	async fn initialise_credentials_attempt(&self, user: &str, pass: &str) -> Result<()> {
		// Start a new writeable transaction
		let txn = self.transaction(Write).await?.enclose();
		// Fetch the root users from the storage
		let users = catch!(txn, txn.all_root_users(None).await);
		// Process credentials, depending on existing users
		if users.is_empty() {
			// Display information in the logs
			info!(target: TARGET, "Credentials were provided, and no root users were found. The root user '{user}' will be created");
			// Create and new root user definition
			let stm = define_user_statement_new_with_password(
				Base::Root,
				user.to_owned(),
				pass,
				INITIAL_USER_ROLE.to_owned(),
			);
			let opt = Options::new(&ExecConfig::default())
				.with_auth(Arc::new(Auth::for_root(Role::Owner)));
			let mut ctx = self.setup_ctx()?;
			ctx.set_transaction(Arc::clone(&txn));
			let ctx = ctx.freeze();
			let mut stack = TreeStack::new();
			let res = stack
				.enter(|stk| {
					crate::legacy::define_user_statement_compute(&stm, stk, &ctx, &opt, None)
				})
				.finish()
				.await;
			catch!(txn, res);
			// We added a user, so commit the transaction
			txn.commit().await
		} else {
			// Display information in the logs
			warn!(target: TARGET, "Credentials were provided, but existing root users were found. The root user '{user}' will not be created");
			warn!(target: TARGET, "Consider removing the --user and --pass arguments from the server start command");
			// We didn't write anything, so just rollback
			txn.cancel().await
		}
	}

	/// Setup the default namespace and database
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn initialise_defaults(&self, namespace: &str, database: &str) -> Result<()> {
		info!(target: TARGET, "This is a new SurrealDB instance. Initialising default namespace '{namespace}' and database '{database}'");
		// Create the SQL statement
		let sql = r"
			DEFINE NAMESPACE $namespace COMMENT 'Default namespace generated by SurrealDB';
		USE NS $namespace;
		DEFINE DATABASE $database COMMENT 'Default database generated by SurrealDB';
		DEFINE CONFIG DEFAULT NAMESPACE $namespace DATABASE $database;
		"
		.to_string();

		// Create the variables
		let vars = map! {
			"namespace".to_string() => namespace.to_string().into_value(),
			"database".to_string() => database.to_string().into_value(),
		};

		// Execute the SQL statement
		self.execute(
			&sql,
			&Session::owner(),
			Some(vars.into_iter().collect::<std::collections::BTreeMap<_, _>>().into()),
		)
		.await?;
		// Everything ok
		Ok(())
	}

	/// Performs a database import from SQL, for a startup script.
	///
	/// Delegates to [`Self::import`] rather than repeating it, so that a dump
	/// restored by `--import-file` is parsed under the same profile as one
	/// restored by `surreal import`. Parsed under the datastore's configured
	/// query limits instead, this entry point would refuse depths that an
	/// export is required to be able to write back.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn startup(&self, sql: &str, sess: &Session) -> Result<Vec<QueryResult>> {
		// Output function invocation details to logs
		trace!(target: TARGET, "Running datastore startup import script");
		// Execute the SQL import
		self.import(sql, sess).await
	}

	/// Starts this datastore's maintenance tasks, if they are not already
	/// running.
	///
	/// The builder starts them itself, and settles the storage version first, so
	/// this exists for a caller that built with
	/// [`Builder::without_maintenance_tasks`] in order to own that ordering.
	/// Such a caller owes the same sequence, because these tasks write: the
	/// node-membership refresh blindly upserts this node's row, and every leased
	/// job writes its lease. A write that lands before `!v` does makes a
	/// datastore this process created indistinguishable from one written before
	/// `!v` existed, which [`Datastore::get_version`] is obliged to refuse as
	/// out of date. Call this only once [`Datastore::check_version`] has
	/// returned.
	///
	/// Idempotent: a datastore that already carries its tasks is left alone.
	pub fn start_maintenance_tasks(self: &Arc<Self>) {
		let mut maintenance = self.maintenance.lock();
		if maintenance.is_some() {
			return;
		}
		*maintenance =
			Some(crate::kvs::tasks::init(self, self.shutdown.clone(), &self.engine_options));
	}

	/// Whether this datastore's maintenance tasks are running.
	///
	/// A datastore that never starts them is a database with no index
	/// compaction, no tombstone reclaim, no changefeed GC, no index-build
	/// recovery and no cluster heartbeat — none of which announces itself, so a
	/// caller that defers the start with
	/// [`Builder::without_maintenance_tasks`](self::builder::Builder::without_maintenance_tasks)
	/// has this to assert against.
	pub fn maintenance_tasks_running(&self) -> bool {
		self.maintenance.lock().is_some()
	}

	/// Run the datastore shutdown tasks, performing any necessary cleanup
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn shutdown(&self) -> Result<()> {
		// Output function invocation details to logs
		trace!(target: TARGET, "Running datastore shutdown operations");
		// One caller runs the whole sequence at a time. The steps below are
		// ordered — tasks stopped before the storage engine closes — and a
		// concurrent caller that found the handles already taken would otherwise
		// skip the wait and close the engine while the first caller's pass was
		// still using it. Later callers block here and return once the sequence
		// they were waiting on has finished.
		let _shutting_down = self.shutdown_lock.lock().await;
		// Stop this datastore's maintenance tasks first. They open transactions
		// of their own, and the storage engine shutdown below refuses every
		// commit once it has run, so a pass still in flight would fail rather
		// than finish. Cancelling is idempotent, so a caller that already
		// cancelled its own token — as the server and the embedded engine do —
		// loses nothing by reaching here.
		self.shutdown.cancel();
		// Taken rather than borrowed: the guard must not be held across the
		// await, and the handles are consumed by resolving them.
		let tasks = self.maintenance.lock().take();
		if let Some(tasks) = tasks {
			// Bounded: a pass runs user-defined SurrealQL in the async event
			// case, so waiting for one to finish cannot be waiting forever.
			if timeout(MAINTENANCE_SHUTDOWN_TIMEOUT, tasks.resolve()).await.is_err() {
				warn!(
					target: TARGET,
					"Maintenance tasks did not stop within {MAINTENANCE_SHUTDOWN_TIMEOUT:?}; \
					 continuing shutdown without them"
				);
			}
		}
		// Local index builder tasks are deliberately left running: the storage
		// engine shutdown below stops the commit coordinator first, after which
		// every commit is refused before it applies (see the engine
		// `Transaction::commit` gate). An in-flight build therefore makes no
		// durable change during shutdown and stays at its last committed
		// checkpoint, so the periodic resume scan continues it after restart —
		// exactly as it would after a crash.
		// Archive this datastore in the cluster, but don't let a blocked
		// metadata transaction prevent storage engine shutdown.
		let _ = archive_node_for_shutdown(
			NODE_DELETE_TIMEOUT,
			self.delete_node_with_timeout(NODE_DELETE_TIMEOUT).await,
		);
		// Run any storage engine shutdown tasks
		self.transaction_factory.shutdown().await
	}

	/// Waits until the storage backend is able to serve transactions.
	///
	/// Startup awaits this before opening its first transaction. A backend that
	/// can serve as soon as it is built returns immediately; one that has to
	/// join a cluster and catch up first blocks here for as long as that takes,
	/// which keeps a legitimately slow join from being charged against a
	/// caller's retry budget. `Err` means the backend will never serve.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn wait_until_serve_ready(&self) -> Result<()> {
		self.transaction_factory.wait_until_serve_ready().await
	}

	/// Drop every version of every key in the half-open range `[start, end)`
	/// **outside** any user transaction.
	///
	/// Resolves the backend's [`DestroyRange`] capability through the
	/// [`TransactionBuilder::extension`] hook and delegates to it. A backend
	/// that does not offer the capability yields
	/// [`crate::kvs::Error::RangeDestroyNotSupported`]: nothing was deleted, so
	/// a caller holding a transactional fallback matches on that error and
	/// takes it, and every other caller propagates rather than mistaking an
	/// unperformed destroy for a completed one.
	///
	/// The destruction bypasses MVCC, so the caller owns two guarantees: the
	/// data is already logically inaccessible (typically because a committed
	/// transaction cleared the catalog entry naming it), and any snapshot that
	/// could still read it has expired.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self), fields(rng = range.to_string()))]
	pub async fn unsafe_destroy_range(&self, range: KeyRange<'static>) -> Result<()> {
		let Some(ops) = self.destroy_range_ops() else {
			return Err(crate::kvs::Error::RangeDestroyNotSupported.into());
		};
		ops.destroy_range(range).await.map_err(Into::into)
	}

	/// Resolve the backend's out-of-transaction range-destroy capability.
	///
	/// `None` means the backend cannot destroy a range outside a transaction —
	/// either it has no such primitive, or its current configuration cannot use
	/// the one it has. Resolved by capability rather than by backend name, so
	/// callers stay free of per-backend `cfg` arms and a new capable backend
	/// needs no change here.
	fn destroy_range_ops(&self) -> Option<Arc<dyn DestroyRange>> {
		let ext = self.transaction_factory.extension(TypeId::of::<DestroyRangeHandle>())?;
		let handle = ext.downcast::<DestroyRangeHandle>().ok()?;
		Some(Arc::clone(&handle.0))
	}

	/// Advance the MVCC garbage-collection safepoint by `lifetime`.
	///
	/// Routes through the backend's [`TransactionBuilder::extension`] hook;
	/// no-op on backends other than TiKV. Background tasks call this on
	/// `EngineOptions::tikv_gc_interval` and shutdown runs one final
	/// advisory pass.
	pub(crate) async fn run_mvcc_gc(&self, lifetime: Duration) -> Result<()> {
		#[cfg(feature = "kv-tikv")]
		if let Some(ops) = self.tikv_ops() {
			return ops.run_mvcc_gc(lifetime).await.map_err(Into::into);
		}
		let _ = lifetime;
		Ok(())
	}

	/// Resolve stale transactional locks left by crashed clients.
	///
	/// Routes through the backend's [`TransactionBuilder::extension`] hook;
	/// no-op on backends other than TiKV. Background tasks call this on
	/// `EngineOptions::tikv_lock_cleanup_interval`.
	pub(crate) async fn run_lock_cleanup(&self, lifetime: Duration) -> Result<()> {
		#[cfg(feature = "kv-tikv")]
		if let Some(ops) = self.tikv_ops() {
			return ops.run_lock_cleanup(lifetime).await.map_err(Into::into);
		}
		let _ = lifetime;
		Ok(())
	}

	/// Number of in-flight transactions tracked by the backend, when
	/// available. `None` indicates the backend does not track this.
	pub fn in_flight_transaction_count(&self) -> Option<usize> {
		#[cfg(feature = "kv-tikv")]
		if let Some(ops) = self.tikv_ops() {
			return Some(ops.in_flight_transaction_count());
		}
		None
	}

	/// Resolve the TiKV operational extension handle, if the backend is
	/// TiKV. Returns `None` for every other flavour.
	#[cfg(feature = "kv-tikv")]
	fn tikv_ops(&self) -> Option<Arc<surrealdb_kvs_any::tikv::TikvOpsHandle>> {
		let ext = self
			.transaction_factory
			.extension(TypeId::of::<surrealdb_kvs_any::tikv::TikvOpsHandle>())?;
		ext.downcast::<surrealdb_kvs_any::tikv::TikvOpsHandle>().ok()
	}

	// --------------------------------------------------
	// Surrealism eager loading
	// --------------------------------------------------

	/// Pre-load all Surrealism module runtimes into the cache so that
	/// subsequent query planning can resolve function metadata (e.g. the
	/// `writeable` flag) without triggering on-demand compilation.
	///
	/// Modules are loaded in parallel using a `JoinSet`. Any individual
	/// failure is logged but does not abort the overall loading process.
	#[cfg(feature = "surrealism")]
	pub async fn eager_load_surrealism_modules(&self) {
		use crate::catalog::providers::{DatabaseProvider, NamespaceProvider};
		use crate::surrealism::cache::SurrealismCacheLookup;

		let txn = match self.transaction(Read).await {
			Ok(txn) => Arc::new(txn),
			Err(e) => {
				warn!(target: TARGET, error = %e, "Surrealism eager load: failed to open transaction");
				return;
			}
		};

		let mut ctx = match self.setup_ctx() {
			Ok(ctx) => ctx,
			Err(e) => {
				warn!(target: TARGET, error = %e, "Surrealism eager load: failed to set up context");
				return;
			}
		};
		ctx.set_transaction(Arc::clone(&txn));
		let ctx = ctx.freeze();

		let nss = match txn.all_ns(None).await {
			Ok(nss) => nss,
			Err(e) => {
				warn!(target: TARGET, error = %e, "Surrealism eager load: failed to list namespaces");
				return;
			}
		};

		// Collect all module lookups first, then load in parallel.
		struct ModuleLookup {
			ns_id: crate::catalog::NamespaceId,
			db_id: crate::catalog::DatabaseId,
			bucket: String,
			key: String,
			display_name: String,
		}

		let mut lookups = Vec::new();
		for ns in nss.iter() {
			let dbs = match txn.all_db(ns.namespace_id, None).await {
				Ok(dbs) => dbs,
				Err(e) => {
					warn!(
						target: TARGET,
						error = %e, ns = %ns.name,
						"Surrealism eager load: failed to list databases"
					);
					continue;
				}
			};
			for db in dbs.iter() {
				let modules = match txn.all_db_modules(ns.namespace_id, db.database_id, None).await
				{
					Ok(m) => m,
					Err(e) => {
						warn!(
							target: TARGET,
							error = %e, ns = %ns.name, db = %db.name,
							"Surrealism eager load: failed to list modules"
						);
						continue;
					}
				};
				for md in modules.iter() {
					if let crate::catalog::ModuleExecutable::Surrealism(s) = &md.executable {
						lookups.push(ModuleLookup {
							ns_id: ns.namespace_id,
							db_id: db.database_id,
							bucket: s.bucket.clone(),
							key: s.key.clone(),
							display_name: md
								.name
								.clone()
								.unwrap_or_else(|| "<unnamed>".to_string()),
						});
					}
				}
			}
		}

		if lookups.is_empty() {
			debug!(target: TARGET, "Surrealism eager load: no modules to load");
			return;
		}

		let total = lookups.len();
		debug!(target: TARGET, count = total, "Surrealism eager load: loading modules");

		let concurrency =
			std::thread::available_parallelism().map(|n| n.get()).unwrap_or(8).clamp(2, 16);
		let load_sem = std::sync::Arc::new(tokio::sync::Semaphore::new(concurrency));

		let mut join_set = tokio::task::JoinSet::new();
		for lookup in lookups {
			let ctx = Arc::clone(&ctx);
			let load_sem = Arc::clone(&load_sem);
			join_set.spawn(async move {
				let _permit = load_sem
					.acquire_owned()
					.await
					.expect("Surrealism eager load semaphore must not be closed");
				let cache_lookup = SurrealismCacheLookup::File(
					&lookup.ns_id,
					&lookup.db_id,
					&lookup.bucket,
					&lookup.key,
				);
				match ctx.get_surrealism_runtime(cache_lookup).await {
					Ok(_) => {
						debug!(
							target: TARGET,
							module = %lookup.display_name,
							"Surrealism eager load: loaded module"
						);
						true
					}
					Err(e) => {
						warn!(
							target: TARGET,
							module = %lookup.display_name,
							error = %e,
							"Surrealism eager load: failed to load module"
						);
						false
					}
				}
			});
		}

		let mut loaded = 0usize;
		let mut failed = 0usize;
		while let Some(result) = join_set.join_next().await {
			match result {
				Ok(true) => loaded += 1,
				Ok(false) => failed += 1,
				Err(e) => {
					warn!(target: TARGET, error = %e, "Surrealism eager load: task panicked");
					failed += 1;
				}
			}
		}

		if failed > 0 {
			warn!(
				target: TARGET,
				loaded, failed, total,
				"Surrealism eager load: completed with failures"
			);
		} else {
			tracing::info!(
				target: TARGET,
				loaded, total,
				"Surrealism eager load: all modules loaded"
			);
		}
	}

	// --------------------------------------------------
	// Node functions
	// --------------------------------------------------

	/// Initialise the cluster and run bootstrap utilities
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn bootstrap(&self) -> Result<()> {
		// Each bootstrap step is retried independently, because concurrent instances
		// writing to the same cluster metadata keys may cause transaction conflicts.
		// Insert this node in the cluster
		Self::retry("Insert node", || self.insert_node()).await?;
		// Mark inactive nodes as archived
		Self::retry("Expire nodes", || self.expire_nodes()).await?;
		// Remove archived nodes
		Self::retry("Remove nodes", || self.remove_nodes()).await?;
		// Everything ok
		Ok(())
	}

	/// Runs a startup precondition until it succeeds or its budget runs out,
	/// retrying *every* failure rather than only a transaction conflict.
	///
	/// Almost every failure [`Self::get_version`] can report is the storage
	/// layer declining to serve a transaction. On a distributed backend that is
	/// what forming a cluster looks like from the outside — a replica refuses
	/// writes while a view change is in flight — and it clears on its own once
	/// formation settles. Those refusals are not distinguishable from each other
	/// by class, which is why the loop retries by default rather than by
	/// allow-list.
	///
	/// The exception is [`Self::is_permanent_bootstrap_failure`]: a marker whose
	/// bytes this build cannot read is a property of the disk, and waiting on it
	/// costs twice over — the caller waits out the whole budget, and the server,
	/// whose own ceiling is shorter, then reports a timeout in place of the error
	/// that would have named the problem.
	///
	/// The wait is bounded, and progress is reported on a fixed cadence rather
	/// than per attempt, so a long formation is visible in the log without the
	/// log growing with the retry rate.
	///
	/// The server wraps this in its own `SURREAL_STARTUP_OPERATION_TIMEOUT`
	/// budget, which is the operator-facing ceiling and is shorter than
	/// [`BOOTSTRAP_RETRY_BUDGET`] by default. This bound is what stops an
	/// embedder, which has no such wrapper, from waiting forever.
	/// Whether a bootstrap failure is a property of the bytes on disk rather
	/// than of the storage layer's availability.
	///
	/// These name a datastore this build cannot read, and no amount of waiting
	/// changes that. Matched by type rather than by rendered text, which is what
	/// the server's equivalent has to fall back on across the crate boundary.
	fn is_permanent_bootstrap_failure(err: &anyhow::Error) -> bool {
		err.chain().any(|e| {
			matches!(
				e.downcast_ref::<DatastoreError>(),
				Some(
					DatastoreError::InvalidStorageVersion
						| DatastoreError::OutdatedStorageVersion { .. }
						| DatastoreError::MigratedBeyondStorageVersion { .. }
				)
			)
		})
	}

	async fn retry_bootstrap<F, Fut, R>(task: &str, func: F) -> Result<R>
	where
		F: Fn() -> Fut,
		Fut: Future<Output = Result<R>>,
	{
		let started = Instant::now();
		let mut last_reported = started;
		let mut attempt = 1u32;
		// `None` after an attempt that never answered, which has no error to
		// carry; the report below distinguishes the two.
		let mut last_error = None;
		loop {
			let remaining = BOOTSTRAP_RETRY_BUDGET.saturating_sub(started.elapsed());
			if remaining.is_zero() {
				break;
			}
			// Bound the attempt itself as well as the budget: a backend that
			// accepts the transaction and then never answers would otherwise
			// spend the whole budget on one attempt.
			let attempt_timeout = BOOTSTRAP_RETRY_ATTEMPT_TIMEOUT.min(remaining);
			match timeout(attempt_timeout, func()).await {
				Ok(Ok(result)) => {
					if attempt > 1 {
						info!(
							target: TARGET,
							task, attempt, elapsed = ?started.elapsed(),
							"Storage became available and the startup step completed."
						);
					}
					return Ok(result);
				}
				Ok(Err(e)) if Self::is_permanent_bootstrap_failure(&e) => return Err(e),
				Ok(Err(e)) => last_error = Some(e),
				Err(_) => last_error = None,
			}
			// One line per interval, whatever the attempt rate, and the first
			// failure always reports so a wait is never silent.
			if attempt == 1 || last_reported.elapsed() >= BOOTSTRAP_RETRY_LOG_INTERVAL {
				last_reported = Instant::now();
				match &last_error {
					Some(e) => info!(
						target: TARGET,
						task, attempt, elapsed = ?started.elapsed(),
						budget = ?BOOTSTRAP_RETRY_BUDGET, error = %e,
						"Storage is not ready for the startup step yet; still retrying."
					),
					None => info!(
						target: TARGET,
						task, attempt, elapsed = ?started.elapsed(),
						budget = ?BOOTSTRAP_RETRY_BUDGET,
						timeout = ?attempt_timeout,
						"The startup step did not answer within its attempt timeout; still retrying."
					),
				}
			}
			let remaining = BOOTSTRAP_RETRY_BUDGET.saturating_sub(started.elapsed());
			if remaining.is_zero() {
				break;
			}
			// Exponential back-off with jitter, so the nodes of a cluster that
			// all restarted together do not retry in lockstep. The exponent is
			// capped before it is applied, not after: `Duration`'s multiplication
			// panics on overflow, so a doubling left to run free would abort the
			// process rather than saturate at the ceiling below it.
			let doublings = (attempt - 1).min(BOOTSTRAP_RETRY_MAX_DOUBLINGS);
			let backoff = (BOOTSTRAP_RETRY_MIN_BACKOFF * 2u32.pow(doublings))
				.min(BOOTSTRAP_RETRY_MAX_BACKOFF)
				.mul_f64(rand::rng().random_range(0.5..=1.5))
				.min(remaining);
			sleep(backoff).await;
			attempt = attempt.saturating_add(1);
		}
		match last_error {
			Some(e) => Err(e).context(format!(
				"{task} failed after {attempt} attempts over {:?}",
				started.elapsed()
			)),
			None => bail!(EngineError::Internal(format!(
				"{task} timed out after {attempt} attempts over {:?}",
				started.elapsed()
			))),
		}
	}

	/// Retries an async operation until it succeeds or the global timeout elapses.
	///
	/// Only [`TransactionConflict`](crate::kvs::Error::TransactionConflict)
	/// errors are retried; any other error is returned immediately to the
	/// caller. On each retryable failure a randomized delay (0–10 s) is
	/// applied before the next attempt, adding jitter to reduce repeated
	/// collisions when multiple instances start concurrently against the
	/// same storage backend.
	///
	/// The global timeout is checked only after a *failed* attempt; a successful
	/// result is always returned immediately, even if the elapsed time
	/// exceeds the budget. Each attempt's timeout is the lesser of its
	/// natural timeout (10 s * attempt number) and the remaining global
	/// budget, so total wall-clock time never significantly exceeds the
	/// global timeout. If no attempt succeeds within the budget, an error
	/// is returned.
	async fn retry<F, Fut, R>(task: &str, func: F) -> Result<R>
	where
		F: Fn() -> Fut,
		Fut: Future<Output = Result<R>>,
	{
		let global_timeout = Duration::from_secs(120);
		let per_attempt_timeout = Duration::from_secs(10);
		let time = Instant::now();
		let mut last_error = None;
		let mut attempt = 1;
		loop {
			// Cap each attempt to the remaining global budget
			let remaining = global_timeout.saturating_sub(time.elapsed());
			if remaining.is_zero() {
				break;
			}
			let attempt_timeout = (per_attempt_timeout * attempt).min(remaining);
			if let Ok(result) = timeout(attempt_timeout, func()).await {
				match result {
					Ok(result) => return Ok(result),
					Err(e) => {
						// Only retry on transaction conflict errors. Both the
						// bare `kvs::Error` and the `err::Error::Kvs`-wrapped
						// shape occur here: every `Transaction` write goes
						// through `.map_err(Error::from)`, and the operations
						// this loop retries all reach the store that way, so a
						// backend that surfaces a conflict at set/delete time
						// rather than at commit produces the wrapped one.
						if crate::kvs::is_retryable_transaction_conflict(&e) {
							last_error = Some(e);
						} else {
							return Err(e);
						}
					}
				}
			}
			// Check if the global timeout has been exceeded
			if time.elapsed() >= global_timeout {
				break;
			}
			// Randomized back-off capped to the remaining budget
			let remaining = global_timeout.saturating_sub(time.elapsed());
			if remaining.is_zero() {
				break;
			}
			let tempo = Duration::from_secs(rand::rng().random_range(0..10)).min(remaining);
			sleep(tempo).await;
			attempt += 1;
		}
		if let Some(e) = last_error {
			error!(target: TARGET, "{task} - All {attempt} attempts failed. Last error: {e}");
		} else {
			error!(target: TARGET, "{task} - All {attempt} attempts failed.");
		}
		bail!(EngineError::Internal(format!(
			"{task} failed after {attempt} attempts due to timeout"
		)));
	}

	/// Registers this node's cluster membership entry with a fresh heartbeat.
	///
	/// Must be run at server or database startup. The write is idempotent:
	/// the entry at `Nd::new(self.id)` is owned by this node, so the call
	/// upserts the row whether or not a previous lifetime of the same node
	/// id left a record behind. This supports deployments where the node id
	/// is stable across restarts (e.g. a stateful cluster member reusing
	/// its durable storage) without forcing the operator to clean up state
	/// between runs.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn insert_node(&self) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, id = %self.id,"Inserting node in the cluster");
		// Refresh system usage metrics
		crate::sys::refresh().await;
		// Open transaction and set node data
		let txn = self.transaction(Write).await?;
		let key = NodeKey {
			nd: self.id,
		};
		let now = self.clock_now();
		let node = Node::new_with_endpoint(self.id, now, false, self.http_endpoint.clone());
		run!(txn, txn.set_key(&key, &node).await)
	}

	/// Updates an already existing node in the cluster.
	///
	/// This function should be run periodically at a regular interval.
	///
	/// This function updates the entry for this node with an up-to-date
	/// timestamp. This ensures that the node is not marked as expired by any
	/// garbage collection tasks, preventing any data cleanup for this node.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn update_node(&self) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, id = %self.id, "Updating node in the cluster");
		// Open transaction and set node data
		let txn = self.transaction(Write).await?;
		let key = NodeKey {
			nd: self.id,
		};
		let now = self.clock_now();
		let node = Node::new_with_endpoint(self.id, now, false, self.http_endpoint.clone());
		run!(txn, txn.replace_key(&key, &node).await)
	}

	/// Updates this node, bounding each step and explicitly cancelling any
	/// open write transaction before returning on timeout or cancellation.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self, canceller))]
	pub(crate) async fn update_node_with_timeout(
		&self,
		timeout_duration: Duration,
		canceller: &CancellationToken,
	) -> Result<()> {
		trace!(target: TARGET, id = %self.id, timeout = ?timeout_duration, "Updating node in the cluster with timeout");

		let deadline = Instant::now() + timeout_duration;

		let txn =
			await_node_step(deadline, timeout_duration, Some(canceller), self.transaction(Write))
				.await?;
		let key = NodeKey {
			nd: self.id,
		};
		let now = self.clock_now();
		let node = Node::new_with_endpoint(self.id, now, false, self.http_endpoint.clone());

		await_node_tx_step(
			&txn,
			deadline,
			timeout_duration,
			Some(canceller),
			txn.replace_key(&key, &node),
		)
		.await?;
		await_node_tx_step(&txn, deadline, timeout_duration, Some(canceller), txn.commit()).await
	}

	/// Deletes a node from the cluster.
	///
	/// This function should be run when a node is shutting down.
	///
	/// This function marks the node as archived, ready for garbage collection.
	/// Later on when garbage collection is running the live queries assigned
	/// to this node will be removed, along with the node itself.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn delete_node(&self) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, id = %self.id, "Archiving node in the cluster");
		// Open transaction and set node data
		let txn = self.transaction(Write).await?;
		let key = NodeKey {
			nd: self.id,
		};
		let Some(val) = catch!(txn, txn.get_node(self.id).await) else {
			// Nothing to archive: this node either never registered, or a peer's
			// expiry scan has already reaped the row. Neither is a failure of
			// this shutdown, and reporting one would put an error above whatever
			// actually stopped the node.
			let _ = txn.cancel().await;
			return Ok(());
		};
		let node = val.as_ref().archive();
		run!(txn, txn.replace_key(&key, &node).await)
	}

	/// Archives this node, bounding each step and explicitly cancelling any
	/// open write transaction before returning on timeout.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn delete_node_with_timeout(&self, timeout_duration: Duration) -> Result<()> {
		trace!(target: TARGET, id = %self.id, timeout = ?timeout_duration, "Archiving node in the cluster with timeout");

		let deadline = Instant::now() + timeout_duration;
		let txn =
			await_node_step(deadline, timeout_duration, None, self.transaction(Write)).await?;
		let key = NodeKey {
			nd: self.id,
		};
		let val = await_node_tx_step(&txn, deadline, timeout_duration, None, txn.get_node(self.id))
			.await?;
		let Some(val) = val else {
			// Nothing to archive; see `delete_node`.
			let _ = txn.cancel().await;
			return Ok(());
		};
		let node = val.as_ref().archive();

		await_node_tx_step(&txn, deadline, timeout_duration, None, txn.replace_key(&key, &node))
			.await?;
		await_node_tx_step(&txn, deadline, timeout_duration, None, txn.commit()).await
	}

	/// Expires nodes which have timedout from the cluster.
	///
	/// This function should be run periodically at an interval.
	///
	/// This function marks the node as archived, ready for garbage collection.
	/// Later on when garbage collection is running the live queries assigned
	/// to this node will be removed, along with the node itself.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn expire_nodes(&self) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, "Archiving expired nodes in the cluster");
		// Fetch all of the inactive nodes
		let inactive = {
			let txn = self.transaction(Read).await?;
			let nds = catch!(txn, txn.all_nodes().await);
			let now = self.clock_now();
			catch!(txn, txn.cancel().await);
			// Filter the inactive nodes
			nds.iter()
				.filter_map(|n| {
					// Check that the node is active and has expired
					match n.is_active() && n.heartbeat < now - Duration::from_secs(30) {
						true => Some(n.to_owned()),
						false => None,
					}
				})
				.collect::<Vec<_>>()
		};
		// Check if there are inactive nodes
		if !inactive.is_empty() {
			// Open a writeable transaction
			let txn = self.transaction(Write).await?;
			// Whether any candidate still qualified once re-read below.
			let mut expired = false;
			// Archive the inactive nodes
			for nd in inactive.iter() {
				// Get the key for the node entry
				let key = NodeKey {
					nd: nd.id,
				};
				// The candidate set was sampled in an earlier transaction. A node
				// id that survives a restart can be re-registered inside that
				// window — `insert_node` upserts an active row under the same id,
				// with a fresh heartbeat — and archiving it here would retire a
				// live member. The write is therefore conditional on the heartbeat
				// the scan saw: a row whose heartbeat has moved has re-registered
				// or refreshed itself, and is no longer the row that expired.
				//
				// That closes the window in both directions. A commit that landed
				// before this transaction's snapshot is visible to this re-read,
				// and one racing this transaction writes the same key, which the
				// engine's write-conflict detection rejects.
				let current = catch!(txn, txn.get_key(&key, None).await);
				let Some(current) =
					current.filter(|n| n.is_active() && n.heartbeat == nd.heartbeat)
				else {
					trace!(target: TARGET, id = %nd.id, "Skipping node that is no longer expired");
					continue;
				};
				// Log the node archival
				trace!(target: TARGET, id = %nd.id, "Archiving node in the cluster");
				// Mark the node as archived, carrying the re-read row forward so
				// no field of the stale snapshot is written back
				let node = current.archive();
				// Update the node entry
				catch!(txn, txn.replace_key(&key, &node).await);
				expired = true;
			}
			// Commit the changes, or release the transaction when every candidate
			// turned out to be live after all
			match expired {
				true => catch!(txn, txn.commit().await),
				false => catch!(txn, txn.cancel().await),
			}
		}
		// Everything was successful
		Ok(())
	}

	/// Removes and cleans up nodes which are no longer in this cluster.
	///
	/// This function should be run periodically at an interval.
	///
	/// This function clears up all nodes which have been marked as archived.
	/// When a matching node is found, all node queries, and table queries are
	/// garbage collected, before the node itself is completely deleted.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn remove_nodes(&self) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, "Cleaning up archived nodes in the cluster");
		// Fetch all of the archived nodes
		let archived = {
			let txn = self.transaction(Read).await?;
			let nds = catch!(txn, txn.all_nodes().await);
			catch!(txn, txn.cancel().await);
			// Filter the archived nodes
			nds.iter().filter_map(Node::archived).collect::<Vec<_>>()
		};
		// Loop over the archived nodes
		for id in archived.iter() {
			// Open a writeable transaction
			let mut next = Some(
				NodeLiveQueryPrefix {
					nd: *id,
				}
				.range()?,
			);
			let txn = self.transaction(Write).await?;
			{
				// The archived set was sampled in an earlier transaction. A node
				// id that survives a restart can be re-registered inside that
				// window — `insert_node` upserts an active row under the same id
				// — and reaping it here would delete a live member along with the
				// live queries it has already registered. Re-read the row in this
				// transaction and only proceed while it is still archived.
				let key = NodeKey {
					nd: *id,
				};
				let node = catch!(txn, txn.get_key(&key, None).await);
				if !node.is_some_and(|nd| nd.is_archived()) {
					trace!(target: TARGET, id = %id, "Skipping node that is no longer archived");
					catch!(txn, txn.cancel().await);
					continue;
				}
			}
			{
				// Log the live query scanning
				trace!(target: TARGET, id = %id, "Deleting live queries for node");
				// Scan the live queries for this node
				while let Some(rng) = next {
					// Fetch the next batch of keys and values
					let res = catch!(
						txn,
						txn.batch_keys_vals(rng.clone(), NORMAL_BATCH_SIZE, None).await
					);
					// A full page carries a continuation: resume the range after
					// the last key this page returned.
					next = match (&res.next, res.result.last()) {
						(Some(_), Some((k, _))) => Some(rng.resume_after(k, Direction::Forward)),
						_ => None,
					};
					for (k, v) in res.result.iter() {
						// Decode the data for this live query
						let val: NodeLiveQuery = KVValue::kv_decode_value(v, ())?;
						// Get the key for this node live query
						let nlq = catch!(txn, NodeLiveQueryKey::decode_key(k));
						// Check that the node for this query is archived
						if archived.contains(&nlq.nd) {
							// Get the key for this table live query
							let tlq = SubscriptionKey {
								ns: val.ns,
								db: val.db,
								tb: Cow::Borrowed(&val.tb),
								lq: nlq.lq,
							};
							// Delete the table live query
							catch!(txn, txn.clr_key(&tlq).await);
							// Delete the node live query
							catch!(txn, txn.clr_key(&nlq).await);
						}
					}
					// Pause and yield execution
					yield_now!();
				}
			}
			{
				// Log the node deletion
				trace!(target: TARGET, id = %id, "Deleting node from the cluster");
				// Get the key for the node entry
				let key = NodeKey {
					nd: *id,
				};
				// Delete the cluster node entry
				catch!(txn, txn.clr_key(&key).await);
			}
			// Commit the changes
			catch!(txn, txn.commit().await);
		}
		// Everything was successful
		Ok(())
	}

	// ------------------------------
	// Durable RPC session functions
	// ------------------------------

	/// Creates or replaces the durable copy of a client-attached RPC session,
	/// expiring `ttl` from now (an unconditional upsert).
	///
	/// Session creation goes through [`create_rpc_session`](Self::create_rpc_session)
	/// (insert-if-absent), local changes through
	/// [`update_rpc_session`](Self::update_rpc_session) (update-if-present),
	/// and cross-node reconciliation through
	/// [`load_rpc_session`](Self::load_rpc_session), so none resurrects or
	/// duplicates a session across nodes. This blind upsert is retained as a
	/// primitive for callers that own the id exclusively (and for test setup).
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self, session))]
	pub async fn persist_rpc_session(
		&self,
		id: Uuid,
		session: &Session,
		ttl: Duration,
	) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, id = %id, "Persisting durable RPC session");
		// Capture the durable form with a refreshed expiry
		let expires_at = self.clock_now().value + ttl.as_millis() as u64;
		let value = durable_session(session, expires_at);
		// Open transaction and set the session data
		let key = SessionKey {
			id,
		};
		let txn = self.transaction(Write).await?;
		run!(txn, txn.set_key(&key, &value).await)
	}

	/// Creates the durable copy of a client-attached RPC session, but only if
	/// one does not already exist. Returns `true` if it created the entry,
	/// `false` if a session with this id already exists.
	///
	/// Uses a conditional insert (`put_compare_key` with no expected value),
	/// which is atomic even on last-writer-wins backends (TiKV) — a blind
	/// `set` is not — so two concurrent `attach`es for the same id on
	/// different nodes cannot both create it: one wins and the other is
	/// reported as an existing session, letting `attach` return
	/// `session_exists` instead of silently overwriting.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self, session))]
	pub async fn create_rpc_session(
		&self,
		id: Uuid,
		session: &Session,
		ttl: Duration,
	) -> Result<bool> {
		trace!(target: TARGET, id = %id, "Creating durable RPC session");
		let key = SessionKey {
			id,
		};
		let expires_at = self.clock_now().value + ttl.as_millis() as u64;
		let value = durable_session(session, expires_at);
		let txn = self.transaction(Write).await?;
		// `put_compare_key(.., None)` writes only if the key is absent.
		match txn.put_compare_key(&key, &value, None).await {
			Ok(()) => match txn.commit().await {
				Ok(()) => Ok(true),
				// Cancel after any failed commit (a conflict or otherwise), so
				// the transaction is rolled back consistently with the `run!`
				// macro; only the error classification differs.
				Err(e) if super::is_conditional_write_conflict(&e) => {
					let _ = txn.cancel().await;
					Ok(false)
				}
				Err(e) => {
					let _ = txn.cancel().await;
					Err(e)
				}
			},
			Err(e) => {
				let _ = txn.cancel().await;
				if super::is_conditional_write_conflict(&e) {
					Ok(false)
				} else {
					Err(e)
				}
			}
		}
	}

	/// Refreshes the durable copy of an *existing* RPC session with the given
	/// value, expiring `ttl` from now, **without recreating it** if it is gone.
	///
	/// Returns `true` if the entry was present and updated, `false` if it no
	/// longer exists (or was changed on another node). Uses a conditional
	/// write (`put_compare_key` guarded by the value just read), so it is
	/// atomic on last-writer-wins backends (TiKV): a session deleted elsewhere
	/// between the read and the write is neither resurrected nor clobbered — a
	/// blind `set` would be last-writer-wins and could resurrect it. This is
	/// the "push a local change to storage" path (a session-mutating method);
	/// the authoritative *reload* path is
	/// [`load_rpc_session`](Self::load_rpc_session).
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self, session))]
	pub async fn update_rpc_session(
		&self,
		id: Uuid,
		session: &Session,
		ttl: Duration,
	) -> Result<bool> {
		trace!(target: TARGET, id = %id, "Updating durable RPC session");
		let key = SessionKey {
			id,
		};
		let txn = self.transaction(Write).await?;
		// Read the current stored value to use as the conditional-write guard.
		let Some(current) = catch!(txn, txn.get_key(&key, None).await) else {
			let _ = txn.cancel().await;
			return Ok(false);
		};
		let expires_at = self.clock_now().value + ttl.as_millis() as u64;
		let value = durable_session(session, expires_at);
		// Write only if the stored value is still the one we read, so a delete
		// or change committed on another node in between wins (no resurrection,
		// no clobber) instead of being overwritten by this blind write.
		match txn.put_compare_key(&key, &value, Some(&current)).await {
			Ok(()) => match txn.commit().await {
				Ok(()) => Ok(true),
				// Cancel after any failed commit (a conflict or otherwise), so
				// the transaction is rolled back consistently with the `run!`
				// macro; only the error classification differs.
				Err(e) if super::is_conditional_write_conflict(&e) => {
					let _ = txn.cancel().await;
					Ok(false)
				}
				Err(e) => {
					let _ = txn.cancel().await;
					Err(e)
				}
			},
			Err(e) => {
				let _ = txn.cancel().await;
				if super::is_conditional_write_conflict(&e) {
					Ok(false)
				} else {
					Err(e)
				}
			}
		}
	}

	/// Loads the current durable copy of a client-attached RPC session — the
	/// authoritative cross-node state — returning the restored session and its
	/// absolute expiry (ms since the UNIX epoch), or `None` if it is gone or
	/// expired.
	///
	/// This is a pure read plus lazy expiry: an entry past its `expires_at` is
	/// deleted and reported as a miss, but a live entry is returned **without**
	/// being rewritten. It never extends a session's life, so it is safe to
	/// call before the caller is authorized — both when `get_session`
	/// rehydrates an evicted session and when the transport reconciles a
	/// cached session against storage before dispatch. The TTL is slid only
	/// after authorization, by [`update_rpc_session`](Self::update_rpc_session).
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn load_rpc_session(&self, id: Uuid) -> Result<Option<(Session, u64)>> {
		// Log when this method is run
		trace!(target: TARGET, id = %id, "Loading durable RPC session");
		let key = SessionKey {
			id,
		};
		let now = self.clock_now().value;
		// Pure read.
		let durable = {
			let txn = self.transaction(Read).await?;
			let val = catch!(txn, txn.get_key(&key, None).await);
			catch!(txn, txn.cancel().await);
			val
		};
		let Some(durable) = durable else {
			return Ok(None);
		};
		// Lazily delete an expired entry with a conditional delete guarded by
		// the value we read, so a refresh committed on another node between the
		// read and the delete is not clobbered (a blind `clr` is
		// last-writer-wins on TiKV). On a condition conflict the entry changed
		// — leave it and report a miss for this request; it rehydrates fresh on
		// the next one.
		if durable.expires_at <= now {
			trace!(target: TARGET, id = %id, "Durable RPC session has expired");
			let txn = self.transaction(Write).await?;
			match txn.del_compare_key(&key, Some(&durable)).await {
				Ok(()) => match txn.commit().await {
					Ok(()) => {}
					Err(e) if super::is_conditional_write_conflict(&e) => {
						let _ = txn.cancel().await;
					}
					Err(e) => {
						let _ = txn.cancel().await;
						return Err(e);
					}
				},
				Err(e) => {
					let _ = txn.cancel().await;
					if !super::is_conditional_write_conflict(&e) {
						return Err(e);
					}
				}
			}
			return Ok(None);
		}
		// Restore the in-memory session without touching the durable copy,
		// handing back the stored expiry so the caller can enforce the TTL.
		let expires_at = durable.expires_at;
		restore_session(durable).map(|session| Some((session, expires_at)))
	}

	/// Deletes the durable copy of a client-attached RPC session, when it is
	/// still the value being torn down.
	///
	/// Run on detach/teardown so the session cannot be rehydrated. It reads the
	/// current value and deletes only that (`del_compare_key`), rather than
	/// clearing the key blindly: a blind `clr` is last-writer-wins on TiKV, so
	/// a slow detach could otherwise delete a *newer* session that another node
	/// re-attached under the same id after the old one was removed. An entry
	/// already absent is a no-op.
	///
	/// A condition conflict — the stored value changed between the read and the
	/// delete (a concurrent refresh/re-attach on another node) — is surfaced as
	/// an **error**, not swallowed: the durable copy was *not* removed, so
	/// reporting success would let [`RpcProtocol::forget_session`]/`detach`
	/// claim the session was torn down while it remains rehydratable. The
	/// caller (whose `del_session` removes the durable copy before local state)
	/// then fails the teardown and can retry, keeping detach fail-closed. In
	/// the supported single-node-per-session model such a conflict does not
	/// arise (the owning node serializes the session's writes).
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn delete_rpc_session(&self, id: Uuid) -> Result<()> {
		// Log when this method is run
		trace!(target: TARGET, id = %id, "Deleting durable RPC session");
		let key = SessionKey {
			id,
		};
		let txn = self.transaction(Write).await?;
		// Read the value we intend to remove; if it is already gone, done.
		let Some(current) = catch!(txn, txn.get_key(&key, None).await) else {
			let _ = txn.cancel().await;
			return Ok(());
		};
		// Delete only if the stored value is still the one we read. A conflict
		// (value changed concurrently) means the delete did not happen, so it
		// is surfaced as an error rather than reported as a successful teardown.
		match txn.del_compare_key(&key, Some(&current)).await {
			Ok(()) => match txn.commit().await {
				Ok(()) => Ok(()),
				Err(e) => {
					let _ = txn.cancel().await;
					Err(e)
				}
			},
			Err(e) => {
				let _ = txn.cancel().await;
				Err(e)
			}
		}
	}

	/// Purges expired durable RPC sessions.
	///
	/// This function should be run periodically at a regular interval.
	///
	/// It uses a distributed task lease so only one node in the cluster
	/// performs the purge per interval. Entries are scanned in batches, and
	/// only entries whose expiry has passed are deleted; an entry that fails
	/// to decode (for example one written by a newer node during a rolling
	/// upgrade) is skipped, never deleted.
	///
	/// # Arguments
	/// * `interval` - The interval between purge runs, to calculate the lease duration
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub(crate) async fn purge_expired_rpc_sessions(&self, interval: &Duration) -> Result<()> {
		// Output function invocation details to logs
		trace!(target: TARGET, "Attempting expired RPC session purge");
		// Create a new lease handler
		let lh = LeaseHandler::new(
			self.sequences.clone(),
			self.id,
			self.transaction_factory.clone(),
			TaskLeaseType::RpcSessionCleanup,
			*interval * 2,
		)?;
		// If we don't get the lease, another node is handling this task
		if !lh.has_lease().await? {
			return Ok(());
		}
		// Output function invocation details to logs
		trace!(target: TARGET, "Purging expired RPC sessions");
		let now = self.clock_now().value;
		// Scan the durable session entries in batches under read transactions,
		// deleting each expired entry in its own conditional-delete write
		// transaction. The delete is guarded by the value read
		// (`del_compare_key`), so a request that refreshed the session after
		// the scan read the old expired value is not clobbered — a blind `clr`
		// is last-writer-wins on TiKV. A per-entry transaction keeps one such
		// conflict from aborting the whole purge.
		let mut next = Some(SessionPrefix {}.range()?);
		while let Some(rng) = next {
			// Fetch the next batch of keys and values under a read transaction.
			let batch = {
				let txn = self.transaction(Read).await?;
				let res =
					catch!(txn, txn.batch_keys_vals(rng.clone(), NORMAL_BATCH_SIZE, None).await);
				catch!(txn, txn.cancel().await);
				res
			};
			// A full page carries a continuation: resume the range after the last
			// key this page returned.
			next = match (&batch.next, batch.result.last()) {
				(Some(_), Some((k, _))) => Some(rng.resume_after(k, Direction::Forward)),
				_ => None,
			};
			for (k, v) in batch.result.iter() {
				// Decode the data for this session entry. Skip (but never
				// delete) an entry we cannot decode: it may have been written
				// by a newer node during a rolling upgrade.
				let val: DurableSession = match KVValue::kv_decode_value(v, ()) {
					Ok(val) => val,
					Err(e) => {
						warn!(target: TARGET, "Skipping undecodable durable RPC session entry: {e}");
						continue;
					}
				};
				// Only delete an expired entry, and only if it is still the
				// value we read.
				if val.expires_at <= now {
					let key = SessionKey::decode_key(k)?;
					trace!(target: TARGET, id = %key.id, "Purging expired RPC session");
					let txn = self.transaction(Write).await?;
					match txn.del_compare_key(&key, Some(&val)).await {
						Ok(()) => match txn.commit().await {
							Ok(()) => {}
							// Refreshed concurrently at commit (TiKV): leave it.
							Err(e) if super::is_conditional_write_conflict(&e) => {
								let _ = txn.cancel().await;
							}
							Err(e) => {
								let _ = txn.cancel().await;
								return Err(e);
							}
						},
						Err(e) => {
							let _ = txn.cancel().await;
							if !super::is_conditional_write_conflict(&e) {
								return Err(e);
							}
						}
					}
				}
			}
			// Pause and yield execution
			yield_now!();
		}
		// Everything was successful
		Ok(())
	}

	// --------------------------------------------------
	// Live query functions
	// --------------------------------------------------

	/// Clean up the live queries for a disconnected connection.
	///
	/// This function should be run when a WebSocket disconnects.
	///
	/// This function clears up the live queries on the current node, which
	/// are specified by uique live query UUIDs. This is necessary when a
	/// WebSocket disconnects, and any associated live queries need to be
	/// cleaned up and removed.
	#[instrument(err, level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn delete_queries(&self, ids: Vec<uuid::Uuid>) -> Result<()> {
		// Log the node deletion
		trace!(target: TARGET, "Deleting live queries for a connection");
		// Fetch expired nodes
		let txn = self.transaction(Write).await?;
		// Loop over the live query unique ids
		for id in ids {
			// Get the key for this node live query
			let nlq = NodeLiveQueryKey {
				nd: self.id(),
				lq: id,
			};
			// Fetch the LIVE meta data node entry
			if let Some(lq) = catch!(txn, txn.get_key(&nlq, None).await) {
				// Get the key for this node live query
				let nlq = NodeLiveQueryKey {
					nd: self.id(),
					lq: id,
				};
				// Get the key for this table live query
				let tlq = SubscriptionKey {
					ns: lq.ns,
					db: lq.db,
					tb: Cow::Borrowed(&lq.tb),
					lq: id,
				};
				// Delete the table live query
				catch!(txn, txn.clr_key(&tlq).await);
				// Delete the node live query
				catch!(txn, txn.clr_key(&nlq).await);
			}
		}
		// Commit the changes
		catch!(txn, txn.commit().await);
		// All ok
		Ok(())
	}

	// --------------------------------------------------
	// Changefeed functions
	// --------------------------------------------------

	/// Performs changefeed garbage collection as a background task.
	///
	/// This method is responsible for cleaning up old changefeed data across
	/// all databases. It uses a distributed task lease mechanism to coordinate
	/// which node performs this maintenance operation. Once a batch starts it
	/// runs to completion even if the lease expires, so brief overlap is
	/// possible.
	///
	/// The process involves:
	/// 1. Acquiring a lease for the ChangeFeedCleanup task
	/// 2. Cleaning up old changefeed data from all databases
	///
	/// # Arguments
	/// * `interval` - The interval between compaction runs, to calculate the lease duration
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self))]
	pub async fn changefeed_process(
		&self,
		interval: &Duration,
		canceller: &CancellationToken,
	) -> Result<()> {
		self.changefeed_process_bounded(interval, CHANGEFEED_GC_PASS_KEY_BUDGET, canceller).await
	}

	/// [`Self::changefeed_process`] with the per-pass key budget lowered, so a
	/// test can drive a pass that stops mid-backlog and inspect what it left
	/// behind.
	#[cfg(test)]
	#[cfg_attr(not(feature = "kv-mem"), allow(dead_code))]
	pub(crate) async fn changefeed_gc_with_budget(
		&self,
		interval: &Duration,
		budget: u64,
		canceller: &CancellationToken,
	) -> Result<()> {
		self.changefeed_process_bounded(interval, budget, canceller).await
	}

	/// One changefeed-collection pass, deleting at most `budget` entries from
	/// each keyspace it collects.
	///
	/// The changefeed backlog and, under the Router engine, the live-query event
	/// backlog are both sized by write throughput rather than by the catalog, so
	/// neither is deleted in one transaction: each is paged behind committed
	/// transactions of at most one page (see [`crate::kvs::paging`]). A pass
	/// therefore costs a bounded amount of work however far either backlog has
	/// run ahead, and the next tick resumes at the head of what survives.
	///
	/// The two keyspaces share this pass's lease but hold separate budgets. The
	/// same writes fill both, so a budget spanning them would let whichever is
	/// collected first spend it whenever the write rate outran it, leaving the
	/// other uncollected on every pass and growing on disk without limit.
	async fn changefeed_process_bounded(
		&self,
		interval: &Duration,
		budget: u64,
		canceller: &CancellationToken,
	) -> Result<()> {
		// Output function invocation details to logs
		trace!(target: TARGET, "Attempting changefeed garbage collection");
		// Create a new lease handler
		let lh = LeaseHandler::new(
			self.sequences.clone(),
			self.id,
			self.transaction_factory.clone(),
			TaskLeaseType::ChangeFeedCleanup,
			*interval * 2,
		)?;
		// If we don't get the lease, another node is handling this task
		if !lh.has_lease().await? {
			return Ok(());
		}
		// Output function invocation details to logs
		trace!(target: TARGET, "Running changefeed garbage collection");
		// Entries this pass may delete from the changefeed keyspace, shared out
		// across the databases it visits.
		let mut cf_budget = budget;
		// Perform the changefeed garbage collection. A pass that lost the lease
		// ends this one: the live-query collector below shares the lease, and its
		// own first check would be answered from the maintenance throttle by the
		// very check that lost it — so it would delete alongside the new holder.
		if !crate::cf::gc_all_at(self, &lh, canceller, &mut cf_budget).await? {
			return Ok(());
		}
		// When the Router engine is active, also garbage-collect the dedicated
		// live-query event keyspace, retaining entries for the configured window so
		// reconnecting/lagging subscribers can still replay. This shares the
		// pass's lease with the changefeed GC above and spends its own budget.
		if self.config.datastore.live_query_engine == LiveQueryEngine::Router {
			let retention = self.config.datastore.live_query_retention;
			let mut lq_budget = budget;
			crate::lq::gc::gc_all_at(self, &lh, retention, canceller, &mut lq_budget).await?;
		}
		// Everything ok
		Ok(())
	}

	/// Run one live-query router pass.
	///
	/// Under the [`LiveQueryEngine::Router`] engine this tails the dedicated
	/// `lqe` keyspace since the node's cursor and delivers notifications off the
	/// write path (see [`crate::lq::router`]); it is the sole delivery path in
	/// that mode. Under the default [`LiveQueryEngine::Inline`] engine it is a
	/// cheap no-op, so the engine's background task can call it unconditionally.
	/// Unlike changefeed GC this runs on every node without a lease: each node
	/// delivers only to the subscriptions it owns.
	#[instrument(level = "trace", target = "surrealdb::core::lq", skip(self))]
	pub(crate) async fn live_query_router_process(&self) -> Result<()> {
		// Only the Router engine delivers via the router.
		if self.config.datastore.live_query_engine != LiveQueryEngine::Router {
			return Ok(());
		}
		crate::lq::router::process(self, &self.live_query_router).await
	}

	// --------------------------------------------------
	// Indexing functions
	// --------------------------------------------------

	pub(crate) fn ensure_not_cancelled(canceller: &CancellationToken) -> Result<()> {
		if canceller.is_cancelled() {
			bail!(EngineError::QueryCancelled);
		}
		Ok(())
	}

	/// Processes the index compaction queue.
	///
	/// This method is called periodically by the index compaction thread to
	/// process indexes that have been marked for compaction. It acquires a
	/// distributed lease to coordinate compaction across the cluster. Once a
	/// batch starts it runs to completion even if the lease expires, so brief
	/// overlap is possible.
	///
	/// The method scans the index compaction queue (stored as `Ic` keys) and
	/// delegates to [`Self::index_compaction_loop`], which compacts each
	/// distinct index exactly once — duplicate queue entries for the same
	/// index are skipped. On native targets compaction tasks run in parallel
	/// (one spawned task per index), while on wasm they run sequentially.
	/// Indexes that support compaction include full-text, count, and HNSW.
	///
	/// The queue is read in a short-lived read transaction so that user
	/// transactions enqueueing new compaction requests do not conflict with
	/// the compaction cycle. Each index compaction runs on its own write
	/// transaction. Once all compactions have completed, a separate write
	/// transaction removes the processed queue entries. Compaction failures
	/// are logged but do not prevent other indexes from being processed.
	///
	/// # Arguments
	/// * `dbs` - The shared datastore instance, cloned into each compaction task
	/// * `interval` - The interval between compaction runs, used to calculate the lease duration
	/// * `canceller` - Token checked before starting each lease, batch, and compaction unit
	///
	/// # Returns
	/// A tuple `(iterations, errors)` where `iterations` is the number of
	/// compaction batches processed and `errors` is the total number of
	/// individual index compaction failures across all batches.
	/// Resume index builds stranded by a crashed or expired owner node.
	///
	/// A `CONCURRENTLY` index build runs as a detached task. If its owning node
	/// dies mid-build, nothing waits on that generation again, so the durable
	/// build state stays in `Building`/`Closing` and the index reports
	/// `status: indexing` with a frozen counter indefinitely. This scan adopts
	/// such builds — once their owner lease has expired — via the existing
	/// expired-lease takeover (see [`IndexBuilder::resume_stalled`]) and drives
	/// them to completion.
	///
	/// The scan is lease-guarded so a single node runs it per cluster; the
	/// per-index takeover is additionally CAS-guarded, so correctness does not
	/// depend on the lease. Enumeration walks the catalog, so cost is
	/// proportional to the total index count; operators who prefer to recover
	/// stalled builds manually (with `REBUILD INDEX`) can disable the scan by
	/// setting its interval to zero.
	///
	/// Recovery is serialized: a pass adopts at most one stalled build, and
	/// no pass adopts anything while a local builder task is still running.
	/// A restart with several stranded builds (for example multiple full-text
	/// indexes on a small instance) therefore rebuilds them one at a time
	/// instead of multiplying the node's memory and CPU footprint; every
	/// stalled build is still recovered, one scan pass after the previous one
	/// finishes. User-initiated `REBUILD INDEX` is not throttled by this.
	///
	/// Returns the number of stalled builds adopted this pass.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self, canceller))]
	pub(crate) async fn resume_stalled_index_builds(
		&self,
		interval: Duration,
		canceller: CancellationToken,
	) -> Result<usize> {
		Self::ensure_not_cancelled(&canceller)?;
		// Single-node-per-cluster guard. The lease lasts two intervals so an
		// in-flight scan isn't preempted between ticks.
		let lh = LeaseHandler::new_with_canceller(
			self.sequences.clone(),
			self.id,
			self.transaction_factory.clone(),
			TaskLeaseType::IndexBuildResume,
			interval * 2,
			canceller.clone(),
		)?;
		if !lh.has_lease().await? {
			return Ok(0);
		}
		// Serialize recovery: while any local builder task is still running
		// (a previously adopted build or a user-started one), defer further
		// adoptions to a later pass. Without this, a restart with several
		// stranded builds starts them all at once, and the concurrent initial
		// scans can overwhelm a small instance's memory and CPU.
		if self.index_builder.has_unfinished_build().await {
			trace!(
				target: TARGET,
				"Deferring stalled index build adoption; a local index build is still running"
			);
			return Ok(0);
		}
		// Snapshot the (ns, db, table, index) hierarchy in a short read
		// transaction. Index definitions are cloned out so the per-index
		// build-state checks below don't hold the catalog transaction open.
		let mut candidates = Vec::new();
		{
			let txn = self.transaction(Read).await?;
			let res: Result<()> = async {
				for ns in txn.all_ns(None).await?.iter() {
					for db in txn.all_db(ns.namespace_id, None).await?.iter() {
						for tb in txn.all_tb(ns.namespace_id, db.database_id, None).await?.iter() {
							for ix in txn
								.all_tb_indexes(
									ns.namespace_id,
									db.database_id,
									&tb.name.clone(),
									None,
								)
								.await?
								.iter()
							{
								// Indexes pending removal are cleared by the
								// tombstone reaper, not resumed.
								if ix.prepare_remove {
									continue;
								}
								candidates.push((
									ns.namespace_id,
									ns.name.clone(),
									db.database_id,
									db.name.clone(),
									tb.table_id,
									Arc::new(ix.clone()),
								));
							}
						}
					}
				}
				Ok(())
			}
			.await;
			let _ = txn.cancel().await;
			res?;
		}
		// Attempt a takeover for each candidate. `resume_stalled` is a cheap
		// no-op for healthy/online/live builds, so this is safe to call for
		// every index every pass.
		let index_builder = &self.index_builder;
		let mut resumed = 0;
		for (ns_id, ns_name, db_id, db_name, tb_id, ix) in candidates {
			Self::ensure_not_cancelled(&canceller)?;
			lh.try_maintain_lease().await?;
			let ctx = self.setup_ctx()?.freeze();
			let opt = self.setup_options(
				&Session::owner().with_ns(ns_name.as_str()).with_db(db_name.as_str()),
			);
			match index_builder
				.resume_stalled(&ctx, opt, ns_id, db_id, tb_id, Arc::clone(&ix))
				.await
			{
				Ok(true) => {
					resumed += 1;
					info!(
						target: TARGET,
						"Resuming stalled index build '{}' on table '{}'",
						ix.name, ix.table_name
					);
					// One adoption per pass: a later pass adopts the next
					// stalled build once this one has finished, keeping
					// recovery sequential on this node.
					break;
				}
				Ok(false) => {}
				Err(e) => {
					warn!(
						target: TARGET,
						"Failed to resume stalled index build '{}' on table '{}': {e}",
						ix.name, ix.table_name
					);
				}
			}
		}
		Ok(resumed)
	}

	/// Drains the index-compaction queue (`/!ic` keys) in bounded batches.
	///
	/// Each iteration scans at most [`INDEX_COMPACTION_QUEUE_BATCH_SIZE`]
	/// queue keys, compacts every distinct index they reference, and then
	/// deletes exactly those keys in one write transaction, so no single
	/// transaction's key cardinality exceeds the batch size regardless of how
	/// many entries have accumulated. Entries enqueued after a batch's scan
	/// are untouched by its cleanup and are picked up by a later iteration
	/// (or a later invocation), so a queue entry is only ever removed after
	/// its index has been compacted at-or-after the entry was written.
	///
	/// Batches rotate across indexes: each batch's scan resumes past the last
	/// index the previous batch covered and wraps at the end of the queue
	/// range, so every index with pending entries is visited once per
	/// rotation regardless of relative enqueue and drain rates — an index
	/// sustaining a full batch of new entries per iteration still cannot pin
	/// the scan to itself (a start-anchored or key-successor scan only stays
	/// fair while the drain outpaces the enqueue).
	///
	/// Under sustained enqueue the drain keeps running — every iteration
	/// stays bounded — and stops when the queue empties, the lease is lost,
	/// or the task is cancelled.
	///
	/// Coordinated across the cluster by a [`TaskLeaseType::IndexCompaction`]
	/// lease. Returns the number of processed batches and the number of
	/// indexes that failed to compact.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(dbs, canceller))]
	pub async fn index_compaction(
		dbs: Arc<Datastore>,
		interval: Duration,
		canceller: CancellationToken,
	) -> Result<(usize, usize)> {
		// Output function invocation details to logs
		trace!(target: TARGET, "Attempting index compaction process");
		// Create a new lease handler
		let lh = LeaseHandler::new_with_canceller(
			dbs.sequences.clone(),
			dbs.id,
			dbs.transaction_factory.clone(),
			TaskLeaseType::IndexCompaction,
			interval * 2,
			canceller.clone(),
		)?;
		let mut count_iteration = 0;
		let mut count_error = 0;
		// The queue range and a rotating window within it. After each batch
		// the window resumes past the last index that batch covered, so
		// indexes later in the keyspace are reached even while an
		// earlier-sorting index keeps enqueueing new entries (queue keys
		// sort by ns/db/tb/ix before their time-ordered UUID, so a hot
		// index would otherwise pin a start-anchored scan to itself). When
		// the scan reaches the end of the range it wraps to the start, and
		// a wrap that finds nothing means the queue is drained.
		let queue = IndexCompactionPrefix {}.range()?;
		let mut window = queue.clone();
		// We continue without interruptions while there are keys and the lease
		'compaction: loop {
			Self::ensure_not_cancelled(&canceller)?;
			// Attempt to acquire a lease for the IndexCompaction task
			// If we don't get the lease, another node is handling this task
			if !lh.has_lease().await? {
				return Ok((count_iteration, count_error));
			}
			Self::ensure_not_cancelled(&canceller)?;
			// Output function invocation details to logs
			trace!(target: TARGET, "Running index compaction process");
			// Read one bounded batch of queue keys in a short-lived read
			// transaction. The queue holds one entry per indexed record
			// write since it last drained, so an unbounded snapshot would
			// make the cleanup transaction below arbitrarily large — every
			// key it deletes is a per-replica write reservation on
			// distributed backends. Queue values carry no payload, so a
			// keys-only scan suffices.
			let keys = {
				let txn = dbs.transaction(Read).await?;
				let res =
					txn.keys(window.clone(), INDEX_COMPACTION_QUEUE_BATCH_SIZE, 0, None).await;
				let _ = txn.cancel().await;
				res?
			};
			Self::ensure_not_cancelled(&canceller)?;
			if keys.is_empty() {
				if window.start() == queue.start() {
					// Nothing left anywhere in the queue.
					return Ok((count_iteration, count_error));
				}
				// End of the range: wrap to re-scan entries that were
				// skipped when the window seeked past a partially-drained
				// index.
				window = queue.clone();
				continue;
			}
			// Compact each distinct index referenced by this batch before
			// deleting the batch's queue entries: an entry may only be
			// removed once its index has been compacted at-or-after the
			// entry was enqueued.
			count_iteration += 1;
			count_error +=
				Self::index_compaction_loop(Arc::clone(&dbs), &lh, &keys, canceller.clone())
					.await?;
			// Seek the next batch past the last index this batch covered.
			// Entries of that index beyond this batch are picked up again
			// after the window wraps, so a continuously-refilling index
			// cannot starve later-sorting ones. A key that fails to decode
			// cannot name an index to seek past: fall back to resuming
			// immediately after the key itself, so the scan still advances and
			// the cleanup below still removes the undecodable entry (it
			// references no valid index, so deleting it cannot violate the
			// compact-before-delete invariant).
			if let Some(last_key) = keys.last() {
				window = match IndexCompactionKey::decode_key(last_key) {
					Ok(last) => {
						// The first key ordering after the whole index's run of
						// queue entries.
						let covered = IndexCompactionIxPrefix {
							ns: last.ns,
							db: last.db,
							tb: Cow::Owned(last.tb.into_owned()),
							ix: last.ix,
						}
						.skip_extensions()?;
						queue.clone().resume_after(&covered, Direction::Forward)
					}
					Err(e) => {
						warn!(target: TARGET, "Skipping undecodable index compaction queue entry: {e}");
						queue.clone().resume_after(last_key, Direction::Forward)
					}
				};
			}
			// Delete this batch's queue entries in a separate write
			// transaction, bounded by the batch size. This avoids conflicts
			// with concurrent user transactions that may enqueue new
			// compaction requests. Failed indexes are not re-enqueued here;
			// the next user write to the affected index will naturally
			// trigger a new compaction request.
			loop {
				let txn = dbs.transaction(Write).await?;
				if let Err(e) = Self::ensure_not_cancelled(&canceller) {
					let _ = txn.cancel().await;
					return Err(e);
				}
				// Deleted as bytes rather than through the decoded key, because
				// the batch deliberately includes entries that do not decode. An
				// undecodable entry names no index, so it can never be compacted
				// and a typed delete could never address it; leaving it would
				// park it at the head of the queue forever.
				for k in &keys {
					if let Err(e) = txn.del(Key::from(k)).await {
						warn!(target: TARGET, "Failed to delete compaction queue entry: {e}");
					}
				}
				if let Err(e) = Self::ensure_not_cancelled(&canceller) {
					let _ = txn.cancel().await;
					return Err(e);
				}
				#[cfg(test)]
				if let Err(e) = maybe_inject_retryable_conflict(
					RetryableConflictSite::IndexCompactionQueueCleanup,
					dbs.id,
				) {
					if Self::cancel_and_retry_index_operation_conflict(
						&txn,
						&e,
						"Retryable conflict committing compaction queue cleanup, retrying",
					)
					.await
					{
						continue;
					}
					warn!(target: TARGET, "Failed to commit compaction queue cleanup: {e}");
					break 'compaction;
				}
				if let Err(e) = txn.commit().await {
					if Self::cancel_and_retry_index_operation_conflict(
						&txn,
						&e,
						"Retryable conflict committing compaction queue cleanup, retrying",
					)
					.await
					{
						continue;
					}
					warn!(target: TARGET, "Failed to commit compaction queue cleanup: {e}");
					break 'compaction;
				}
				break;
			}
		}
		Ok((count_iteration, count_error))
	}

	/// Periodically drains the background reclaim queue (`/!rc` keys),
	/// destroying the data prefix of namespaces/databases/indexes that were
	/// removed by a committed `REMOVE` statement.
	///
	/// `REMOVE NAMESPACE/DATABASE/INDEX` delete only the catalog definition
	/// inside the user transaction and enqueue a [`ReclaimKey`]; this task
	/// performs the expensive data deletion out-of-band so the user statement
	/// returns immediately and never trips a request/transaction timeout.
	///
	/// Coordinated across the cluster by a [`TaskLeaseType::ReclaimTombstones`]
	/// lease so only one node reclaims at a time. The queue is walked in batches
	/// of at most [`RECLAIM_BATCH_SIZE`] entries, each read in a short-lived
	/// read transaction and each retired or stamped in one write transaction of
	/// its own, so neither the pass's snapshot nor its queue update grows with
	/// the number of pending removals. Each prefix is then destroyed
	/// independently and idempotently — in one out-of-transaction call on a
	/// backend offering [`DestroyRange`], otherwise in bounded pages, each
	/// committed together with the resume cursor that accounts for it. A queue
	/// entry is retired only once its prefix is empty, so a crash or an
	/// exhausted budget mid-reclaim resumes from the committed cursor on a later
	/// pass instead of restarting the prefix.
	///
	/// One pass deletes at most [`RECLAIM_PASS_KEY_BUDGET`] data keys in total,
	/// so a prefix larger than that is finished over several ticks rather than
	/// monopolising the schedule this task shares. That budget is divided among
	/// the entries a batch still has to visit, floored at one page each: an
	/// entry naming an oversized prefix takes a page and yields to the next
	/// instead of spending the whole pass on itself, so each of the first
	/// `RECLAIM_PASS_KEY_BUDGET / RECLAIM_BATCH_SIZE` entries that still hold
	/// data makes progress on every pass.
	///
	/// Snapshot safety: a queued removal is only reclaimed once it has been
	/// *observed* by this task for at least `grace`. The reclaim task destroys
	/// data out-of-band, and on a backend offering out-of-transaction range
	/// destruction that destruction bypasses MVCC, so a read transaction whose
	/// snapshot predates the `REMOVE` must be given time to finish first. On
	/// first sight the task stamps the entry's
	/// [`ReclaimState::observed_ms`]; aging is measured from there, not from the
	/// key's `uid` (a UUIDv7 stamped while the `REMOVE` statement runs, which can
	/// be arbitrarily earlier than the commit inside a long `BEGIN`/`COMMIT`
	/// block). Because the task only ever reads committed entries, `observed_ms`
	/// is always at or after the removal's commit, so `age >= grace` implies the
	/// commit is at least `grace` old — equivalent to it having fallen behind the
	/// MVCC GC safepoint (`now - tikv_gc_lifetime`) when `grace >= tikv_gc_lifetime`,
	/// by which point any transaction that could still read the data has expired.
	/// A `grace` of zero reclaims immediately without stamping (used by tests and
	/// the language-test harness teardown, where there are no concurrent readers).
	///
	/// Returns `(iterations, errors)`.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(dbs, canceller))]
	pub async fn reclaim_tombstones(
		dbs: Arc<Datastore>,
		interval: Duration,
		grace: Duration,
		canceller: CancellationToken,
	) -> Result<(usize, usize)> {
		Self::reclaim_tombstones_bounded(dbs, interval, grace, RECLAIM_PASS_KEY_BUDGET, canceller)
			.await
	}

	/// [`Self::reclaim_tombstones`] with the per-pass key budget lowered, so a
	/// test can drive a pass that stops mid-prefix and inspect what it left
	/// behind.
	#[cfg(test)]
	#[cfg_attr(
		not(any(feature = "kv-mem", feature = "kv-rocksdb", feature = "kv-surrealkv")),
		allow(dead_code)
	)]
	pub(crate) async fn reclaim_tombstones_with_budget(
		dbs: Arc<Datastore>,
		interval: Duration,
		grace: Duration,
		budget: u64,
		canceller: CancellationToken,
	) -> Result<(usize, usize)> {
		Self::reclaim_tombstones_bounded(dbs, interval, grace, budget, canceller).await
	}

	/// One reclaim pass, deleting at most `budget` data keys in total.
	///
	/// The pass walks the whole queue and spends its key budget on part of it,
	/// which are two different bounds and are enforced separately.
	///
	/// The walk is unconditional. Stamping an entry's first sighting and ageing it
	/// against the grace costs at most one write per entry, so that work scales
	/// with the number of pending removals — catalog scale — and not with the data
	/// they name. Gating it on the key budget would leave an entry beyond the
	/// budget's reach unstamped, and an unstamped entry has `observed_ms == 0`, so
	/// its grace has not started and it is not yet even a candidate for reclaim.
	/// The queue is walked in bounded batches, each batch's stamps committed in one
	/// transaction, so the walk's memory and write batches stay proportional to one
	/// batch however long the queue is.
	///
	/// The key budget is then spent on the [`RECLAIM_PASS_ENTRY_QUOTA`]
	/// longest-observed eligible entries, selected while walking so only that many
	/// are ever held. Oldest-first rather than queue order: key order makes the
	/// entries that happen to sort lowest the only ones ever served while they hold
	/// data, whereas the wait an operator cares about is how long a removal has
	/// gone unreclaimed. Spreading the budget across every eligible entry instead
	/// would shrink each share towards one key as the queue grows.
	async fn reclaim_tombstones_bounded(
		dbs: Arc<Datastore>,
		interval: Duration,
		grace: Duration,
		budget: u64,
		canceller: CancellationToken,
	) -> Result<(usize, usize)> {
		trace!(target: TARGET, "Attempting tombstone reclaim process");
		// Data keys this pass may still delete, shared out across the entries it
		// serves. Spent to zero ends the spend with every cursor committed.
		let mut budget = budget;
		// Coordinate across the cluster so only one node reclaims at a time.
		let lh = LeaseHandler::new_with_canceller(
			dbs.sequences.clone(),
			dbs.id,
			dbs.transaction_factory.clone(),
			TaskLeaseType::ReclaimTombstones,
			interval * 2,
			canceller.clone(),
		)?;
		let mut count_iteration = 0;
		let mut count_error = 0;
		// The queue range and a window within it, advanced past each batch the
		// walk reads. Reading the queue in bounded batches is what keeps both the
		// snapshot the pass holds and the write transaction that updates it
		// proportional to one batch rather than to the number of pending removals.
		let queue = ReclaimPrefix {}.range()?;
		let mut window = queue.clone();
		// The longest-observed eligible entries seen so far, at most
		// `RECLAIM_PASS_ENTRY_QUOTA` of them. A max-heap ordered oldest-first, so
		// the entry discarded when the quota is exceeded is the newest held.
		let mut candidates: BinaryHeap<ReclaimCandidate> = BinaryHeap::new();
		// Whether the walk finished holding the lease. Losing it mid-walk ends the
		// pass: the deletes below would otherwise run against a prefix the node
		// that holds the lease now is already working on.
		let mut lease_held = true;
		// Walk the queue: stamp, age, and select. No deletes, so no budget.
		loop {
			Self::ensure_not_cancelled(&canceller)?;
			// If we don't hold the lease, another node is handling this task.
			if !lh.has_lease().await? {
				lease_held = false;
				break;
			}
			Self::ensure_not_cancelled(&canceller)?;
			// Read one bounded batch of queue entries in a short-lived read
			// transaction, to avoid holding a write lock across the entire
			// reclaim cycle. Values are read as bytes so that an entry this node
			// cannot decode is skipped with a warning rather than failing the
			// whole pass.
			let items = {
				let txn = dbs.transaction(Read).await?;
				let res = txn.scan_raw(window.clone(), RECLAIM_BATCH_SIZE, 0, None).await;
				let _ = txn.cancel().await;
				res?
			};
			Self::ensure_not_cancelled(&canceller)?;
			let Some((last, _)) = items.last().cloned() else {
				// The window has run off the end of the queue: everything queued
				// has been walked.
				break;
			};
			count_iteration += 1;
			// Current wall-clock time (unix millis), used to age each entry
			// against `grace` and to stamp first observations.
			let now_ms = web_time::SystemTime::now()
				.duration_since(web_time::SystemTime::UNIX_EPOCH)
				.map(|d| d.as_millis() as u64)
				.unwrap_or(0);
			let grace_ms = grace.as_millis() as u64;
			// Queue states to initialise or repair. The raw value read with each
			// one is the compare-and-set guard, so a concurrent cursor advance or
			// cancellation cannot be overwritten by this batch.
			let mut to_stamp: Vec<(Vec<u8>, Vec<u8>, ReclaimState)> = Vec::new();
			for (k, v) in items.iter() {
				Self::ensure_not_cancelled(&canceller)?;
				if let Err(e) = ReclaimKey::decode_key(k) {
					count_error += 1;
					warn!(target: TARGET, "Failed to decode reclaim queue entry: {e}");
					continue;
				}
				// The state carries both the observation stamp the grace is
				// measured from and the resume cursor a partly-reclaimed prefix
				// continues at, so it is read before either is consulted.
				// A value this node cannot read still names a prefix whose catalog
				// entry is committed-removed, so the entry is restarted rather than
				// skipped: skipping it strands data that nothing else can reach,
				// because the queue entry is the only remaining name for it.
				// Restarting is safe in both fields — treating the entry as never
				// observed keeps the grace gate conservative, and discarding an
				// unreadable cursor only re-scans pages that may already be empty,
				// which a delete tolerates.
				let state = match ReclaimState::kv_decode_value(v, ()) {
					Ok(s) => s,
					Err(e) => {
						count_error += 1;
						warn!(
							target: TARGET,
							"Restarting a reclaim queue entry whose state could not be read: {e}",
						);
						// Repair the unreadable state conditionally before attempting
						// the reclaim. A typed cursor CAS cannot use unreadable bytes as
						// its expected value, and a blind repair could resurrect a claim
						// concurrently cancelled on another node.
						let repaired = ReclaimState {
							observed_ms: if grace.is_zero() {
								0
							} else {
								now_ms
							},
							cursor: None,
						};
						to_stamp.push((k.clone(), v.clone(), repaired.clone()));
						// Zero-grace callers may reclaim immediately after the
						// conditional repair commits. If that repair loses a race, the
						// page's own CAS sees that `repaired` is not current and stops.
						if grace.is_zero() {
							candidates.push(ReclaimCandidate {
								observed_ms: repaired.observed_ms,
								key: k.clone(),
								state: repaired,
							});
							if candidates.len() > RECLAIM_BATCH_SIZE as usize {
								candidates.pop();
							}
						}
						continue;
					}
				};
				// A zero grace reclaims immediately, skipping the
				// observe-then-age dance (tests / harness teardown — no
				// concurrent readers).
				if !grace.is_zero() {
					if state.observed_ms == 0 {
						// First sighting of this committed entry — record an
						// observation time (>= commit) and defer reclaim. Aging
						// is measured from here, never from the pre-commit
						// `uid`. Not a candidate this pass: its grace starts now.
						to_stamp.push((
							k.clone(),
							v.clone(),
							ReclaimState {
								observed_ms: now_ms,
								cursor: state.cursor.clone(),
							},
						));
						continue;
					}
					// Snapshot-safety gate: only destroy data once it has been
					// observed for at least `grace`, by which point any
					// transaction that could still read it is behind the MVCC
					// GC safepoint.
					if now_ms.saturating_sub(state.observed_ms) < grace_ms {
						continue;
					}
				}
				candidates.push(ReclaimCandidate {
					observed_ms: state.observed_ms,
					key: k.clone(),
					state,
				});
				if candidates.len() > RECLAIM_BATCH_SIZE as usize {
					// The newest held entry gives up its place: it has waited
					// least, so it loses to every other candidate. Held up to one
					// batch rather than up to the share divisor, because an entry
					// whose reclaim spends nothing — an already-empty prefix, or a
					// backend that drops the range in one call — costs no budget,
					// and the spend below walks through as many of those as it
					// finds. Capping the set at the divisor would stop that at the
					// divisor and throttle the backends where reclaim is cheapest.
					// One batch of candidates is the memory the pass already holds
					// for one batch of scanned entries.
					candidates.pop();
				}
			}
			// Persist this batch's stamps in one write transaction, bounded by the
			// batch as the paged data delete is bounded by the page. Done
			// separately from the read scan so we don't conflict with concurrent
			// enqueues.
			if !to_stamp.is_empty() {
				let txn = dbs.transaction(Write).await?;
				if let Err(e) = Self::ensure_not_cancelled(&canceller) {
					let _ = txn.cancel().await;
					return Err(e);
				}
				let mut condition_failed = false;
				for (k, expected, state) in &to_stamp {
					let value = match state.kv_encode_value() {
						Ok(value) => value,
						Err(e) => {
							let _ = txn.cancel().await;
							return Err(e);
						}
					};
					match txn.put_compare(Key::from(k.clone()), value, Some(expected.clone())).await
					{
						Ok(()) => {}
						Err(e) if super::is_conditional_write_conflict(&e) => {
							condition_failed = true;
							break;
						}
						Err(e) => {
							warn!(target: TARGET, "Failed to stamp reclaim queue entry: {e}");
						}
					}
				}
				if condition_failed {
					let _ = txn.cancel().await;
				} else {
					// A stamp that does not land leaves the entry unobserved, so the
					// next pass starts its grace instead. Counted rather than silent:
					// an uncounted failure here reports as a healthy pass while the
					// entry's clock never starts.
					if let Err(e) = txn.commit().await {
						let _ = txn.cancel().await;
						if !super::is_conditional_write_conflict(&e) {
							count_error += 1;
							warn!(target: TARGET, "Failed to commit reclaim queue stamps: {e}");
							return Ok((count_iteration, count_error));
						}
					}
				}
			}
			// Seek past the batch just walked; the window advancing is also what
			// terminates the walk, at the end of the queue.
			window = queue.clone().resume_after(&last, Direction::Forward);
		}
		if !lease_held {
			return Ok((count_iteration, count_error));
		}
		// Spend the key budget on the selected entries, longest-observed first.
		// `into_sorted_vec` is ascending in the candidate order, which is the
		// oldest observation first and the queue's key order between entries
		// observed in the same millisecond.
		let selected = candidates.into_sorted_vec();
		// Entries whose prefix this pass emptied, to delete from the queue. An
		// entry the pass only partly emptied is left queued for a later pass.
		let mut done: Vec<Vec<u8>> = Vec::with_capacity(selected.len());
		// How many of the selected entries are still to spend from the budget, so
		// each takes its slice of what is left rather than all of it.
		let mut remaining = selected.len() as u64;
		for candidate in selected {
			Self::ensure_not_cancelled(&canceller)?;
			// Stop at the entry the lease was lost on. The queue update below
			// still commits what this pass emptied, and whichever node holds
			// the lease now continues from the durable cursors. The answer has
			// to be read rather than discarded: a lease check is throttled to
			// one datastore read per maintenance period, so a call that drops
			// it consumes the read the page loop's own check depends on and
			// leaves that check answering affirmatively without asking.
			if !lh.try_maintain_lease().await? {
				break;
			}
			let ReclaimCandidate {
				key,
				state,
				..
			} = candidate;
			// Decoded during the walk that selected it, so this cannot fail; a
			// failure is still counted rather than panicking on it.
			let rc = match ReclaimKey::decode_key(&key) {
				Ok(rc) => rc,
				Err(e) => {
					count_error += 1;
					warn!(target: TARGET, "Failed to decode reclaim queue entry: {e}");
					remaining = remaining.saturating_sub(1);
					continue;
				}
			};
			// Keys this entry may delete before the pass moves on: its share of
			// what the budget has left, across the entries still to spend from
			// it, capped at the budget so the tail of a pass hands out only what
			// remains. An entry naming a prefix larger than its share therefore
			// cannot take the whole budget and leave its siblings untouched.
			// Floored at one key rather than one page: a share below a page
			// still deletes, since the page size caps a transaction rather than
			// setting a minimum.
			// The divisor is the entries still to spend, capped at the quota: a
			// pass holding a batch of candidates would otherwise cut every share
			// to a thousandth of the budget, so no entry would delete a useful
			// amount. Capped, each served entry gets about a page and the pass
			// stops when the budget runs out — which is what makes the
			// oldest-first order above decide who is served.
			let divisor = remaining.min(RECLAIM_PASS_ENTRY_QUOTA as u64);
			let share = (budget / divisor.max(1)).max(1).min(budget);
			remaining = remaining.saturating_sub(1);
			let mut left = share;
			// Whether the lease passed to another node mid-entry. Recorded
			// rather than broken on directly, so the budget below is charged
			// for the pages this entry did commit before the pass ends.
			let mut lease_lost = false;
			match dbs.reclaim_decoded(&rc, &state, &lh, &canceller, &mut left).await {
				// The prefix is empty, so the entry has nothing left to
				// name and can be retired.
				Ok(ReclaimOutcome::Complete) => done.push(key),
				// Progress is durable but keys remain: leaving the entry
				// queued is what lets a later pass resume it.
				Ok(ReclaimOutcome::Incomplete) => {}
				// The entry is already gone, so it must not be added to
				// `done`: that would delete whatever a concurrent writer
				// put at the same key.
				Ok(ReclaimOutcome::Cancelled) => {}
				// Whichever node holds the lease now resumes from the
				// cursors this pass committed.
				Ok(ReclaimOutcome::LeaseLost) => lease_lost = true,
				// Shutdown. Not a failure of this entry, so it is neither
				// counted nor logged; the queue update below refuses to
				// commit and the pass ends there.
				Err(e)
					if matches!(
						crate::err::engine_error(&e),
						Some(EngineError::QueryCancelled)
					) =>
				{
					break;
				}
				Err(e) => {
					count_error += 1;
					warn!(target: TARGET, "Tombstone reclaim failed for a queue entry: {e}");
				}
			}
			// Charge what the entry deleted, not what it was offered.
			budget = budget.saturating_sub(share.saturating_sub(left));
			if lease_lost {
				// The queue update below still commits what this pass
				// emptied; the node holding the lease now takes the rest.
				break;
			}
			if budget == 0 {
				// The pass has spent its key budget. Every cursor it
				// advanced is committed, so the next tick continues from
				// there rather than repeating this work.
				break;
			}
		}
		// Retire the entries this pass emptied, in one write transaction bounded
		// by the entry quota.
		if !done.is_empty() {
			let txn = dbs.transaction(Write).await?;
			if let Err(e) = Self::ensure_not_cancelled(&canceller) {
				let _ = txn.cancel().await;
				return Err(e);
			}
			// Retire only the value currently stored. This prevents a stale
			// completion from deleting a state advanced by another node, and
			// makes a concurrent cancellation win cleanly on TiKV.
			let mut condition_failed = false;
			for k in &done {
				let current = match txn.get(Key::from(k), None).await {
					Ok(Some(current)) => current,
					Ok(None) => continue,
					Err(e) => {
						warn!(target: TARGET, "Failed to read reclaim queue entry: {e}");
						continue;
					}
				};
				match txn.del_compare(Key::from(k), Some(&current)).await {
					Ok(()) => {}
					Err(e) if super::is_conditional_write_conflict(&e) => {
						condition_failed = true;
						break;
					}
					Err(e) => {
						warn!(target: TARGET, "Failed to delete reclaim queue entry: {e}");
					}
				}
			}
			if condition_failed {
				let _ = txn.cancel().await;
				return Ok((count_iteration, count_error));
			}
			// A pass whose queue update does not land has reclaimed data
			// without recording that it did, so it is counted: an uncounted
			// failure here reports as a healthy pass and leaves nothing for an
			// operator to see but the next tick repeating the same work.
			if let Err(e) = txn.commit().await {
				let _ = txn.cancel().await;
				if !super::is_conditional_write_conflict(&e) {
					count_error += 1;
					warn!(target: TARGET, "Failed to commit reclaim queue update: {e}");
				}
			}
		}
		Ok((count_iteration, count_error))
	}

	/// Whether the table a queue entry names still has a consumer of the
	/// shared doc-ID space: a doc-ID index, or the `graph_doc_ids` marker a
	/// numeric graph fold records (its blocks resolve through the space). A
	/// table with no definition has no consumer — its whole keyspace is
	/// reclaimed separately.
	async fn tb_has_doc_id_consumer(&self, rc: &ReclaimKey<'_>) -> Result<bool> {
		let txn = self.transaction(Read).await?;
		let res = async {
			let Some(tb) = txn.get_tb(rc.ns, rc.db, rc.tb.as_ref(), None).await? else {
				return Ok(false);
			};
			if tb.graph_doc_ids {
				return Ok(true);
			}
			let ixs = txn.all_tb_indexes(rc.ns, rc.db, rc.tb.as_ref(), None).await?;
			Ok(ixs.iter().any(|ix| ix.uses_shared_doc_ids()))
		}
		.await;
		let _ = txn.cancel().await;
		res
	}

	/// Destroy the data prefix a decoded reclaim queue entry names.
	///
	/// Resolves the entry's kind to the byte range beneath it and hands that
	/// range to [`Self::reclaim_range`]. All of these kinds name a subtree holding
	/// keys of more than one type, so the range is resolved as bytes.
	async fn reclaim_decoded(
		&self,
		rc: &ReclaimKey<'_>,
		state: &ReclaimState,
		lh: &LeaseHandler,
		canceller: &CancellationToken,
		budget: &mut u64,
	) -> Result<ReclaimOutcome> {
		let prefix = match rc.kind {
			ReclaimKind::Namespace => NsRoot {
				ns: rc.ns,
			}
			.raw_range()?,
			ReclaimKind::Database => DbRoot {
				ns: rc.ns,
				db: rc.db,
			}
			.raw_range()?,
			ReclaimKind::Index => IdxRoot {
				ns: rc.ns,
				db: rc.db,
				tb: Cow::Borrowed(rc.tb.as_ref()),
				ix: rc.ix,
			}
			.raw_range()?,
			// The bands of a table's shared doc-ID space, each its own entry so
			// each carries its own resume cursor. `rc.ix` is unused for these:
			// the space belongs to the table, not to any one index.
			//
			// The space is only orphaned while the table has no doc-ID consumer.
			// A consumer present here means one was defined after the entry was
			// queued without cancelling it — a node too old to know these kinds,
			// or too old to know the `graph_doc_ids` marker, is the case that
			// matters — so the reclaim obligation has lapsed and the entry is
			// retired with whatever the space still holds left in place.
			// Deleting from it would strip mappings the live consumer resolves
			// its entries through.
			//
			// The consumer check is resolved once, ahead of the prefix arms
			// below, because it opens a read transaction and scans the table's
			// index list.
			// Matched through the same predicate that keeps these kinds off the
			// out-of-transaction destroy, so the two cannot disagree about which
			// kinds hold a revocable claim.
			kind if kind.is_doc_id() && self.tb_has_doc_id_consumer(rc).await? => {
				// A cursor means this entry had already deleted part of the
				// space, so what the consumer adopted is torn: a `!di` mapping
				// whose `!dd` twin is gone resolves to no record. Nothing here
				// can repair it — the keys are already deleted, and the reaper
				// must not delete further from a space a live index is reading —
				// so the tear is reported for an operator to rebuild the table's
				// doc-ID indexes.
				if state.cursor.is_some() {
					warn!(
						target: TARGET,
						"A doc-ID index was defined over a partly-reclaimed doc-ID space \
						 ({}:{}:{}): the space is torn and the table's doc-ID indexes \
						 need rebuilding",
						rc.ns,
						rc.db,
						rc.tb.as_ref(),
					);
				}
				return Ok(ReclaimOutcome::Complete);
			}
			ReclaimKind::DocKey => {
				DocKeyPrefix::new(rc.ns, rc.db, Cow::Borrowed(rc.tb.as_ref())).raw_range()?
			}
			ReclaimKind::DocLookup => {
				DocLookupPrefix::new(rc.ns, rc.db, Cow::Borrowed(rc.tb.as_ref())).raw_range()?
			}
			ReclaimKind::DocLookupIdentity => {
				DocLookupIdentityPrefix::new(rc.ns, rc.db, Cow::Borrowed(rc.tb.as_ref()))
					.raw_range()?
			}
			ReclaimKind::DocPending => {
				DocPendingPrefix::new(rc.ns, rc.db, Cow::Borrowed(rc.tb.as_ref())).raw_range()?
			}
		};
		self.reclaim_range(rc, state, prefix, lh, canceller, budget).await
	}

	/// Destroy every key beneath `prefix`, resuming from the queue entry's
	/// committed cursor and stopping once `budget` keys have gone.
	///
	/// `budget` is this entry's allowance out of the pass's, and is decremented by
	/// what the entry actually deletes. Returning [`ReclaimOutcome::Incomplete`]
	/// with it spent leaves a durable cursor for the next turn this entry gets.
	///
	/// A backend offering [`DestroyRange`] empties the whole prefix in one
	/// out-of-transaction call, and the pass is complete. Every other backend
	/// pages the delete: each round opens one write transaction, scans a bounded
	/// page of keys, deletes exactly those keys, writes the resume cursor, and
	/// commits. Memory is therefore O(page) whatever the prefix's cardinality.
	///
	/// The cursor and the page of deletions it accounts for commit in the same
	/// transaction, so every key at or before the cursor is durably gone and
	/// progress is monotonic: a restart, a lost lease or an exhausted budget
	/// resumes at the cursor instead of rescanning the prefix. Resuming is also
	/// what keeps each scan off the delete tombstones the retired pages left
	/// behind. [`ReclaimState::observed_ms`] is carried through every cursor
	/// write unchanged — the grace gate measures from the first observation, and
	/// restamping here would let a prefix too large for one pass reset its own
	/// grace and never age past it.
	///
	/// Giving up single-transaction atomicity is sound because the catalog entry
	/// naming this prefix is already committed-removed: a partly-destroyed
	/// prefix is unreachable garbage, not partial state any reader can observe.
	///
	/// Idempotent: a re-run on an already-empty prefix scans one empty page and
	/// reports [`ReclaimOutcome::Complete`].
	async fn reclaim_range(
		&self,
		rc: &ReclaimKey<'_>,
		state: &ReclaimState,
		prefix: RawRange,
		lh: &LeaseHandler,
		canceller: &CancellationToken,
		budget: &mut u64,
	) -> Result<ReclaimOutcome> {
		// A backend that can drop the range outside a transaction destroys
		// every version in it in one call, so it needs neither pages nor a
		// cursor and ignores `expunge` — the catalog entry is already gone, so
		// there is nothing to retain. A failure here is propagated rather than
		// retried through the paged path: the entry stays queued and the next
		// pass tries again, so a transient storage failure is never mistaken
		// for an absent capability.
		//
		// Not taken for a table's shared doc-ID prefixes, whose claim is
		// revocable: `DEFINE INDEX` cancels the reclaim to keep the mappings the
		// space still holds. An out-of-transaction destroy neither joins that
		// transaction's conflict domain nor re-reads the claim, so it would go on
		// to delete mappings the new index has already adopted, leaving entries
		// pointing at doc-IDs that resolve to no record. The paged path re-reads
		// the claim inside every page's transaction, which is what lets the
		// cancellation stop it; its cursor is also what tells the next
		// `DEFINE INDEX` that the space was left torn.
		if !rc.kind.is_doc_id()
			&& let Some(ops) = self.destroy_range_ops()
		{
			trace!(
				target: TARGET,
				mechanism = ops.mechanism(),
				"Destroying a reclaimed prefix out-of-transaction",
			);
			ops.destroy_range(prefix.into_key_range()).await?;
			return Ok(ReclaimOutcome::Complete);
		}
		// Resume past the last key whose deletion is durable, but only where the
		// cursor names a key this prefix covers. A cursor at or past the prefix's
		// end would leave an empty window, which the delete cannot tell from a
		// drained prefix: it would report the entry complete, retire the only
		// remaining name for the data, and strand whatever the prefix still holds.
		// Restarting from the head instead re-scans pages that may already be
		// empty, which a delete tolerates.
		let resumable = state
			.cursor
			.as_deref()
			.is_some_and(|c| c >= prefix.start().as_slice() && c < prefix.end().as_slice());
		let window = match &state.cursor {
			Some(cursor) if resumable => prefix.resume_after(cursor, Direction::Forward),
			Some(_) => {
				warn!(
					target: TARGET,
					"Restarting a reclaim from the head of its prefix: the resume cursor \
					 names a key outside it",
				);
				prefix
			}
			None => prefix,
		};
		let outcome = PagedDelete {
			window,
			companion: PageCompanion::ReclaimEntry {
				rc,
				state: state.clone(),
			},
			expunge: rc.expunge == Expunge::Expunge,
			page: RECLAIM_BATCH_SIZE,
		}
		.run(self, lh, canceller, budget)
		.await?;
		Ok(match outcome {
			PagedOutcome::Complete => ReclaimOutcome::Complete,
			PagedOutcome::Incomplete => ReclaimOutcome::Incomplete,
			PagedOutcome::Cancelled => ReclaimOutcome::Cancelled,
			PagedOutcome::LeaseLost => ReclaimOutcome::LeaseLost,
		})
	}

	#[cfg(not(target_family = "wasm"))]
	async fn await_index_compaction_handle(
		ikb: &IndexKeyBase,
		handle: &mut tokio::task::JoinHandle<Result<()>>,
		canceller: &CancellationToken,
	) {
		match handle.await {
			Ok(Ok(())) => {}
			Ok(Err(e))
				if canceller.is_cancelled()
					&& matches!(
						crate::err::engine_error(&e),
						Some(EngineError::QueryCancelled)
					) => {}
			Ok(Err(e)) => {
				warn!("Index compaction {ikb} fails while awaiting cancellation: {e}");
			}
			Err(e) => {
				warn!("Index compaction {ikb} join fails while awaiting cancellation: {e}");
			}
		}
	}

	#[cfg(not(target_family = "wasm"))]
	async fn await_index_compaction_handles(
		handles: &mut Vec<(IndexKeyBase, tokio::task::JoinHandle<Result<()>>)>,
		canceller: &CancellationToken,
	) {
		while let Some((ikb, mut handle)) = handles.pop() {
			Self::await_index_compaction_handle(&ikb, &mut handle, canceller).await;
		}
	}

	/// Compacts each distinct index referenced by the given queue keys.
	///
	/// Folds queued graph adjacency scopes into packed blocks.
	///
	/// Modeled on [`Self::index_compaction`]: leased so one node drains the
	/// queue at a time, a rotating window so a hot table cannot starve
	/// later-sorting ones, bounded read batches, and queue cleanup in
	/// separate bounded write transactions. Before the leased drain, this
	/// node's read-path observations are flushed into the durable queue —
	/// they are held in memory because a read cannot write a queue entry.
	///
	/// The pass runs regardless of `graph_fold_threshold`: a zero threshold
	/// disables new read-path observations (fold initiation), never debt
	/// repayment — edge deletes on already-folded tables keep writing
	/// tombstones and queueing durable triggers whatever the threshold, and
	/// leaving those queued would grow the queue and the per-read tombstone
	/// subtraction without bound.
	pub async fn graph_fold(
		dbs: Arc<Datastore>,
		interval: Duration,
		canceller: CancellationToken,
	) -> Result<(usize, usize)> {
		trace!(target: TARGET, "Attempting graph fold process");
		Self::flush_graph_fold_observations(&dbs).await?;
		let lh = LeaseHandler::new_with_canceller(
			dbs.sequences.clone(),
			dbs.id,
			dbs.transaction_factory.clone(),
			TaskLeaseType::GraphFold,
			interval * 2,
			canceller.clone(),
		)?;
		let batch = dbs.config.idx.graph_fold_batch;
		let mut count_iteration = 0;
		let mut count_error = 0;
		let queue = GraphFoldPrefix {}.range()?;
		let mut window = queue.clone();
		// Whether the sweep since the last window wrap deleted a queue entry
		// or folded a scope. A wrap-around re-scan retries entries retained
		// by failed folds; without progress between two wraps every remaining
		// entry has just failed again, so the call yields to the next
		// interval instead of hot-looping on a poison scope.
		let mut progressed = false;
		'fold: loop {
			Self::ensure_not_cancelled(&canceller)?;
			// Without the lease, another node is draining the queue.
			if !lh.has_lease().await? {
				break 'fold;
			}
			Self::ensure_not_cancelled(&canceller)?;
			trace!(target: TARGET, "Running graph fold process");
			// One bounded, keys-only batch of queue entries per iteration,
			// in a short-lived read transaction.
			let keys = {
				let txn = dbs.transaction(Read).await?;
				let res =
					txn.keys(window.clone(), INDEX_COMPACTION_QUEUE_BATCH_SIZE, 0, None).await;
				let _ = txn.cancel().await;
				res?
			};
			Self::ensure_not_cancelled(&canceller)?;
			if keys.is_empty() {
				if window.start() == queue.start() || !progressed {
					// Nothing left anywhere in the queue, or everything left
					// belongs to scopes that failed this sweep.
					break 'fold;
				}
				// End of the range: wrap to re-scan entries skipped when the
				// window seeked past a partially-drained scope, or retained
				// when a scope's fold failed.
				progressed = false;
				window = queue.clone();
				continue;
			}
			count_iteration += 1;
			// The distinct scopes this batch names, in queue order, and each
			// entry's scope for the cleanup below. Entries that fail to
			// decode name nothing foldable; the cleanup removes them.
			let mut scopes: Vec<GraphFoldScope> = Vec::new();
			let mut seen: HashSet<GraphFoldScope> = HashSet::new();
			let mut key_scopes: Vec<Option<GraphFoldScope>> = Vec::with_capacity(keys.len());
			for key in &keys {
				match GraphFoldKey::decode_key(key) {
					Ok(key) => {
						let scope = GraphFoldScope {
							ns: key.ns,
							db: key.db,
							tb: key.tb.into_owned(),
							id: key.id.into_owned(),
							dir: key.dir,
						};
						if seen.insert(scope.clone()) {
							scopes.push(scope.clone());
						}
						key_scopes.push(Some(scope));
					}
					Err(e) => {
						warn!(target: TARGET, "Skipping undecodable graph fold queue entry: {e}");
						key_scopes.push(None);
					}
				}
			}
			// The scopes whose drain completed; only their queue entries are
			// deleted below. A failed scope keeps its entries, so its fold
			// debt survives for the wrap-around re-scan and later calls.
			let mut folded: HashSet<GraphFoldScope> = HashSet::with_capacity(scopes.len());
			for scope in scopes {
				match Self::fold_queued_scope(&dbs, &scope, batch, &canceller).await {
					Ok(()) => {
						folded.insert(scope);
					}
					Err(e) => {
						if canceller.is_cancelled() {
							return Err(e);
						}
						count_error += 1;
						warn!(target: TARGET, "Graph fold failed for a queued scope: {e}");
					}
				}
			}
			// Seek the next batch past the last scope's run of queue entries,
			// so a scope that keeps re-enqueueing cannot pin the window.
			if let Some(last_key) = keys.last() {
				window = match GraphFoldKey::decode_key(last_key) {
					Ok(last) => {
						let covered = GraphFoldDirPrefix {
							ns: last.ns,
							db: last.db,
							tb: Cow::Owned(last.tb.into_owned()),
							id: Cow::Owned(last.id.into_owned()),
							dir: last.dir,
						}
						.skip_extensions()?;
						queue.clone().resume_after(&covered, Direction::Forward)
					}
					Err(_) => queue.clone().resume_after(last_key, Direction::Forward),
				};
			}
			// Delete this batch's consumed queue entries in a separate bounded
			// write transaction: entries whose scope folded, and undecodable
			// entries — which can never be folded — deleted as bytes so they
			// do not park at the head of the queue forever.
			let deletable: Vec<&Vec<u8>> = keys
				.iter()
				.zip(&key_scopes)
				.filter(|(_, scope)| scope.as_ref().is_none_or(|s| folded.contains(s)))
				.map(|(k, _)| k)
				.collect();
			if deletable.is_empty() {
				continue;
			}
			progressed = true;
			loop {
				let txn = dbs.transaction(Write).await?;
				if let Err(e) = Self::ensure_not_cancelled(&canceller) {
					let _ = txn.cancel().await;
					return Err(e);
				}
				for k in &deletable {
					if let Err(e) = txn.del(Key::from(k.as_slice())).await {
						warn!(target: TARGET, "Failed to delete graph fold queue entry: {e}");
					}
				}
				if let Err(e) = txn.commit().await {
					if Self::cancel_and_retry_index_operation_conflict(
						&txn,
						&e,
						"Retryable conflict committing graph fold queue cleanup, retrying",
					)
					.await
					{
						continue;
					}
					warn!(target: TARGET, "Failed to commit graph fold queue cleanup: {e}");
					break 'fold;
				}
				break;
			}
		}
		Ok((count_iteration, count_error))
	}

	/// Writes this node's read-path fold observations into the durable
	/// queue: blind puts of per-observation keys, so nothing contends.
	async fn flush_graph_fold_observations(dbs: &Arc<Datastore>) -> Result<()> {
		let observations = dbs.triggers.drain_graph_fold_observations();
		if observations.is_empty() {
			return Ok(());
		}
		let txn = dbs.transaction(Write).await?;
		for scope in &observations {
			let key = GraphFoldKey {
				ns: scope.ns,
				db: scope.db,
				tb: Cow::Borrowed(&scope.tb),
				id: Cow::Borrowed(&scope.id),
				dir: scope.dir,
				nid: dbs.id,
				uid: Uuid::now_v7(),
			};
			if let Err(e) = txn.put_key(&key, &()).await {
				let _ = txn.cancel().await;
				return Err(e);
			}
		}
		txn.commit().await
	}

	/// Drains one queued scope: bounded fold passes, each in its own
	/// transaction, retrying a bounded number of times when a concurrent
	/// edge write conflicts with a pass.
	async fn fold_queued_scope(
		dbs: &Arc<Datastore>,
		scope: &GraphFoldScope,
		batch: usize,
		canceller: &CancellationToken,
	) -> Result<()> {
		// The catalog write that marks the vertex table folded addresses the
		// namespace and database by name. A namespace or database dropped
		// since the entry was queued leaves nothing to fold.
		let (ns_name, db_name) = {
			let txn = dbs.transaction(Read).await?;
			let ns = txn
				.all_ns(None)
				.await?
				.iter()
				.find(|n| n.namespace_id == scope.ns)
				.map(|n| n.name.to_string());
			let db = txn
				.all_db(scope.ns, None)
				.await?
				.iter()
				.find(|d| d.database_id == scope.db)
				.map(|d| d.name.to_string());
			let _ = txn.cancel().await;
			match (ns, db) {
				(Some(ns), Some(db)) => (ns, db),
				_ => return Ok(()),
			}
		};
		let vertex = crate::val::RecordId::new(scope.tb.clone(), scope.id.clone());
		let mut retries = 0;
		loop {
			Self::ensure_not_cancelled(canceller)?;
			let txn = Arc::new(dbs.transaction(Write).await?);
			// The environment the fold's doc-ID assignment reads: the
			// production `IndexEnv` is the query context, built the same way
			// the index-compaction processors build theirs.
			let mut env = dbs.setup_ctx()?;
			env.set_transaction(Arc::clone(&txn));
			let env = env.freeze();
			let outcome = match crate::idx::adjacency::fold_scope(
				&env, scope.ns, scope.db, &ns_name, &db_name, &vertex, scope.dir, batch,
			)
			.await
			{
				Ok(outcome) => outcome,
				Err(e) => {
					let _ = txn.cancel().await;
					return Err(e);
				}
			};
			match txn.commit().await {
				Ok(()) => {
					retries = 0;
					if !outcome.has_more {
						return Ok(());
					}
				}
				Err(e) => {
					// A concurrent RELATE or DELETE on the scope beat this
					// pass; take a fresh snapshot and try again, bounded so a
					// write-hot vertex cannot spin the task.
					if surrealdb_datastore::is_retryable_transaction_conflict(&e) && retries < 5 {
						retries += 1;
						continue;
					}
					return Err(e);
				}
			}
		}
	}

	/// On native targets, compaction tasks are spawned in parallel — one per
	/// distinct index — and joined afterwards. Duplicate queue entries for
	/// the same index are deduplicated via a [`HashMap`] so only one task is
	/// spawned per index. Failures are logged but do not abort the loop.
	///
	/// Returns the number of indexes that failed to compact.
	#[cfg(not(target_family = "wasm"))]
	async fn index_compaction_loop(
		dbs: Arc<Datastore>,
		lh: &LeaseHandler,
		keys: &[Vec<u8>],
		canceller: CancellationToken,
	) -> Result<usize> {
		let mut compacted_indexes = HashMap::new();
		for k in keys {
			Self::ensure_not_cancelled(&canceller)?;
			lh.try_maintain_lease().await?;
			// An undecodable entry names no index to compact; skip it here
			// and let the batch cleanup delete it, so one corrupt key cannot
			// wedge every future compaction cycle.
			let ic = match IndexCompactionKey::decode_key(k) {
				Ok(ic) => ic,
				Err(e) => {
					warn!(target: TARGET, "Skipping undecodable index compaction queue entry: {e}");
					continue;
				}
			};
			let ikb = IndexKeyBase::new(ic.ns, ic.db, ic.tb.as_ref().clone(), ic.ix);
			if let Entry::Vacant(e) = compacted_indexes.entry(ikb) {
				e.insert(());
			}
		}
		let mut error_count = 0;
		let mut handles: Vec<(IndexKeyBase, tokio::task::JoinHandle<Result<()>>)> =
			Vec::with_capacity(compacted_indexes.len());
		for (ikb, _) in compacted_indexes {
			if let Err(e) = Self::ensure_not_cancelled(&canceller) {
				Self::await_index_compaction_handles(&mut handles, &canceller).await;
				return Err(e);
			}
			let dbs = Arc::clone(&dbs);
			let canceller = canceller.clone();
			let task_ikb = ikb.clone();
			let jh = spawn(async move { dbs.process_index_compaction(&task_ikb, canceller).await });
			handles.push((ikb, jh));
		}
		while let Some((ikb, mut jh)) = handles.pop() {
			let res = tokio::select! {
				biased;
				_ = canceller.cancelled() => {
					Self::await_index_compaction_handle(&ikb, &mut jh, &canceller).await;
					Self::await_index_compaction_handles(&mut handles, &canceller).await;
					bail!(EngineError::QueryCancelled);
				}
				res = &mut jh => res?,
			};
			if let Err(e) = res {
				if canceller.is_cancelled() {
					Self::await_index_compaction_handles(&mut handles, &canceller).await;
					return Err(e);
				}
				error_count += 1;
				warn!("Index compaction {ikb} fails: {e}");
			}
		}
		Ok(error_count)
	}

	/// Compacts each distinct index referenced by the given queue keys.
	///
	/// On wasm, `tokio::spawn` is unavailable so compactions run
	/// sequentially. A [`HashSet`] is used to skip duplicate queue entries
	/// for the same index. Failures are logged but do not abort the loop,
	/// matching the non-wasm behavior so that a single transient failure
	/// does not prevent other indexes from being compacted.
	///
	/// Returns the number of indexes that failed to compact.
	#[cfg(target_family = "wasm")]
	async fn index_compaction_loop(
		dbs: Arc<Datastore>,
		lh: &LeaseHandler,
		keys: &[Vec<u8>],
		canceller: CancellationToken,
	) -> Result<usize> {
		let mut seen = HashSet::new();
		let mut error_count = 0;
		for k in keys {
			Self::ensure_not_cancelled(&canceller)?;
			lh.try_maintain_lease().await?;
			// An undecodable entry names no index to compact; skip it here
			// and let the batch cleanup delete it, so one corrupt key cannot
			// wedge every future compaction cycle.
			let ic = match IndexCompactionKey::decode_key(k) {
				Ok(ic) => ic,
				Err(e) => {
					warn!(target: TARGET, "Skipping undecodable index compaction queue entry: {e}");
					continue;
				}
			};
			let ikb = IndexKeyBase::new(ic.ns, ic.db, ic.tb.as_ref().clone(), ic.ix);
			if !seen.insert(ikb.clone()) {
				continue;
			}
			let res: Result<()> =
				async { dbs.process_index_compaction(&ikb, canceller.clone()).await }.await;
			if let Err(e) = res {
				if canceller.is_cancelled() {
					return Err(e);
				}
				error_count += 1;
				warn!("Index compaction {ikb} fails: {e}");
			}
		}
		Ok(error_count)
	}

	/// Performs the actual compaction of a single index.
	///
	/// Looks up the index definition identified by `ikb` and dispatches to
	/// the appropriate compaction implementation based on the index type:
	/// full-text, count, HNSW, or DiskANN. Indexes that are being removed
	/// (`prepare_remove`), not found, or of an unsupported type are silently
	/// skipped with a trace log.
	async fn process_index_compaction(
		&self,
		ikb: &IndexKeyBase,
		canceller: CancellationToken,
	) -> Result<()> {
		Self::ensure_not_cancelled(&canceller)?;
		// The catalog definition and the index's durable build state, read
		// together so the ownership decision below costs no extra transaction.
		let (ix, build_owner_live) = {
			let txn = self.transaction(Read).await?;
			let res = async {
				let ix = txn
					.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
					.await?;
				let live = build_owner_is_live(&txn, ikb).await?;
				Ok::<_, anyhow::Error>((ix, live))
			}
			.await;
			let _ = txn.cancel().await;
			res?
		};
		Self::ensure_not_cancelled(&canceller)?;
		match ix {
			Some(ix) if !ix.prepare_remove => {
				// A vector index whose build is still in flight is left to that
				// build's own drain, because only the drain knows which on-disk
				// layout to compact into. A `REBUILD INDEX` that migrates
				// `format_version` holds the new definition in its uncommitted
				// statement transaction, so the catalog read above still reports the
				// retired one. Compacting from here would fold the pendings into the
				// retired layout and leave the published index without them; and
				// because the process-local vector-index wrapper is keyed without the
				// format version, the two compactors would also evict each other's
				// graph on every access.
				//
				// Durable state is the whole test, on every node including the one
				// running the build. It is committed before the builder is
				// registered locally and held until the statement that publishes
				// the definition closes its transaction, so it already covers every
				// window in which this catalog read can be stale. A process-local
				// check would only add the tail between that release and the
				// builder task's exit, where the build has finished publishing and
				// skipping would discard the request that release just queued.
				//
				// The queue entry that led here is dropped with the rest of its
				// batch, and for these two kinds that loses nothing: their builders
				// drain the index's pendings before returning, so the entry is
				// already redundant. Full-text and count builders have no such drain,
				// which is why the test is scoped to the kinds that do rather than
				// applied to every index — dropping one of their requests would leave
				// deltas uncompacted until the next write to the index.
				let drains_own_pendings = match &ix.index {
					Index::Hnsw(_) => true,
					#[cfg(diskann)]
					Index::DiskAnn(_) => true,
					_ => false,
				};
				if drains_own_pendings && build_owner_live {
					trace!(target: TARGET, "Index compaction: Index {ikb:?} is being built, leaving it to its builder");
					return Ok(());
				}
				match &ix.index {
					Index::FullText(p) => {
						self.process_fulltext_compaction(ikb, p, &canceller).await?;
					}
					Index::Count(_) => {
						self.process_count_compaction(ikb, &canceller).await?;
					}
					Index::Hnsw(_) => {
						// HNSW compaction owns its pending-key allocation and pending-range
						// drain semantics separately from full-text/count compaction.
						self.process_hnsw_compaction(ikb, ix.format_version, &canceller).await?;
					}
					#[cfg(diskann)]
					Index::DiskAnn(_) => {
						self.process_diskann_compaction(ikb, &canceller).await?;
					}
					_ => {
						trace!(target: TARGET, "Index compaction: Index {:?} does not support compaction, skipping", ikb);
					}
				}
			}
			_ => {
				trace!(target: TARGET, "Index compaction: Index {:?} not found, skipping", ikb);
			}
		}
		Ok(())
	}

	/// Discards the process-local HNSW wrapper and element caches for one index
	/// after a compaction write that reached the graph and did not commit.
	///
	/// Neither half of that state can be validated against the store. The
	/// element caches carry no version at all. A graph layer carries one, but
	/// it is a counter each writer advances in its own copy as it applies, so
	/// two writers applying the same batch from the same version reach the same
	/// one: the rolled-back topology is then indistinguishable to a state check
	/// from the topology the winning commit stored, and a later apply would
	/// write node changes derived from it over the winner's nodes. An apply
	/// that failed part-way is worse still — it can mutate a layer before
	/// reaching the `save_nodes` that advances the version at all.
	///
	/// The next access rebuilds the wrapper and reloads every layer from
	/// persisted state, which is the cost this pays. A write that stopped at
	/// the compaction guards never reached the graph and must not come here.
	async fn discard_hnsw_index(
		&self,
		tb: crate::catalog::TableId,
		ikb: &IndexKeyBase,
		format_version: u16,
	) {
		if let Err(e) = self.index_stores.remove_hnsw_index(tb, ikb.clone(), format_version).await {
			warn!(target: TARGET, "Failed to evict HNSW index after an uncommitted compaction write: {e}");
		}
	}

	/// Runs HNSW compaction as bounded read-plan/write-apply batches.
	///
	/// Pending entries are captured in a read transaction and conditionally
	/// deleted in a short write transaction before graph mutation. A write that
	/// reached the graph in place and then did not commit leaves the
	/// process-local wrapper holding a topology and caches the store never
	/// took, so the wrapper is discarded; a write that was staged, or that
	/// stopped at the guards, left the wrapper untouched and keeps it. The
	/// discard targets the format version the write phase applied through — a
	/// `REBUILD INDEX` can bump the catalog format after `format_version` was
	/// captured, and both the wrapper and the cache entries are scoped per
	/// format.
	async fn process_hnsw_compaction(
		&self,
		ikb: &IndexKeyBase,
		format_version: u16,
		canceller: &CancellationToken,
	) -> Result<()> {
		loop {
			Self::ensure_not_cancelled(canceller)?;
			let prepared = {
				let txn = Arc::new(self.transaction(Read).await?);
				let res: Result<
					Option<(
						crate::catalog::TableId,
						crate::idx::trees::hnsw::index::HnswCompactionPlan,
					)>,
				> = async {
					let Some(tb) = txn.get_tb(ikb.ns(), ikb.db(), ikb.table(), None).await? else {
						return Ok(None);
					};
					match txn
						.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
						.await?
					{
						Some(ix) if !ix.prepare_remove && matches!(&ix.index, Index::Hnsw(_)) => {
							let mut ctx = self.setup_ctx()?;
							ctx.set_transaction(Arc::clone(&txn));
							let ctx = ctx.freeze();
							let plan = IndexOperation::prepare_hnsw_compaction(&ctx, ikb).await?;
							Ok(Some((tb.table_id, plan)))
						}
						_ => Ok(None),
					}
				}
				.await;
				let _ = txn.cancel().await;
				res?
			};
			let Some((tb, plan)) = prepared else {
				return Ok(());
			};
			if !plan.has_work() {
				return Ok(());
			}
			let has_more = plan.has_more();
			Self::ensure_not_cancelled(canceller)?;

			let txn = Arc::new(self.transaction(Write).await?);
			// The apply phase re-reads the catalog and mutates the wrapper and
			// cache belonging to that fresh format, so every failure-side
			// recovery below must clear the same format, not the one captured at
			// dispatch time.
			let mut applied_format = format_version;
			let res: Result<HnswCompactionOutcome> = async {
				// Re-tested inside the write transaction, and under a conflict
				// registration. The dispatch-time test was a snapshot in a
				// transaction that has since been cancelled, so a build acquired
				// after it would otherwise be invisible to this apply; the
				// registration makes such an acquisition conflict this commit
				// instead, and the retry re-reads it.
				if build_owner_is_live_locked(&txn, ikb).await? {
					return Ok(HnswCompactionOutcome::Skipped);
				}
				match txn
					.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
					.await?
				{
					Some(ix) if !ix.prepare_remove => match &ix.index {
						Index::Hnsw(p) => {
							applied_format = ix.format_version;
							let mut ctx = self.setup_ctx()?;
							ctx.set_transaction(Arc::clone(&txn));
							let ctx = ctx.freeze();
							IndexOperation::apply_hnsw_compaction(
								&ctx,
								&self.index_stores,
								ikb,
								p,
								ix.format_version,
								plan,
							)
							.await
						}
						_ => Ok(HnswCompactionOutcome::Skipped),
					},
					_ => Ok(HnswCompactionOutcome::Skipped),
				}
			}
			.await;
			match res {
				Ok(outcome) if outcome.applied() => {
					// Only an in-place batch reaches the graph before its commit; a
					// staged one publishes from the commit itself, so a transaction
					// that does not commit leaves its wrapper untouched.
					let in_place = outcome == HnswCompactionOutcome::InPlace;
					if let Err(e) = Self::ensure_not_cancelled(canceller) {
						let _ = txn.cancel().await;
						if in_place {
							self.discard_hnsw_index(tb, ikb, applied_format).await;
						}
						return Err(e);
					}
					#[cfg(test)]
					if let Err(e) = maybe_inject_retryable_conflict(
						RetryableConflictSite::HnswCompaction,
						self.id,
					) {
						let _ = txn.cancel().await;
						if in_place {
							self.discard_hnsw_index(tb, ikb, applied_format).await;
						}
						if Self::retry_index_operation_conflict(
							&e,
							format!(
								"Retryable conflict committing HNSW compaction for {ikb}, retrying"
							),
						)
						.await
						{
							continue;
						}
						return Err(e);
					}
					if let Err(e) = txn.commit().await {
						let _ = txn.cancel().await;
						if in_place {
							self.discard_hnsw_index(tb, ikb, applied_format).await;
						}
						if Self::retry_index_operation_conflict(
							&e,
							format!(
								"Retryable conflict committing HNSW compaction for {ikb}, retrying"
							),
						)
						.await
						{
							continue;
						}
						return Err(e);
					}
				}
				Ok(_) => {
					let _ = txn.cancel().await;
					return Ok(());
				}
				Err(e) => {
					let _ = txn.cancel().await;
					self.discard_hnsw_index(tb, ikb, applied_format).await;
					if Self::retry_index_operation_conflict(
						&e,
						format!("Retryable conflict applying HNSW compaction for {ikb}, retrying"),
					)
					.await
					{
						continue;
					}
					return Err(e);
				}
			}
			Self::ensure_not_cancelled(canceller)?;
			if !has_more {
				return Ok(());
			}
			// Defense-in-depth: every match arm above either commits (Ok(true))
			// or cancels (Ok(false)/Err) the tx, so by here `closed()` should
			// always be true. Catch any future regression where a `?` between
			// the match and this point bypasses finalization. No-op today.
			if !txn.closed() {
				let _ = txn.cancel().await;
			}
		}
	}

	#[cfg(diskann)]
	/// Runs DiskANN compaction as bounded read-plan/write-apply batches.
	async fn process_diskann_compaction(
		&self,
		ikb: &IndexKeyBase,
		canceller: &CancellationToken,
	) -> Result<()> {
		loop {
			Self::ensure_not_cancelled(canceller)?;
			let prepared = {
				let txn = Arc::new(self.transaction(Read).await?);
				let res: Result<
					Option<(
						crate::catalog::TableId,
						crate::idx::trees::diskann::index::DiskAnnCompactionPlan,
					)>,
				> = async {
					let Some(tb) = txn.get_tb(ikb.ns(), ikb.db(), ikb.table(), None).await? else {
						return Ok(None);
					};
					match txn
						.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
						.await?
					{
						Some(ix)
							if !ix.prepare_remove && matches!(&ix.index, Index::DiskAnn(_)) =>
						{
							let mut ctx = self.setup_ctx()?;
							ctx.set_transaction(Arc::clone(&txn));
							let ctx = ctx.freeze();
							let plan =
								IndexOperation::prepare_diskann_compaction(&ctx, ikb).await?;
							Ok(Some((tb.table_id, plan)))
						}
						_ => Ok(None),
					}
				}
				.await;
				let _ = txn.cancel().await;
				res?
			};
			let Some((_tb, plan)) = prepared else {
				return Ok(());
			};
			if !plan.requires_apply() {
				return Ok(());
			}
			let has_more = plan.has_more();
			Self::ensure_not_cancelled(canceller)?;

			let txn = Arc::new(self.transaction(Write).await?);
			let res: Result<bool> = async {
				// See the HNSW counterpart: the dispatch-time ownership test is
				// a cancelled snapshot, so it is re-tested here under a conflict
				// registration that a concurrent build acquisition trips.
				if build_owner_is_live_locked(&txn, ikb).await? {
					return Ok(false);
				}
				match txn
					.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
					.await?
				{
					Some(ix) if !ix.prepare_remove => match &ix.index {
						Index::DiskAnn(p) => {
							let mut ctx = self.setup_ctx()?;
							ctx.set_transaction(Arc::clone(&txn));
							let ctx = ctx.freeze();
							IndexOperation::apply_diskann_compaction(
								&ctx,
								&self.index_stores,
								ikb,
								p,
								ix.format_version,
								plan,
							)
							.await
						}
						_ => Ok(false),
					},
					_ => Ok(false),
				}
			}
			.await;
			// `apply_diskann_compaction` normally owns the transaction's
			// lifecycle (commits on success, cancels on apply failure while
			// holding the graph write lock — closing the #7318 race). A few
			// pre-apply paths inside `IndexOperation::apply_diskann_compaction`
			// (missing table or catalog lookup errors) can return without
			// finalizing the tx, so we add an idempotent safety net here:
			// cancel only if the tx is still open. Cancel on an already-closed
			// tx returns `TransactionFinished` and is harmlessly discarded.
			if !txn.closed() {
				let _ = txn.cancel().await;
			}
			match res {
				Ok(true) => {}
				Ok(false) => return Ok(()),
				Err(e) => return Err(e),
			}
			Self::ensure_not_cancelled(canceller)?;
			if !has_more {
				return Ok(());
			}
		}
	}

	/// Runs full-text compaction as a read-plan followed by a guarded write.
	///
	/// This avoids holding a mutable range scan over `!dc`/`!tt`; deltas
	/// committed after the read snapshot remain for a later compaction.
	async fn process_fulltext_compaction(
		&self,
		ikb: &IndexKeyBase,
		p: &crate::catalog::FullTextParams,
		canceller: &CancellationToken,
	) -> Result<()> {
		loop {
			Self::ensure_not_cancelled(canceller)?;
			let plan = {
				let txn = self.transaction(Read).await?;
				let ix = txn
					.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
					.await?
					.filter(|ix| !ix.prepare_remove);
				let res = IndexOperation::prepare_fulltext_compaction(
					&self.index_stores,
					ikb,
					&txn,
					p,
					&self.config.idx.file_allowlist,
					match &ix {
						Some(ix) if matches!(ix.index, crate::catalog::Index::FullText(_)) => {
							ix.format_version
						}
						_ => return Ok(()),
					},
				)
				.await;
				let _ = txn.cancel().await;
				res?
			};
			if !plan.has_work() {
				return Ok(());
			}
			let has_more = plan.has_more();
			Self::ensure_not_cancelled(canceller)?;

			let txn = self.transaction(Write).await?;
			let res = async {
				match txn
					.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
					.await?
				{
					Some(ix) if !ix.prepare_remove => match &ix.index {
						Index::FullText(p) => {
							IndexOperation::apply_fulltext_compaction(
								&self.index_stores,
								ikb,
								&txn,
								p,
								&self.config.idx.file_allowlist,
								ix.format_version,
								plan,
							)
							.await
						}
						_ => Ok(false),
					},
					_ => Ok(false),
				}
			}
			.await;
			match res {
				Ok(true) => {
					if let Err(e) = Self::ensure_not_cancelled(canceller) {
						let _ = txn.cancel().await;
						return Err(e);
					}
					#[cfg(test)]
					if let Err(e) = maybe_inject_retryable_conflict(
						RetryableConflictSite::FullTextCompaction,
						self.id,
					) {
						if Self::cancel_and_retry_index_operation_conflict(
							&txn,
							&e,
							format!(
								"Retryable conflict committing full-text compaction for {ikb}, retrying"
							),
						)
						.await
						{
							continue;
						}
						return Err(e);
					}
					if let Err(e) = txn.commit().await {
						if Self::cancel_and_retry_index_operation_conflict(
							&txn,
							&e,
							format!(
								"Retryable conflict committing full-text compaction for {ikb}, retrying"
							),
						)
						.await
						{
							continue;
						}
						return Err(e);
					}
				}
				Ok(false) => {
					let _ = txn.cancel().await;
					return Ok(());
				}
				Err(e) => {
					let _ = txn.cancel().await;
					if Self::retry_index_operation_conflict(
						&e,
						format!(
							"Retryable conflict applying full-text compaction for {ikb}, retrying"
						),
					)
					.await
					{
						continue;
					}
					return Err(e);
				}
			}
			Self::ensure_not_cancelled(canceller)?;
			if !has_more {
				return Ok(());
			}
			// Defense-in-depth: every match arm above either commits (Ok(true))
			// or cancels (Ok(false)/Err) the tx, so by here `closed()` should
			// always be true. Catch any future regression where a `?` between
			// the match and this point bypasses finalization. No-op today.
			if !txn.closed() {
				let _ = txn.cancel().await;
			}
		}
	}

	/// Runs count-index compaction as a read-plan followed by a guarded write.
	///
	/// The write phase deletes only keys captured in the plan, so concurrent
	/// `!iu` deltas are preserved and included by later reads/compactions.
	async fn process_count_compaction(
		&self,
		ikb: &IndexKeyBase,
		canceller: &CancellationToken,
	) -> Result<()> {
		loop {
			Self::ensure_not_cancelled(canceller)?;
			let plan = {
				let txn = self.transaction(Read).await?;
				let res = IndexOperation::prepare_count_compaction(ikb, &txn).await;
				let _ = txn.cancel().await;
				res?
			};
			if !plan.has_work() {
				return Ok(());
			}
			let has_more = plan.has_more();
			Self::ensure_not_cancelled(canceller)?;

			let txn = self.transaction(Write).await?;
			let res = async {
				match txn
					.get_tb_index_by_id(ikb.ns(), ikb.db(), ikb.table(), ikb.index(), None)
					.await?
				{
					Some(ix) if !ix.prepare_remove && matches!(&ix.index, Index::Count(_)) => {
						IndexOperation::apply_count_compaction(ikb, &txn, plan).await
					}
					_ => Ok(false),
				}
			}
			.await;
			match res {
				Ok(true) => {
					if let Err(e) = Self::ensure_not_cancelled(canceller) {
						let _ = txn.cancel().await;
						return Err(e);
					}
					#[cfg(test)]
					if let Err(e) = maybe_inject_retryable_conflict(
						RetryableConflictSite::CountCompaction,
						self.id,
					) {
						if Self::cancel_and_retry_index_operation_conflict(
							&txn,
							&e,
							format!(
								"Retryable conflict committing count compaction for {ikb}, retrying"
							),
						)
						.await
						{
							continue;
						}
						return Err(e);
					}
					if let Err(e) = txn.commit().await {
						if Self::cancel_and_retry_index_operation_conflict(
							&txn,
							&e,
							format!(
								"Retryable conflict committing count compaction for {ikb}, retrying"
							),
						)
						.await
						{
							continue;
						}
						return Err(e);
					}
				}
				Ok(false) => {
					let _ = txn.cancel().await;
					return Ok(());
				}
				Err(e) => {
					let _ = txn.cancel().await;
					if Self::retry_index_operation_conflict(
						&e,
						format!("Retryable conflict applying count compaction for {ikb}, retrying"),
					)
					.await
					{
						continue;
					}
					return Err(e);
				}
			}
			Self::ensure_not_cancelled(canceller)?;
			if !has_more {
				return Ok(());
			}
		}
	}

	/// Process queued async events using a distributed lease to coordinate batches.
	/// Once a batch starts it runs to completion even if the lease expires, so
	/// brief overlap is possible.
	///
	/// Returns as soon as `canceller` is tripped, at the next batch boundary. The
	/// events themselves are user-defined SurrealQL that nothing here bounds, so
	/// this bounds the wait to one batch rather than to the whole queue — which
	/// is what stops a busy queue from holding [`Self::shutdown`] open for as
	/// long as writes keep arriving.
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self, canceller))]
	pub(crate) async fn event_processing(
		&self,
		interval: Duration,
		canceller: &CancellationToken,
	) -> Result<()> {
		// Output function invocation details to logs
		trace!(target: TARGET, "Attempting event processing process");
		// Create a new lease handler
		let lh = LeaseHandler::new(
			self.sequences.clone(),
			self.id,
			self.transaction_factory.clone(),
			TaskLeaseType::EventProcessing,
			interval * 2,
		)?;
		// We continue while there are keys, the lease, and no cancellation
		loop {
			// Stop between batches once shutdown starts. Cancellation is not a
			// failure: the queue is durable, so whatever is left is processed by
			// the next pass on this node or another.
			if canceller.is_cancelled() {
				return Ok(());
			}
			// Attempt to acquire a lease for the EventProcessing task
			// If we don't get the lease, another node is handling this task
			if !lh.has_lease().await? {
				return Ok(());
			}
			// Output function invocation details to logs
			trace!(target: TARGET, "Running event processing process");
			if process_next_events_batch(self, Some(&lh)).await? == 0 {
				// The last batch didn't have any events to process,
				// we can sleep until the next wake-up call
				return Ok(());
			}
		}
	}

	// --------------------------------------------------
	// Other functions
	// --------------------------------------------------

	/// Create a new transaction on this datastore
	///
	/// ```rust,no_run
	/// use surrealdb_core::kvs::{Datastore, TransactionType::*};
	/// use anyhow::Error;
	///
	/// #[tokio::main]
	/// async fn main() -> Result<(),Error> {
	///     let ds = Datastore::new("rocksdb://database.db").await?;
	///     let mut tx = ds.transaction(Write).await?;
	///     tx.cancel().await?;
	///     Ok(())
	/// }
	/// ```
	pub async fn transaction(&self, write: TransactionType) -> Result<Transaction> {
		self.transaction_factory.transaction(write, self.sequences.clone()).await
	}

	pub(crate) fn sequences(&self) -> &Sequences {
		&self.sequences
	}

	pub(crate) fn transaction_factory(&self) -> &TransactionFactory {
		&self.transaction_factory
	}

	#[cfg(test)]
	#[cfg_attr(not(feature = "kv-mem"), allow(dead_code))]
	pub(crate) fn index_builder(&self) -> &IndexBuilder {
		&self.index_builder
	}
	/// The post-commit wake-ups the background tasks wait on.
	pub fn commit_triggers(&self) -> &Arc<CommitTriggers> {
		&self.triggers
	}

	/// The live-query engine this datastore delivers notifications through.
	///
	/// Selected from the datastore configuration at construction and fixed for
	/// the datastore's lifetime. The engine's background tasks read it to decide
	/// whether to run the per-node live-query router at all: under
	/// [`LiveQueryEngine::Inline`] the router has nothing to deliver, so no task
	/// is spawned for it.
	pub fn live_query_engine(&self) -> LiveQueryEngine {
		self.config.datastore.live_query_engine
	}

	pub async fn health_check(&self) -> Result<()> {
		let tx = self.transaction(Read).await?;

		// Cancel the transaction
		trace!("Cancelling health check transaction");
		// Read a declared key rather than a probe byte: whether it is present says
		// nothing here, only that the store answered.
		match tx.get_key(&VersionKey {}, None).await {
			Err(err) => {
				// Ensure the transaction is cancelled
				let _ = tx.cancel().await;
				// Return an error for this endpoint
				Err(err)
			}
			Ok(_) => {
				// Ensure the transaction is cancelled
				let _ = tx.cancel().await;
				// Return success for this endpoint
				Ok(())
			}
		}
	}

	/// Returns how long ago the current node last refreshed its cluster
	/// heartbeat, or `None` when this node has no cluster membership row.
	///
	/// The node-membership refresh background task rewrites this node's
	/// heartbeat to the KV store every `node_membership_refresh_interval`. A
	/// small age therefore confirms, from work the node already performs, that
	/// the refresh task is running and that both the storage write path (the
	/// heartbeat was recently committed) and read path (it is readable here in
	/// a fresh transaction) are healthy. Readiness probes use this instead of a
	/// dedicated health check to avoid duplicating that work.
	///
	/// An absent row is `None` rather than an error, because it is an ordinary
	/// state of a live node and not a failure to read: `insert_node` writes the
	/// row during startup, a peer that archives this node deletes it again, and
	/// either way the next refresh tick writes it back. A caller can therefore
	/// tell "no heartbeat yet" from "storage did not answer", which only `Err`
	/// reports. `/ready` depends on the distinction.
	pub async fn node_heartbeat_age(&self) -> Result<Option<Duration>> {
		// Open a fresh read transaction so the lookup misses the per-transaction
		// cache and actually reads the node key from storage.
		let tx = self.transaction(Read).await?;
		let res = tx.get_node(self.id).await;
		// Always release the transaction, regardless of the lookup result.
		let _ = tx.cancel().await;
		let Some(node) = res? else {
			return Ok(None);
		};
		// Heartbeats are stored as milliseconds since the epoch; saturate to
		// avoid underflow from minor clock skew between writes and this read.
		let now = self.clock_now();
		Ok(Some(Duration::from_millis(now.value.saturating_sub(node.heartbeat.value))))
	}

	/// Run a query.
	///
	/// Every buffered query entry point that takes a whole query is this one:
	/// a [`QueryRequest`] describes what to run, who runs it, and the
	/// conditions — a caller-owned transaction, bound variables, a
	/// cancellation handle — independently of one another, so the
	/// combinations do not need a method each. Import is the exception: it
	/// consumes a byte stream and keeps its own preflight, whose session
	/// errors differ from this one's.
	///
	/// The source is split into statements before the session preflight, so a
	/// caller that submitted unparsable text learns that from the call
	/// whatever else is wrong with the request. SurrealQL statements stay in
	/// surface form; see [`Self::statements_for`].
	///
	/// See [`Self::run_streaming`] to receive results as they are produced
	/// rather than all at once.
	///
	/// ```rust,no_run
	/// use anyhow::Error;
	/// use surrealdb_core::kvs::{Datastore, QueryRequest};
	/// use surrealdb_core::dbs::Session;
	///
	/// #[tokio::main]
	/// async fn main() -> Result<(),Error> {
	///     let ds = Datastore::new("memory").await?;
	///     let ses = Session::owner();
	///     let sql = "USE NS test DB test; SELECT * FROM person;";
	///     let res = ds.run(QueryRequest::new(sql, &ses)).await?;
	///     Ok(())
	/// }
	/// ```
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn run(
		&self,
		req: QueryRequest<'_>,
	) -> std::result::Result<Vec<QueryResult>, TypesError> {
		let QueryRequest {
			source,
			session,
			variables,
			transaction,
			cancel,
		} = req;
		let statements = self.statements_for(source)?;
		let (opt, ctx) = self.setup_query(session, variables, transaction.as_ref(), cancel)?;
		match transaction {
			Some(_) => {
				Executor::execute_statements_with_transaction(self, ctx, opt, statements).await
			}
			None => Executor::execute_statements(self, ctx, opt, statements).await,
		}
		// `anyhow_to_types_error`, not a downcast to `err::Error`: that enum
		// holds a handful of residual variants, so a bare layer error
		// (`ExecError::DbEmpty` from `Options::ns_db()`, say) misses and
		// reaches the client as `internal` where it used to be a validation
		// failure. The helper walks the whole registry.
		.map_err(crate::err::anyhow_to_types_error)
	}

	/// Prepare a query to stream its results.
	///
	/// Where [`Self::run`] answers with every statement's result at once, this
	/// sends [`QueryStreamItem`]s into `items` as the executor produces them,
	/// so a caller can forward rows before the query finishes. See the
	/// [`stream`](crate::dbs::QueryStreamItem) module for what a consumer may
	/// assume about them — chiefly that rows are provisional until their
	/// statement's terminal item arrives.
	///
	/// Parsing and the session checks happen here, so their failures are
	/// reported instead of a job. Everything after that is reported by driving
	/// [`QueryStreamJob::run`].
	///
	/// A streaming caller wants [`QueryRequest::cancel`]: a consumer that stops
	/// reading is only noticed at the next send otherwise, so a query in a
	/// phase that emits nothing for a while — a sort, an aggregate — would run
	/// to completion after the client had gone.
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub fn run_streaming(
		self: &Arc<Self>,
		req: QueryRequest<'_>,
		items: Sender<QueryStreamItem>,
	) -> std::result::Result<QueryStreamJob, TypesError> {
		let QueryRequest {
			source,
			session,
			variables,
			transaction,
			cancel,
		} = req;
		let statements = self.statements_for(source)?;
		let (opt, ctx) = self.setup_query(session, variables, transaction.as_ref(), cancel)?;
		let in_transaction = transaction.is_some();
		// The count is known now because parsing is done, which is what lets a
		// transport announce it before the first result exists.
		let statement_count = statements.len();
		let kvs = Arc::clone(self);
		Ok(QueryStreamJob {
			statement_count,
			run: Box::pin(async move {
				let executed = if in_transaction {
					Executor::execute_statements_streaming_with_transaction(
						&kvs, ctx, opt, statements, items,
					)
					.await
				} else {
					Executor::execute_statements_streaming(&kvs, ctx, opt, statements, items).await
				};
				executed.map_err(crate::err::anyhow_to_types_error)
			}),
		})
	}

	/// Split a [`QuerySource`] into the statements the executor runs.
	///
	/// Parsed SurrealQL stays in surface form: the executor converts each
	/// statement when it is about to run it, rather than converting the batch
	/// before the first one does. GQL has no SurrealQL surface form — it lowers
	/// straight to a plan — so it arrives at the executor already lowered, as
	/// does a source a caller lowered itself.
	fn statements_for(
		&self,
		source: QuerySource<'_>,
	) -> std::result::Result<Vec<TopLevelStatement>, TypesError> {
		fn lowered(plan: LogicalPlan) -> Vec<TopLevelStatement> {
			plan.expressions.into_iter().map(TopLevelStatement::Plan).collect()
		}

		let ast = match source {
			QuerySource::Text {
				text,
				dialect: Dialect::SurrealQl,
			} => syn::parse_with_capabilities(text, &self.capabilities.load(), &self.parser_config)
				.map_err(|e| TypesError::validation(e.to_string(), None))?,
			QuerySource::Text {
				text,
				dialect: Dialect::Gql,
			} => return Ok(lowered(self.parse_gql(text)?)),
			QuerySource::Ast(ast) => ast,
			QuerySource::Plan(plan) => return Ok(lowered(plan)),
		};
		Ok(ast.expressions.into_iter().map(TopLevelStatement::Ast).collect())
	}

	/// Parse and lower GQL query text to the plan the executor runs.
	///
	/// The plan is returned bare rather than in its `PreparedGqlQuery`
	/// wrapper: that type comes from the `gql` crate, so naming it here would
	/// leave the signature unbuildable on a build without the feature.
	#[cfg(feature = "gql")]
	fn parse_gql(&self, text: &str) -> std::result::Result<LogicalPlan, TypesError> {
		crate::gql::parse_with_capabilities(text, &self.capabilities.load(), &self.parser_config)
			.map(|prepared| prepared.0)
			.map_err(|e| TypesError::validation(e.to_string(), None))
	}

	/// The dialect exists on every build because it is chosen from what a
	/// client sent; the front end that would parse it does not.
	#[cfg(not(feature = "gql"))]
	fn parse_gql(&self, _text: &str) -> std::result::Result<LogicalPlan, TypesError> {
		Err(TypesError::configuration(
			"This build does not support GQL queries".to_string(),
			surrealdb_types::ConfigurationError::DialectNotSupported,
		))
	}

	/// The preflight a query runs: the session checks, and the options and
	/// context the statements execute against.
	///
	/// [`Self::execute_import`] does not come through here. It repeats these
	/// checks inline and reports an expired session and an anonymous actor as
	/// `DatastoreError`/`PolicyError` where this reports `TypesError`, so a
	/// check added here does not reach the import path.
	///
	/// A caller-owned transaction is prepared here rather than by the executor.
	/// It carries the session's tenant identity so the emitted
	/// [`crate::observe::TransactionEvent`] names the active namespace,
	/// database and user; and the write-cardinality guard is armed on it
	/// because statements running inside a client-owned transaction (RPC
	/// `begin`, SDK-managed transactions) are subject to the same configured
	/// limit as executor-created statement transactions — wrapping a statement
	/// in an explicit transaction must not bypass the guard.
	fn setup_query(
		&self,
		sess: &Session,
		vars: Option<PublicVariables>,
		tx: Option<&Arc<Transaction>>,
		cancel: Option<CancelHandle>,
	) -> std::result::Result<(Options, FrozenContext), TypesError> {
		// Check if the session has expired
		if sess.expired() {
			return Err(TypesError::not_allowed(
				"The session has expired".to_string(),
				AuthError::SessionExpired,
			));
		}

		// Check if anonymous actors can execute queries when auth is enabled
		// TODO(sgirones): Check this as part of the authorisation layer
		if let Err(e) = self.check_anon(sess) {
			return Err(TypesError::not_allowed(
				format!("Anonymous access not allowed: {e}"),
				AuthError::NotAllowed {
					actor: "anonymous".to_owned(),
					action: "process".to_owned(),
					resource: "query".to_owned(),
				},
			));
		}

		// Create a new query options
		let opt = self.setup_options(sess);

		// Create a default context.
		//
		// `anyhow_to_types_error`, not a downcast to `err::Error`: that enum
		// holds a handful of residual variants, so a bare layer error
		// (`ExecError::DbEmpty` from `Options::ns_db()`, say) misses and
		// reaches the client as `internal` where it used to be a validation
		// failure. The helper walks the whole registry.
		let mut ctx = self.setup_ctx().map_err(crate::err::anyhow_to_types_error)?;

		// Install the external cancellation handle if one was supplied. The
		// executor checks `Context::done` between statements and in iterator
		// hot loops, so flipping the flag mid-query causes the next yield to
		// return `EngineError::QueryCancelled` and the executor's error path
		// finalises the transaction cleanly. Bare-await sites (`SLEEP`)
		// `select!` against the handle's awaitable view. This is a flag rather
		// than the caller dropping the execution future because dropping the
		// future would drop an open transaction with it.
		if let Some(cancel) = cancel {
			ctx.set_cancellation(&cancel);
		}

		// Start an execution context
		ctx.attach_session(sess).map_err(crate::err::into_types_error)?;

		// Store the query variables
		if let Some(vars) = vars {
			ctx.attach_variables(vars.into()).map_err(crate::err::into_types_error)?;
		}

		// Prepare an externally-supplied transaction. See the method docs for
		// why the identity and the guard are applied here.
		if let Some(tx) = tx {
			if let Some(identity) = ctx.tenant_identity() {
				tx.set_tenant_identity(Arc::clone(identity));
			}
			tx.arm_write_keys_limit(self.transaction_max_write_keys());
			ctx.set_transaction(Arc::clone(tx));
		}

		Ok((opt, ctx.freeze()))
	}

	/// Parse and execute an SQL query
	///
	/// ```rust,no_run
	/// use anyhow::Error;
	/// use surrealdb_core::kvs::Datastore;
	/// use surrealdb_core::dbs::Session;
	///
	/// #[tokio::main]
	/// async fn main() -> Result<(),Error> {
	///     let ds = Datastore::new("memory").await?;
	///     let ses = Session::owner();
	///     let ast = "USE NS test DB test; SELECT * FROM person;";
	///     let res = ds.execute(ast, &ses, None).await?;
	///     Ok(())
	/// }
	/// ```
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn execute(
		&self,
		txt: &str,
		sess: &Session,
		vars: Option<PublicVariables>,
	) -> std::result::Result<Vec<QueryResult>, TypesError> {
		self.run(QueryRequest::new(txt, sess).with_variables(vars)).await
	}

	/// Execute a pre-parsed SQL query
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn process(
		&self,
		ast: Ast,
		sess: &Session,
		vars: Option<PublicVariables>,
	) -> std::result::Result<Vec<QueryResult>, TypesError> {
		self.run(QueryRequest::new(ast, sess).with_variables(vars)).await
	}

	/// The parser settings an import is read under.
	///
	/// An import is this engine's own export read back, so its depth ceiling
	/// is derived from the deepest value the storage layer accepts
	/// ([`MAX_VALUE_DEPTH`]) rather than from the configured query limits:
	/// whatever was legal to write has to be legal to restore, on any node and
	/// under any configuration. A ceiling below that caps a restore short of
	/// what the writer accepts, and the shortfall shows up only as one failed
	/// statement inside an otherwise successful restore.
	///
	/// The grammar gates are derived from the caller's live capabilities:
	/// import text is a fresh statement at the query boundary, not text this
	/// engine previously rendered, so the experimental-syntax gates apply to
	/// it as they do to any other operator-supplied query.
	fn import_parser_settings(capabilities: &Capabilities) -> ParserSettings {
		ParserSettings {
			files_enabled: capabilities.allows_experimental(&ExperimentalTarget::Files),
			surrealism_enabled: capabilities.allows_experimental(&ExperimentalTarget::Surrealism),
			..ParserSettings::for_value_depth(MAX_VALUE_DEPTH)
		}
	}

	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn execute_import<S>(
		&self,
		sess: &Session,
		vars: Option<PublicVariables>,
		query: S,
	) -> Result<Vec<QueryResult>>
	where
		S: Stream<Item = Result<Bytes>>,
	{
		// Check if the session has expired
		ensure!(!sess.expired(), DatastoreError::ExpiredSession);

		// Check if anonymous actors can execute queries when auth is enabled
		// TODO(sgirones): Check this as part of the authorisation layer
		self.check_anon(sess).map_err(|_| {
			Error::from(PolicyError::NotAllowed {
				actor: "anonymous".to_string(),
				action: "process".to_string(),
				resource: "query".to_string(),
			})
		})?;

		// Create a new query options
		let opt = self.setup_options(sess);

		// Create a default context
		let mut ctx = self.setup_ctx()?;
		// Start an execution context
		ctx.attach_session(sess)?;
		// Store the query variables
		if let Some(vars) = vars {
			ctx.attach_variables(vars.into())?;
		}
		// Process all statements

		let parser_settings = Self::import_parser_settings(&ctx.get_capabilities());
		let mut statements_stream = StatementStream::new_with_settings(parser_settings);
		let mut buffer = BytesMut::new();
		let mut parse_size = 4096;
		let mut bytes_stream = pin!(query);
		let mut complete = false;
		let mut filling = true;

		let stream = futures::stream::poll_fn(move |cx| {
			loop {
				// fill the buffer to at least parse_size when filling is required.
				while filling {
					let bytes = ready!(bytes_stream.as_mut().poll_next(cx));
					let bytes = match bytes {
						Some(Err(e)) => return Poll::Ready(Some(Err(e))),
						Some(Ok(x)) => x,
						None => {
							complete = true;
							filling = false;
							break;
						}
					};

					buffer.extend_from_slice(&bytes);
					filling = buffer.len() < parse_size
				}

				// if we finished streaming we can parse with complete so that the parser can be
				// sure of it's results.
				if complete {
					return match statements_stream.parse_complete(&mut buffer) {
						Err(e) => {
							Poll::Ready(Some(Err(anyhow::Error::new(ParseError::InvalidQuery(e)))))
						}
						Ok(None) => Poll::Ready(None),
						Ok(Some(x)) => Poll::Ready(Some(Ok(x))),
					};
				}

				// otherwise try to parse a single statement.
				match statements_stream.parse_partial(&mut buffer) {
					Err(e) => {
						return Poll::Ready(Some(Err(anyhow::Error::new(
							ParseError::InvalidQuery(e),
						))));
					}
					Ok(Some(x)) => return Poll::Ready(Some(Ok(x))),
					Ok(None) => {
						// Couldn't parse a statement for sure.
						if buffer.len() >= parse_size && parse_size < u32::MAX as usize {
							// the buffer already contained more or equal to parse_size bytes
							// this means we are trying to parse a statement of more then buffer
							// size. so we need to increase the buffer size.
							parse_size = (parse_size + 1).next_power_of_two();
						}
						// start filling the buffer again.
						filling = true;
					}
				}
			}
		});

		Executor::execute_stream(self, Arc::new(ctx), opt, true, stream).await
	}

	/// Evaluates a SQL [`Value`] without checking authenticating config
	/// This is used in very specific cases, where we do not need to check
	/// whether authentication is enabled, or guest access is disabled.
	/// For example, this is used when processing a record access SIGNUP or
	/// SIGNIN clause, which still needs to work without guest access.
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub(crate) async fn evaluate(
		&self,
		val: &Expr,
		sess: &Session,
		vars: Option<PublicVariables>,
	) -> Result<PublicValue> {
		// Check if the session has expired
		ensure!(!sess.expired(), DatastoreError::ExpiredSession);
		// Create a new memory stack
		let mut stack = TreeStack::new();
		// Create a new query options
		let opt = self.setup_options(sess);
		// Create a default context
		let mut ctx = self.setup_ctx()?;
		// Set the global query timeout
		if let Some(timeout) = self.dynamic_configuration.get_query_timeout() {
			ctx.add_timeout(timeout)?;
		}

		let txn_type = if val.read_only() {
			TransactionType::Read
		} else {
			TransactionType::Write
		};
		// Start a new transaction. Tenant identity is attached up-front so the
		// emitted [`crate::observe::TransactionEvent`] carries the session's
		// namespace, database, user, etc. The write-cardinality guard is
		// armed like any other statement execution: this path evaluates
		// owner-defined record-access clauses (SIGNUP/SIGNIN/AUTHENTICATE)
		// on behalf of unauthenticated callers, so its fan-out must be
		// subject to the same configured limit.
		let txn = self
			.transaction(txn_type)
			.await?
			.with_tenant_identity(Some(Arc::new(crate::observe::TenantIdentity::from(sess))))
			.with_write_keys_limit(self.transaction_max_write_keys())
			.enclose();
		// Store the transaction
		ctx.set_transaction(Arc::clone(&txn));

		// Start an execution context
		ctx.attach_session(sess)?;
		// Store the query variables
		if let Some(vars) = vars {
			ctx.attach_public_variables(vars)?;
		}

		// Freeze the context
		let ctx = ctx.freeze();
		// Compute the value
		let res = stack
			.enter(|stk| crate::legacy::expr_compute(val, stk, &ctx, &opt, None))
			.finish()
			.await
			.catch_return();
		// Store any data
		if res.is_ok() && txn_type == TransactionType::Write {
			// If the compute was successful, then commit if writeable
			txn.commit().await?;
		} else {
			// Cancel if the compute was an error, or if readonly
			txn.cancel().await?;
		};
		// Return result
		convert_value_to_public_value(res?)
	}

	/// Performs a database import from SQL
	///
	/// The text is parsed under [`Self::import_parser_settings`] rather than
	/// the datastore's configured query limits, so that this entry point and
	/// [`Self::execute_import`] restore the same exports. Everything after
	/// parsing is an ordinary query execution.
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn import(&self, sql: &str, sess: &Session) -> Result<Vec<QueryResult>> {
		// Check if the session has expired
		ensure!(!sess.expired(), DatastoreError::ExpiredSession);
		// Parse the import under the import profile.
		//
		// Classified as the caller's mistake, as `Datastore::execute` classifies
		// the same failure: a truncated or hand-edited dump is a malformed
		// request, and retrying it unchanged cannot succeed. Left to rise as a
		// bare `ParseError` it reaches every transport as an unclassified
		// internal fault, which reads as a server problem worth retrying.
		let ast = syn::parse_with_settings(
			sql.as_bytes(),
			Self::import_parser_settings(&self.capabilities.load()),
			async |parser, stk| parser.parse_query(stk).await,
		)
		.map_err(|e| TypesError::validation(e.to_string(), None))?;
		// Execute the SQL import
		self.process(ast, sess, None).await.map_err(|e| anyhow::anyhow!(e))
	}

	/// Performs a database import from SQL
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn import_stream<S>(&self, sess: &Session, stream: S) -> Result<Vec<QueryResult>>
	where
		S: Stream<Item = Result<Bytes>>,
	{
		// Check if the session has expired
		ensure!(!sess.expired(), DatastoreError::ExpiredSession);
		// Execute the SQL import
		self.execute_import(sess, None, stream).await
	}

	/// Performs a full database export as SQL
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn export(
		&self,
		sess: &Session,
		chn: Sender<Vec<u8>>,
	) -> Result<impl Future<Output = Result<()>>> {
		// Create a default export config
		let cfg = surrealdb_rpc::export::Config::default();
		self.export_with_config(sess, chn, cfg).await
	}

	/// Performs a full database export as SQL
	#[instrument(level = "debug", target = "surrealdb::core::kvs::ds", skip_all)]
	pub async fn export_with_config(
		&self,
		sess: &Session,
		chn: Sender<Vec<u8>>,
		cfg: surrealdb_rpc::export::Config,
	) -> Result<impl Future<Output = Result<()>> + 'static> {
		// Check if the session has expired
		ensure!(!sess.expired(), DatastoreError::ExpiredSession);
		// A dump carries the current state of each record and has no grammar for a
		// record's history, so an export cannot answer a request for versions.
		//
		// Refused here rather than inside the returned job, because a transport that
		// streams the export has already sent a success status and opened the body by
		// the time that job runs: a refusal raised in there reaches the caller as an
		// empty dump that claims to have succeeded. Every caller awaits this function
		// before it awaits the job, so this is the last point common to all of them
		// that still precedes a response.
		//
		// Raised as a structured validation error rather than a bare message, so each
		// transport classifies it as the caller's mistake: the request named an option
		// the format has no representation for, and retrying it unchanged cannot
		// succeed.
		if cfg.versions {
			bail!(TypesError::validation(
				"Versioned export is not supported: a dump carries the current state of each \
				 record only"
					.to_owned(),
				surrealdb_types::ValidationError::InvalidRequest,
			));
		}
		// Retrieve the provided NS and DB
		let (ns, db) = crate::iam::check::check_ns_db(sess)?;
		// Create a new readonly transaction
		let txn = self.transaction(Read).await?;
		let batch_size = self.config.datastore.export_batch_size;
		// Return an async export job
		Ok(async move {
			// Process the export
			let res = super::export::export(&txn, &ns, &db, cfg, batch_size, chn).await;
			txn.cancel().await?;
			res
		})
	}

	/// Checks the required permissions level for this session
	#[instrument(level = "trace", target = "surrealdb::core::kvs::ds", skip(self, sess))]
	#[allow(clippy::needless_pass_by_value)] // Public API: ergonomic for callers passing `ResourceKind::X.on_db(ns, db)` inline.
	pub fn check(&self, sess: &Session, action: Action, resource: Resource) -> Result<()> {
		// Check if the session has expired
		ensure!(!sess.expired(), DatastoreError::ExpiredSession);
		// Skip auth for Anonymous users if auth is disabled
		let skip_auth = !self.is_auth_enabled() && sess.au.is_anon();
		if !skip_auth {
			sess.au.is_allowed(action, &resource).map_err(crate::err::Error::from)?;
		}
		// All ok
		Ok(())
	}

	pub fn setup_options(&self, sess: &Session) -> Options {
		Options::new(&self.config.exec)
			.with_ns(sess.ns())
			.with_db(sess.db())
			.with_auth(Arc::clone(&sess.au))
	}

	pub fn setup_ctx(&self) -> Result<Context> {
		let ctx = Context::from_ds(
			self.id,
			self.auth_enabled,
			self.dynamic_configuration.clone(),
			self.dynamic_configuration.get_query_timeout(),
			self.slow_log.clone(),
			self.capabilities.load_full(),
			self.index_stores.clone(),
			self.index_builder.clone(),
			self.sequences.clone(),
			Arc::clone(&self.cache),
			#[cfg(feature = "http")]
			self.http_client.load_full(),
			#[cfg(storage)]
			self.temporary_directory.clone(),
			self.buckets.clone(),
			Arc::clone(&self.config),
			#[cfg(feature = "surrealism")]
			Arc::clone(&self.surrealism_cache),
		)?;
		Ok(ctx)
	}

	/// check for disallowed anonymous users
	pub fn check_anon(&self, sess: &Session) -> Result<(), PolicyError> {
		if self.auth_enabled && sess.au.is_anon() && !self.capabilities.load().allows_guest_access()
		{
			Err(PolicyError::NotAllowed {
				actor: "anonymous".to_string(),
				action: String::new(),
				resource: String::new(),
			})
		} else {
			Ok(())
		}
	}

	/// SECURITY: `USE NS` implicitly creates the namespace when it does
	/// not exist. `DEFINE NAMESPACE` requires `Edit` on `Namespace`@`Root`,
	/// so the same authorization must gate the materialization step in
	/// `USE`. Returns `true` if the caller may proceed with
	/// `get_or_add_ns` — either because the namespace already exists
	/// (in which case the call is a no-op lookup) or because the caller
	/// has the necessary authorization. Returns `false` when the
	/// namespace does not exist *and* the caller lacks permission;
	/// callers that still want to set the session context for a later
	/// authenticated step (the typical pre-signin RPC `USE` pattern)
	/// can do so without triggering creation. See `SECURITY_GUIDE.md`
	/// section 3.
	pub(crate) async fn should_materialize_ns_on_use(
		&self,
		tx: &Transaction,
		auth: &Auth,
		ns: &str,
	) -> Result<bool> {
		if tx.get_ns_by_name(ns, None).await?.is_some() {
			return Ok(true);
		}
		if !self.auth_enabled && auth.is_anon() {
			return Ok(true);
		}
		Ok(auth.is_allowed(Action::Edit, &ResourceKind::Namespace.on_root()).is_ok())
	}

	/// SECURITY: counterpart to [`Self::should_materialize_ns_on_use`]
	/// for the database half of `USE`. Implicit creation requires the
	/// same authorization as `DEFINE DATABASE` (`Edit` on `Database`@`Ns`),
	/// AND the parent namespace must already exist or the caller must
	/// also be authorized to create it — `ensure_ns_db` is
	/// `get_or_add_db_upwards(..., upwards = true)` and will silently
	/// `get_or_add_ns` the parent when it is missing
	/// (`kvs/tx.rs::get_or_add_db_upwards`). Without the second check a
	/// namespace-level Editor on a stale token (the namespace was
	/// dropped after the token was issued) could recreate the parent
	/// namespace as a side effect of `USE NS dropped DB anything`.
	pub(crate) async fn should_materialize_db_on_use(
		&self,
		tx: &Transaction,
		auth: &Auth,
		ns: &str,
		db: &str,
	) -> Result<bool> {
		if tx.get_db_by_name(ns, db, None).await?.is_some() {
			return Ok(true);
		}
		if !self.auth_enabled && auth.is_anon() {
			return Ok(true);
		}
		// Block the upwards-create side effect: if the parent namespace
		// is missing and the caller can't create namespaces, refuse.
		if tx.get_ns_by_name(ns, None).await?.is_none()
			&& auth.is_allowed(Action::Edit, &ResourceKind::Namespace.on_root()).is_err()
		{
			return Ok(false);
		}
		Ok(auth.is_allowed(Action::Edit, &ResourceKind::Database.on_ns(ns)).is_ok())
	}

	pub async fn process_use(
		&self,
		ctx: Option<&dyn crate::catalog::providers::CancellationProbe>,
		session: &mut Session,
		namespace: Option<String>,
		database: Option<String>,
	) -> std::result::Result<QueryResult, TypesError> {
		let new_tx = || async {
			self.transaction(Write).await.map_err(|err| TypesError::internal(err.to_string()))
		};
		let commit_tx = |txn: Transaction| async move {
			txn.commit().await.map_err(|err| TypesError::internal(err.to_string()))
		};

		let query_result = QueryResultBuilder::started_now();
		// SECURITY: `process_use` may be called before the caller has
		// authenticated (e.g. SDKs that call `use` before `signin`). To
		// preserve that pattern without re-opening the bypass that this
		// guard closes, we set the session context but only commit
		// implicit `DEFINE NAMESPACE` / `DEFINE DATABASE`-equivalent
		// creation when the caller has authorization for it. Callers
		// without permission end up with a session that targets a
		// resource that may not exist; downstream operations surface a
		// clean `NsNotFound` / `DbNotFound` rather than a silently
		// auto-created namespace they should not have been able to
		// create. See `SECURITY_GUIDE.md` section 3.
		let map_internal = |err: anyhow::Error| TypesError::internal(err.to_string());
		// SECURITY (GHSA-2v9j): tenant-boundary gate, mirroring the SurrealQL
		// `USE` statement handler (`dbs::executor`) and the RPC `use` handler
		// (`rpc::protocol::yuse`). This path (`process_use`) serves the embedded
		// SDK `Command::Use` and the PostgreSQL wire; the WS/HTTP/gRPC RPC `use`
		// method carries its own copy of this gate in `yuse`. An authenticated
		// Database-, Namespace- or Record-level principal must be verified as
		// authorized for the target namespace/database before the session is
		// pivoted, or it could switch into a foreign tenant and reach any table
		// there with satisfiable PERMISSIONS. The authenticated Auth level is the
		// source of truth; a switch that changes only one of ns/db keeps the
		// other from the current session. Root and anonymous (`Level::No`, e.g.
		// `use` before `signin`) principals are unrestricted by `can_access_ns_db`,
		// preserving the pre-signin `use` pattern.
		{
			let target_ns = namespace.as_deref().or(session.ns.as_deref());
			let target_db = database.as_deref().or(session.db.as_deref());
			if let Some(ns_name) = target_ns {
				let db_name = target_db.unwrap_or_default();
				if !session.au.can_access_ns_db(ns_name, db_name) {
					let err = if session.au.level().ns() == Some(ns_name) {
						ExecError::DbNotAllowed {
							db: db_name.to_owned(),
						}
					} else {
						ExecError::NsNotAllowed {
							ns: ns_name.to_owned(),
						}
					};
					return Err(TypesError::not_allowed(err.to_string(), None));
				}
			}
		}
		match (namespace, database) {
			(Some(ns), Some(db)) => {
				let tx = new_tx().await?;
				let create_ns = self
					.should_materialize_ns_on_use(&tx, &session.au, &ns)
					.await
					.map_err(map_internal)?;
				let create_db = create_ns
					&& self
						.should_materialize_db_on_use(&tx, &session.au, &ns, &db)
						.await
						.map_err(map_internal)?;
				if create_db {
					tx.ensure_ns_db(ctx, &ns, &db).await.map_err(map_internal)?;
					commit_tx(tx).await?;
				} else if create_ns {
					tx.get_or_add_ns(ctx, &ns).await.map_err(map_internal)?;
					commit_tx(tx).await?;
				} else {
					let _ = tx.cancel().await;
				}
				session.ns = Some(ns);
				session.db = Some(db);
			}
			(Some(ns), None) => {
				let tx = new_tx().await?;
				let create_ns = self
					.should_materialize_ns_on_use(&tx, &session.au, &ns)
					.await
					.map_err(map_internal)?;
				if create_ns {
					tx.get_or_add_ns(ctx, &ns).await.map_err(map_internal)?;
					commit_tx(tx).await?;
				} else {
					let _ = tx.cancel().await;
				}
				session.ns = Some(ns);
			}
			(None, Some(db)) => {
				let Some(ns) = session.ns.clone() else {
					return Err(TypesError::validation(
						"Cannot use database without namespace".to_string(),
						None,
					));
				};
				let tx = new_tx().await?;
				let create_db = self
					.should_materialize_db_on_use(&tx, &session.au, &ns, &db)
					.await
					.map_err(map_internal)?;
				if create_db {
					tx.ensure_ns_db(ctx, &ns, &db).await.map_err(map_internal)?;
					commit_tx(tx).await?;
				} else {
					let _ = tx.cancel().await;
				}
				session.db = Some(db);
			}
			// An empty `USE` asks for the configured default, not for the
			// session to be cleared. A session that has already selected a
			// namespace — from a token, say — keeps it, so this only ever fills
			// in what is missing.
			(None, None) if session.ns.is_none() => {
				let tx = new_tx().await?;
				let default = match tx.get_default_config().await {
					Ok(config) => config.map(|c| (c.namespace.clone(), c.database.clone())),
					Err(e) => {
						let _ = tx.cancel().await;
						return Err(map_internal(e));
					}
				};

				// The default names a namespace and database a fresh datastore
				// may not have materialised yet. Creating them is gated on the
				// same authorization an explicit `DEFINE NAMESPACE` /
				// `DEFINE DATABASE` needs, as the arms above are: a caller
				// without it still gets the selection, and a later operation
				// reports a clean `NsNotFound` rather than silently having
				// created what it could not have defined. See
				// `SECURITY_GUIDE.md` section 3.
				if let Some((Some(ns), db)) = default {
					// SECURITY (GHSA-2v9j): the default names a namespace/database
					// to a scoped principal just as an explicit `USE` would, so gate
					// the resolved default the same way before selecting or creating
					// it. Root and anonymous principals are unrestricted by
					// `can_access_ns_db`; a scoped principal is confined to its own
					// namespace/database. Mirrors the executor's `USE DEFAULT` path.
					if !session.au.can_access_ns_db(&ns, db.as_deref().unwrap_or_default()) {
						let _ = tx.cancel().await;
						let err = if session.au.level().ns() == Some(ns.as_str()) {
							ExecError::DbNotAllowed {
								db: db.clone().unwrap_or_default(),
							}
						} else {
							ExecError::NsNotAllowed {
								ns: ns.clone(),
							}
						};
						return Err(TypesError::not_allowed(err.to_string(), None));
					}
					let create_ns = self
						.should_materialize_ns_on_use(&tx, &session.au, &ns)
						.await
						.map_err(map_internal)?;
					if create_ns && let Err(e) = tx.get_or_add_ns(ctx, &ns).await {
						let _ = tx.cancel().await;
						return Err(map_internal(e));
					}
					if let Some(db) = db {
						let create_db = create_ns
							&& self
								.should_materialize_db_on_use(&tx, &session.au, &ns, &db)
								.await
								.map_err(map_internal)?;
						if create_db && let Err(e) = tx.ensure_ns_db(ctx, &ns, &db).await {
							let _ = tx.cancel().await;
							return Err(map_internal(e));
						}
						session.db = Some(db);
					}
					session.ns = Some(ns);
				}

				commit_tx(tx).await?;
			}
			(None, None) => {}
		}

		let value = PublicValue::from_t(object! {
			namespace: session.ns.clone(),
			database: session.db.clone(),
		});

		Ok(query_result.finish_with_result(Ok(value)))
	}

	/// Get a db model by name.
	///
	/// TODO: This should not be public, but it is used by callers outside the
	/// `surrealdb-core` crate (the SDK's local engine and the server's ML route).
	pub async fn get_db_model(
		&self,
		ns: &str,
		db: &str,
		model_name: &str,
		model_version: &str,
	) -> Result<Option<Arc<crate::catalog::StoredMlModelDefinition>>> {
		let tx = self.transaction(Read).await?;
		let db = tx.expect_db_by_name(ns, db).await?;
		let model = tx
			.get_db_model(db.namespace_id, db.database_id, model_name, model_version, None)
			.await?;
		tx.cancel().await?;
		Ok(model.map(|m| Arc::new(m.to_stored())))
	}

	/// Invoke an API handler.
	///
	/// TODO: This should not need to be public, but it is used by the server's
	/// HTTP API route (outside the `surrealdb-core` crate).
	pub async fn invoke_api_handler(
		&self,
		ns: &str,
		db: &str,
		path: &str,
		session: &Session,
		mut req: ApiRequest,
	) -> Result<ApiResponse> {
		// Enforce the tenant boundary before resolving or dispatching anything.
		// The namespace/database come from caller-controlled input (the
		// `/api/:ns/:db/:endpoint` URL path) and the HTTP route has already
		// overwritten the session's selected ns/db with them, so the
		// authenticated level is the only trustworthy scope. A principal
		// authenticated for one tenant must not be able to invoke another
		// tenant's custom API — whose handler runs with permissions disabled
		// (GHSA-848m-r628-vrxw).
		if !session.au.can_access_ns_db(ns, db) {
			debug!(
				request_id = %req.request_id,
				"Custom API request denied: URL namespace/database is outside the authenticated session scope"
			);
			return Ok(ApiResponse::from_error(ApiError::PermissionDenied, req.request_id.clone()));
		}

		let tx = Arc::new(self.transaction(TransactionType::Write).await?);
		// Custom API handlers evaluate owner-defined expressions on behalf of
		// external callers — statement execution in everything but name — so
		// the write-cardinality guard applies exactly as it does to executor
		// statements and explicit client-owned transactions.
		tx.arm_write_keys_limit(self.transaction_max_write_keys());

		// `tx` is open and writeable from here until the commit/cancel below, so
		// every fallible step in between cancels before returning. A bare `?`
		// would drop the transaction without committing or cancelling it,
		// tripping `Transactor::drop`'s "a transaction was dropped without being
		// committed or cancelled" error and leaving it to be reaped rather than
		// rolled back promptly. `catch!` is the cancel-then-propagate form.
		let db = catch!(tx, tx.ensure_ns_db(None, ns, db).await);

		let segments: Vec<&str> = path.split('/').filter(|x| !x.is_empty()).collect();

		// Routes on the stored definitions and compiles only the one that
		// handles this request: this transaction is opened per request, so the
		// compiled catalog cache is always cold, and compiling the whole list
		// would parse every handler body in the database to dispatch one.
		let routed = catch!(
			tx,
			tx.find_db_api(db.namespace_id, db.database_id, &segments, req.method).await
		);
		let res = match routed {
			Some((api, params)) => {
				let api = &api;
				debug!(
					request_id = %req.request_id,
					path = %path,
					"API definition found, dispatching to process_api_request"
				);
				req.params = catch!(tx, params.try_into());

				let opt = self.setup_options(session);

				let mut ctx = catch!(tx, self.setup_ctx());
				ctx.set_transaction(Arc::clone(&tx));
				// Not `catch!`: like `try_into` above, this error needs
				// converting into the function's error type.
				if let Err(e) = ctx.attach_session(session) {
					let _ = tx.cancel().await;
					return Err(e.into());
				}
				let ctx = &ctx.freeze();

				process_api_request(ctx, &opt, api, req).await
			}
			None => {
				trace!(
					request_id = %req.request_id,
					path = %path,
					"No API definition found for path"
				);
				tx.cancel().await?;
				return Ok(ApiResponse::from_error(ApiError::NotFound, req.request_id.clone()));
			}
		};

		// Handle committing or cancelling the transaction
		if res.is_ok() {
			tx.commit().await?;
		} else {
			tx.cancel().await?;
		}

		res
	}

	pub async fn put_ml_model(
		&self,
		session: &Session,
		name: &str,
		version: &str,
		description: &str,
		data: Vec<u8>,
	) -> Result<()> {
		let ns = session.ns.as_ref().context("Namespace is required")?;
		let db = session.db.as_ref().context("Database is required")?;

		self.check(session, Action::Edit, ResourceKind::Model.on_db(ns, db))?;

		// Calculate the hash of the model file
		let hash = crate::obs::hash(&data);
		// Calculate the path of the model file
		let path = get_model_path(ns, db, name, version, &hash);
		// Insert the file data in to the store
		crate::obs::put(&path, data).await?;
		// Insert the model in to the database
		let model = DefineModelStatement {
			name: name.to_string().into(),
			version: version.to_string().into(),
			comment: Expr::Literal(Literal::String(description.into())),
			hash: hash.into(),
			kind: Default::default(),
			permissions: Default::default(),
		};

		let q = LogicalPlan {
			expressions: vec![TopLevelExpr::Expr(Expr::Define(Box::new(DefineStatement::Model(
				model,
			))))],
		};

		self.run(QueryRequest::new(q, session)).await.map_err(|e| anyhow::anyhow!(e))?;

		Ok(())
	}

	/// The per-layer configuration this datastore was built with. Cheap to
	/// clone; the inner handle is an `Arc`. Crate-internal: these are operator
	/// knobs, not API — callers outside core take the specific settings they
	/// need, as the server does through [`Self::parser_config`].
	pub(crate) fn config(&self) -> Arc<RuntimeConfig> {
		Arc::clone(&self.config)
	}

	/// The parser depth limits this datastore parses query text with.
	///
	/// Transports that decode request bodies (RPC, WebSocket, export) apply the
	/// same limits, so they read them from here rather than from their own
	/// defaults. Cheap to clone; the inner handle is an `Arc`.
	pub fn parser_config(&self) -> Arc<ParserConfig> {
		Arc::clone(&self.parser_config)
	}

	/// Retrieve (or generate and cache) the GraphQL schema for the namespace
	/// and database selected on `session`. Backed by the datastore-wide schema
	/// cache so every transport (HTTP `/graphql`, WebSocket subscriptions, the
	/// `graphql` RPC method, the MCP `graphql` tool) shares one set of compiled
	/// schemas and a single DDL-driven invalidation path.
	#[cfg(all(feature = "graphql", not(target_family = "wasm")))]
	pub async fn graphql_schema(
		self: &Arc<Self>,
		session: &Session,
	) -> Result<async_graphql::dynamic::Schema, crate::graphql::GraphqlError> {
		self.graphql_schema_cache.get_schema(self, session).await
	}

	#[cfg(feature = "http")]
	pub fn http_client(&self) -> Arc<HttpClient> {
		self.http_client.load_full()
	}

	/// Builds a [`NodeEndpointResolver`] backed by this datastore's catalog. Used by the
	/// builder to hand a resolver to clustered message brokers after the datastore is
	/// fully constructed.
	///
	/// Only available on non-WASM targets: the underlying transaction types are not
	/// `Send + Sync` under the WASM single-threaded model, and cross-node delivery
	/// (the only consumer) doesn't apply to in-browser datastores.
	#[cfg(not(target_family = "wasm"))]
	pub(crate) fn endpoint_resolver(&self) -> Arc<dyn crate::dbs::NodeEndpointResolver> {
		Arc::new(CatalogNodeEndpointResolver {
			transaction_factory: self.transaction_factory.clone(),
			sequences: self.sequences.clone(),
		})
	}
}

/// Catalog-backed [`NodeEndpointResolver`] handed to clustered brokers post-construction.
///
/// Holds clones of the transaction factory and sequences (both cheap `Arc`-based clones) so
/// it can open read transactions independently of the [`Datastore`] struct, avoiding any
/// reference cycle between the broker and the datastore.
#[cfg(not(target_family = "wasm"))]
#[derive(Clone)]
struct CatalogNodeEndpointResolver {
	transaction_factory: TransactionFactory,
	sequences: Sequences,
}

#[cfg(not(target_family = "wasm"))]
impl std::fmt::Debug for CatalogNodeEndpointResolver {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("CatalogNodeEndpointResolver").finish_non_exhaustive()
	}
}

#[cfg(not(target_family = "wasm"))]
impl crate::dbs::NodeEndpointResolver for CatalogNodeEndpointResolver {
	fn resolve(
		&self,
		target_node: [u8; 16],
	) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<String>> + Send + '_>> {
		Box::pin(async move {
			let uuid = Uuid::from_bytes(target_node);
			let txn =
				self.transaction_factory.transaction(Read, self.sequences.clone()).await.ok()?;
			let key = NodeKey {
				nd: uuid,
			};
			let node: Option<Node> = txn.get_key(&key, None).await.ok()?;
			let _ = txn.cancel().await;
			node.and_then(|n| n.http_endpoint)
		})
	}
}

pub(crate) fn define_user_statement_new_with_password(
	base: Base,
	user: String,
	pass: &str,
	role: String,
) -> DefineUserStatement {
	DefineUserStatement {
		kind: DefineKind::Default,
		base,
		name: Expr::Idiom(Idiom::field(user)),
		hash: crate::iam::hash_password(pass),
		code: Alphanumeric.sample_string(&mut rand::rng(), 128),
		roles: vec![role],
		duration: UserDuration::default(),
		comment: Expr::Literal(Literal::None),
		scram: Some(ScramCredential::generate(pass)),
	}
}

#[cfg(test)]
mod test {
	use std::collections::BTreeMap;
	use std::future::pending;

	use surrealdb_strand::TableName;

	use super::*;
	use crate::catalog::providers::{
		CatalogProvider, DatabaseProvider, NamespaceProvider, TableProvider,
	};
	use crate::iam::verify::verify_root_creds;
	use crate::key::schema::{DocKeyPrefix, DocLookupPrefix, IndexCountKey, IndexCountPrefix};
	use crate::kvs::test_support::{WriteTxSizeObserver, cleanup_sizes};
	use crate::kvs::testing::{
		NonRetryableErrorSite, RetryableConflictSite, inject_non_retryable_error,
		inject_non_retryable_errors, inject_retryable_conflict, inject_retryable_conflicts,
		retryable_conflict_count,
	};
	use crate::types::{PublicValue, PublicVariables};

	async fn new_index_compaction_test_ds() -> Result<(Arc<Datastore>, Session)> {
		new_index_compaction_test_ds_with_config(ConfigMap::empty()).await
	}

	/// [`new_index_compaction_test_ds`], with one configuration key set.
	async fn new_index_compaction_test_ds_with(
		key: &str,
		value: &str,
	) -> Result<(Arc<Datastore>, Session)> {
		new_index_compaction_test_ds_with_config(ConfigMap::empty().with_key_value(key, value))
			.await
	}

	async fn new_index_compaction_test_ds_with_config(
		config: ConfigMap,
	) -> Result<(Arc<Datastore>, Session)> {
		// These tests decide when compaction runs and observe the wake-up that
		// drives it. `CommitTriggers::index_compaction` is a `notify_one`, so a
		// background compactor would take the permit a test is waiting on.
		let ds = Datastore::builder()
			.without_maintenance_tasks()
			.with_config(config)
			.build_with_path("memory")
			.await?;
		let session = Session::owner().with_ns("test").with_db("test");
		let txn = ds.transaction(Write).await?;
		txn.ensure_ns_db(None, "test", "test").await?;
		txn.commit().await?;
		Ok((ds, session))
	}

	async fn execute_all(ds: &Datastore, session: &Session, sql: &str) -> Result<()> {
		for result in ds.execute(sql, session, None).await? {
			result.result?;
		}
		Ok(())
	}

	#[tokio::test]
	async fn record_auth_is_scoped_to_its_ns_db() -> Result<()> {
		// A record-scoped principal is only authorized for the namespace and
		// database it authenticated against. If the session context drifts to
		// another namespace or database (via a USE statement or connection
		// headers), every document operation must be rejected — even when the
		// target table's PERMISSIONS clauses would otherwise allow the
		// operation for record users.
		let ds = Datastore::new("memory").await?;
		let txn = ds.transaction(Write).await?;
		txn.ensure_ns_db(None, "first", "first").await?;
		txn.ensure_ns_db(None, "first", "other").await?;
		txn.ensure_ns_db(None, "second", "second").await?;
		txn.commit().await?;
		// Victim data in `second/second` with fully permissive permissions
		let owner = Session::owner().with_ns("second").with_db("second");
		execute_all(
			&ds,
			&owner,
			"DEFINE TABLE thing SCHEMALESS PERMISSIONS FULL; CREATE thing:1 SET secret = 'v';",
		)
		.await?;
		// A record principal authenticated against `first/first`, whose
		// session context has drifted to `second/second`
		let mut rec = Session::for_record(
			"first",
			"first",
			"user",
			surrealdb_types::Value::RecordId(surrealdb_types::RecordId::new("user", "tester")),
		);
		rec.ns = Some("second".to_owned());
		rec.db = Some("second".to_owned());
		// Every write into the drifted scope must be rejected
		for query in [
			"CREATE thing:2 SET secret = 'w'",
			"UPDATE thing:1 SET secret = 'w'",
			"UPSERT thing:1 SET secret = 'w'",
			"DELETE thing:1",
			"INSERT INTO thing { id: thing:3, secret: 'w' }",
		] {
			let err = execute_all(&ds, &rec, query)
				.await
				.expect_err(&format!("record user expected to be denied: {query}"));
			assert!(
				err.to_string().contains("namespace"),
				"expected a namespace authorization error for {query}, got: {err}"
			);
		}
		// Reads from the drifted scope must be rejected as well
		let err = execute_all(&ds, &rec, "SELECT * FROM thing")
			.await
			.expect_err("record user expected to be denied: SELECT");
		assert!(
			err.to_string().contains("namespace"),
			"expected a namespace authorization error for SELECT, got: {err}"
		);
		// A drift within the same namespace but to a different database must
		// also be rejected
		let owner = Session::owner().with_ns("first").with_db("other");
		execute_all(
			&ds,
			&owner,
			"DEFINE TABLE thing SCHEMALESS PERMISSIONS FULL; CREATE thing:1 SET secret = 'v';",
		)
		.await?;
		let mut rec = Session::for_record(
			"first",
			"first",
			"user",
			surrealdb_types::Value::RecordId(surrealdb_types::RecordId::new("user", "tester")),
		);
		rec.db = Some("other".to_owned());
		let err = execute_all(&ds, &rec, "UPDATE thing:1 SET secret = 'w'")
			.await
			.expect_err("record user expected to be denied in a sibling database");
		assert!(
			err.to_string().contains("database"),
			"expected a database authorization error, got: {err}"
		);
		// The victim data must be unchanged
		let owner = Session::owner().with_ns("second").with_db("second");
		let mut res = ds.execute("SELECT VALUE secret FROM thing", &owner, None).await?;
		let val = res.remove(0).result?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array!["v"]),
			"victim data was modified by an out-of-scope record user"
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_is_available_without_the_experimental_capability() -> Result<()> {
		let ds = Datastore::new("memory").await?;
		let ses = Session::owner().with_ns("test").with_db("test");
		// GQL is on by default: it must not be refused as an experimental
		// capability (any other error — e.g. missing namespace — is irrelevant).
		if let Err(err) =
			ds.run(QueryRequest::new(QuerySource::gql("MATCH (n:person) RETURN n"), &ses)).await
		{
			assert!(
				!err.to_string().contains("Experimental capability `gql` is not enabled"),
				"GQL was still gated: {err}"
			);
		}
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_text_parses_lowers_and_executes() -> Result<()> {
		use crate::dbs::capabilities::Targets;
		let ds = Datastore::builder()
			.with_capabilities(Capabilities::all().with_experimental(Targets::All))
			.build_with_path("memory")
			.await?;
		let ses = Session::owner().with_ns("test").with_db("test");
		let txn = ds.transaction(Write).await?;
		txn.ensure_ns_db(None, "test", "test").await?;
		txn.commit().await?;
		execute_all(&ds, &ses, "CREATE person:tobie SET name = 'Tobie';").await?;
		// A valid GQL query parses, lowers, and executes through the
		// SurrealQL pipeline
		let mut res = ds
			.run(QueryRequest::new(
				QuerySource::gql("MATCH (n:person) RETURN n.name AS name"),
				&ses,
			))
			.await?;
		assert_eq!(res.len(), 1);
		let val = res.remove(0).result?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { name: "Tobie" }]));
		// An invalid GQL query reports a parse error rather than a
		// capability error
		let err =
			ds.run(QueryRequest::new(QuerySource::gql("MATCH RETURN"), &ses)).await.unwrap_err();
		assert!(!err.to_string().contains("experimental"), "unexpected error: {err}");
		Ok(())
	}

	/// `set_capabilities` must take effect on an already-built datastore without
	/// a rebuild: a capability-gated operation (scripting) flips from denied to
	/// allowed after a live swap, proving the executor observes the new
	/// `ArcSwap` snapshot.
	#[cfg(feature = "scripting")]
	#[tokio::test]
	async fn set_capabilities_swaps_live() -> Result<()> {
		let ds = Datastore::new("memory").await?;
		let ses = Session::owner().with_ns("test").with_db("test");
		let txn = ds.transaction(Write).await?;
		txn.ensure_ns_db(None, "test", "test").await?;
		txn.commit().await?;

		// Default capabilities: scripting functions are denied.
		let mut before = ds.execute("RETURN function() { return 1; }", &ses, None).await?;
		assert!(
			before.remove(0).result.is_err(),
			"scripting should be denied under default capabilities"
		);

		// Swap in capabilities that enable scripting — no rebuild, same datastore.
		ds.set_capabilities(Capabilities::all())?;

		// The same datastore now permits scripting, proving the executor
		// observes the new `ArcSwap` snapshot.
		let mut after = ds.execute("RETURN function() { return 1; }", &ses, None).await?;
		assert!(
			after.remove(0).result.is_ok(),
			"scripting should be allowed after the capability swap"
		);
		Ok(())
	}

	/// A datastore with the `gql` capability and an initialised `test/test`
	/// namespace/database, for the GQL mutation tests.
	#[cfg(feature = "gql")]
	async fn gql_test_ds() -> Result<(Arc<Datastore>, Session)> {
		use crate::dbs::capabilities::Targets;
		let ds = Datastore::builder()
			.with_capabilities(Capabilities::all().with_experimental(Targets::All))
			.build_with_path("memory")
			.await?;
		let ses = Session::owner().with_ns("test").with_db("test");
		let txn = ds.transaction(Write).await?;
		txn.ensure_ns_db(None, "test", "test").await?;
		txn.commit().await?;
		Ok((ds, ses))
	}

	/// Run one GQL query, asserting a single statement result, and return it.
	#[cfg(feature = "gql")]
	async fn run_gql(ds: &Datastore, ses: &Session, query: &str) -> Result<PublicValue> {
		let mut res = ds.run(QueryRequest::new(QuerySource::gql(query), ses)).await?;
		assert_eq!(res.len(), 1, "expected one result for {query:?}");
		Ok(res.remove(0).result?)
	}

	/// Run one GQL query expecting failure (parse/lowering rejection or a
	/// per-statement execution error), returning the rendered error.
	#[cfg(feature = "gql")]
	async fn run_gql_err(ds: &Datastore, ses: &Session, query: &str) -> String {
		match ds.run(QueryRequest::new(QuerySource::gql(query), ses)).await {
			Ok(mut res) => match res.remove(0).result {
				Ok(value) => panic!("expected {query:?} to fail, got {value:?}"),
				Err(e) => e.to_string(),
			},
			Err(e) => e.to_string(),
		}
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_set_updates_and_returns_after_image() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A', age = 30;").await?;
		// SET returns the post-mutation value.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person) WHERE n.name = 'A' SET n.age = 31 RETURN n.age AS age",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { age: 31 }]));
		// And it persisted.
		let val = run_gql(&ds, &ses, "MATCH (n:person) RETURN n.age AS age").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { age: 31 }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_remove_unsets_field_and_returns_empty() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A', age = 30;").await?;
		// A mutation-only query returns an empty array.
		let val = run_gql(&ds, &ses, "MATCH (n:person) REMOVE n.age").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		// The field is gone: a filter on the old value no longer matches.
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) WHERE n.age = 30 RETURN n.name AS name").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		// The record itself survives.
		let val = run_gql(&ds, &ses, "MATCH (n:person) RETURN n.name AS name").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { name: "A" }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_delete_nodetach_errors_with_edges_then_detach_succeeds() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(
			&ds,
			&ses,
			"CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B'; \
			RELATE person:1->knows->person:2;",
		)
		.await?;
		// NODETACH (the default) on a node that still has edges errors.
		let err = run_gql_err(&ds, &ses, "MATCH (n:person) WHERE n.name = 'A' DELETE n").await;
		assert!(err.contains("connected edges"), "{err}");
		// The failed delete rolled back: A is still present.
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) RETURN n.name AS name ORDER BY name").await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { name: "A" },
				object! { name: "B" }
			])
		);
		// DETACH DELETE removes A and its edge.
		let val = run_gql(&ds, &ses, "MATCH (n:person) WHERE n.name = 'A' DETACH DELETE n").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) RETURN n.name AS name ORDER BY name").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { name: "B" }]));
		// The knows edge is gone too.
		let val =
			run_gql(&ds, &ses, "MATCH (a:person)-[:knows]->(b:person) RETURN a.name AS a").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_insert_node_and_edge() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		// A leading INSERT (no MATCH) creates a node exactly once.
		let val = run_gql(&ds, &ses, "INSERT (p:person {name: 'A'})").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		run_gql(&ds, &ses, "INSERT (p:person {name: 'B'})").await?;
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) RETURN n.name AS name ORDER BY name").await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { name: "A" },
				object! { name: "B" }
			])
		);
		// INSERT an edge between two MATCH-bound nodes.
		run_gql(
			&ds,
			&ses,
			"MATCH (a:person WHERE a.name = 'A') MATCH (b:person WHERE b.name = 'B') \
			INSERT (a)-[:knows]->(b)",
		)
		.await?;
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (a:person)-[:knows]->(b:person) RETURN a.name AS a, b.name AS b",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { a: "A", b: "B" }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_label_mutation_rejected() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A';").await?;
		let err = run_gql_err(&ds, &ses, "MATCH (n:person) SET n:Archived").await;
		assert!(err.contains("Label mutation is not supported"), "{err}");
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_set_all_properties_replaces_and_multi_item() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A', age = 30, city = 'L';").await?;
		// `SET n = {…}` replaces ALL user properties (age is dropped).
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person) SET n = {name: 'A2', city: 'X'} RETURN n.name AS name, n.city AS city",
		)
		.await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![object! { name: "A2", city: "X" }])
		);
		// The dropped `age` no longer matches.
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) WHERE n.age = 30 RETURN n.name AS name").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		// Multi-item SET on distinct properties.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person) SET n.age = 5, n.city = 'Z' RETURN n.age AS age, n.city AS city",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { age: 5, city: "Z" }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_multi_statement_set_last_wins() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A', age = 1;").await?;
		// Two SET statements in one query: the second sees the first's write.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person) SET n.age = 5 SET n.age = n.age + 1 RETURN n.age AS age",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { age: 6 }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_edge_set_remove_delete() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(
			&ds,
			&ses,
			"CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B'; \
			RELATE person:1->knows->person:2 SET since = 2020;",
		)
		.await?;
		// SET a property on a bound edge.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (a:person)-[k:knows]->(b:person) SET k.since = 2099 RETURN k.since AS since",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { since: 2099 }]));
		// DELETE a bound edge (NODETACH default is fine: an edge has no sub-edges).
		let val = run_gql(&ds, &ses, "MATCH (a:person)-[k:knows]->(b:person) DELETE k").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		let val =
			run_gql(&ds, &ses, "MATCH (a:person)-[:knows]->(b:person) RETURN a.name AS a").await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_fanout_set_is_consistent_per_row() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(
			&ds,
			&ses,
			"CREATE person:1 SET name = 'A', age = 30; CREATE person:2 SET name = 'B'; \
			CREATE person:3 SET name = 'C'; RELATE person:1->knows->person:2; \
			RELATE person:1->knows->person:3;",
		)
		.await?;
		// `a` fans out to two rows; SET a.age = 7 must show a consistent AFTER image
		// on both rows (the §1 fix — no stale pre-mutation binding on a duplicate).
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (a:person)-[:knows]->(b:person) WHERE a.name = 'A' SET a.age = 7 \
			RETURN a.age AS age, b.name AS b ORDER BY b",
		)
		.await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { age: 7, b: "B" },
				object! { age: 7, b: "C" }
			])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_detach_delete_nulls_cascaded_edge_binding() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(
			&ds,
			&ses,
			"CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B'; \
			RELATE person:1->knows->person:2 SET since = 2020;",
		)
		.await?;
		// DETACH DELETE on `a` cascades the `k` edge; the §3 fix nulls `k` in the
		// RETURN rather than surfacing the stale (deleted) edge.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (a:person)-[k:knows]->(b:person) WHERE a.name = 'A' DETACH DELETE a \
			RETURN a AS a, k AS k, b.name AS b",
		)
		.await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![object! {
				a: PublicValue::Null,
				k: PublicValue::Null,
				b: "B"
			}])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_insert_left_edge_chain_and_repeated_anon() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B';")
			.await?;
		// A left-pointing INSERT edge relates b -> a.
		run_gql(
			&ds,
			&ses,
			"MATCH (a:person WHERE a.name = 'A') MATCH (b:person WHERE b.name = 'B') \
			INSERT (a)<-[:knows]-(b)",
		)
		.await?;
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (x:person)-[:knows]->(y:person) RETURN x.name AS x, y.name AS y",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { x: "B", y: "A" }]));
		// A chained INSERT creates three new nodes and two edges.
		run_gql(
			&ds,
			&ses,
			"INSERT (x:item {n: 1})-[:link]->(y:item {n: 2})-[:link]->(z:item {n: 3})",
		)
		.await?;
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (a:item)-[:link]->(b:item) RETURN a.n AS a, b.n AS b ORDER BY a",
		)
		.await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { a: 1, b: 2 },
				object! { a: 2, b: 3 }
			])
		);
		// Repeated anonymous nodes in one INSERT create distinct records.
		run_gql(&ds, &ses, "INSERT (:tag {v: 1}), (:tag {v: 1})").await?;
		let val = run_gql(&ds, &ses, "MATCH (t:tag) RETURN t.v AS v ORDER BY v").await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![object! { v: 1 }, object! { v: 1 }])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_mutation_rejection_ledger() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		// Each lowers (or parses) to a precise rejection. No data needed — these
		// fail before execution.
		let cases: &[(&str, &str)] = &[
			// Mutating a variable not bound by the read body.
			("MATCH (n:person) SET x.age = 1", "Unknown variable"),
			// Mutating a path variable (a composite, not a record).
			("MATCH p = (a:person)-[:knows]->(b:person) SET p.x = 1", "group or path variable"),
			// `SET a = {…}` setting a reserved key.
			("MATCH (n:person) SET n = {id: 1}", "reserved `id` key"),
			// Per-property SET of a reserved edge endpoint (the native write path
			// would otherwise silently re-stamp `out`, so it is rejected up front).
			("MATCH (a:person)-[k:knows]->(b:person) SET k.out = 1", "reserved `out` key"),
			// Label mutation via REMOVE.
			("MATCH (n:person) REMOVE n:Foo", "Label mutation is not supported"),
			// INSERT re-declaring a MATCH-bound variable as a new (labelled) node.
			("MATCH (a:person) INSERT (a:thing)", "already bound"),
			// INSERT node that is neither labelled nor a bound-variable reference.
			("INSERT (x)", "must declare a label"),
			// Undirected INSERT edge.
			("INSERT (a:person)~[:knows]~(b:person)", "Undirected INSERT edges"),
			// DELETE of a non-variable expression.
			("MATCH (n:person) DELETE n.age", "bound variable"),
		];
		for (query, expected) in cases {
			let err = run_gql_err(&ds, &ses, query).await;
			assert!(err.contains(expected), "query {query:?}: expected {expected:?}, got: {err}");
		}
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_mutation_respects_record_permissions() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		// Owner: a table that denies create/update (but allows select), seeded
		// with one row.
		execute_all(
			&ds,
			&ses,
			"DEFINE TABLE person SCHEMALESS \
			PERMISSIONS FOR select FULL, FOR create NONE, FOR update NONE, FOR delete NONE; \
			CREATE person:1 SET name = 'A', age = 30;",
		)
		.await?;
		// A record-scoped session: table PERMISSIONS clauses apply (a role-based
		// system session would bypass them, so this is the meaningful test).
		let rec = Session::for_record(
			"test",
			"test",
			"user",
			surrealdb_types::Value::RecordId(surrealdb_types::RecordId::new("user", "tester")),
		);
		// Each write goes through the native document pipeline, so each is denied:
		// INSERT (create), SET (update), DELETE (delete) all leave the row intact.
		let _ = ds
			.run(QueryRequest::new(QuerySource::gql("INSERT (p:person {name: 'B'})"), &rec))
			.await;
		let _ = ds
			.run(QueryRequest::new(QuerySource::gql("MATCH (n:person) SET n.age = 99"), &rec))
			.await;
		let _ = ds
			.run(QueryRequest::new(QuerySource::gql("MATCH (n:person) DETACH DELETE n"), &rec))
			.await;
		// As owner: exactly the original row remains, unchanged.
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) RETURN n.name AS name, n.age AS age").await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![object! { name: "A", age: 30 }])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_nodetach_probe_ignores_select_permissions() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		// `person` is fully visible/deletable to a record session, but the `knows`
		// edge table hides SELECT from it. Seed a node with one connected edge.
		execute_all(
			&ds,
			&ses,
			"DEFINE TABLE person SCHEMALESS \
			PERMISSIONS FOR select FULL, FOR create FULL, FOR update FULL, FOR delete FULL; \
			DEFINE TABLE knows SCHEMALESS \
			PERMISSIONS FOR select NONE, FOR create FULL, FOR update FULL, FOR delete FULL; \
			CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B'; \
			RELATE person:1->knows->person:2;",
		)
		.await?;
		let rec = Session::for_record(
			"test",
			"test",
			"user",
			surrealdb_types::Value::RecordId(surrealdb_types::RecordId::new("user", "tester")),
		);
		// The NODETACH (default) connected-edge probe runs with permissions
		// DISABLED, so it sees the `knows` edge the record session cannot SELECT and
		// errors — rather than passing the guard and letting the native DELETE
		// silently cascade an edge the caller opted out of removing.
		let err = run_gql_err(&ds, &rec, "MATCH (n:person WHERE n.name = 'A') DELETE n").await;
		assert!(err.contains("connected edges"), "{err}");
		// The node (and its edge) survive the rejected delete.
		let val =
			run_gql(&ds, &ses, "MATCH (n:person) RETURN n.name AS name ORDER BY name").await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { name: "A" },
				object! { name: "B" }
			])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_match_after_set_rereads_live_state() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(
			&ds,
			&ses,
			"CREATE person:1 SET name = 'A', tier = 'bronze'; \
			CREATE person:2 SET name = 'B', tier = 'gold';",
		)
		.await?;
		// A read step after a write re-scans the live (post-write) state in the same
		// transaction: promoting A to gold and then MATCHing on `tier = 'gold'` finds
		// both A (just written) and B.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person WHERE n.name = 'A') SET n.tier = 'gold' \
			MATCH (m:person WHERE m.tier = 'gold') RETURN m.name AS name ORDER BY name",
		)
		.await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { name: "A" },
				object! { name: "B" }
			])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_match_after_delete_rereads_live_state() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B';")
			.await?;
		// The trailing MATCH no longer observes the row the DELETE removed.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person WHERE n.name = 'A') DETACH DELETE n \
			MATCH (m:person) RETURN m.name AS name ORDER BY name",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { name: "B" }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_match_after_insert_sees_new_node_and_anchors_on_binding() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A', age = 20;").await?;
		// A trailing MATCH re-scans and observes the just-inserted node, and can join
		// on the binding the INSERT created (`a.age` anchors the predicate on `b`).
		let val = run_gql(
			&ds,
			&ses,
			"INSERT (a:person {name: 'New', age: 20}) \
			MATCH (b:person WHERE b.age = a.age) RETURN b.name AS name ORDER BY name",
		)
		.await?;
		assert_eq!(
			val,
			PublicValue::Array(surrealdb_types::array![
				object! { name: "A" },
				object! { name: "New" }
			])
		);
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_optional_match_after_set_rereads_live_state() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A'; CREATE person:2 SET name = 'B';")
			.await?;
		// An OPTIONAL block after a write takes the general left-join path (the
		// mutating accumulator is the join's probe side, the OPTIONAL read is its
		// build side). The OPTIONAL must still observe the write: after promoting A
		// to gold, `OPTIONAL MATCH (m:person WHERE m.tier = 'gold')` matches A (just
		// written), so `m` is bound, NOT null-filled.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (n:person WHERE n.name = 'A') SET n.tier = 'gold' \
					OPTIONAL MATCH (m:person WHERE m.tier = 'gold') \
					RETURN n.name AS n, m.name AS m",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { n: "A", m: "A" }]));
		Ok(())
	}

	#[cfg(feature = "gql")]
	#[tokio::test]
	async fn gql_optional_match_after_insert_sees_new_node() -> Result<()> {
		let (ds, ses) = gql_test_ds().await?;
		execute_all(&ds, &ses, "CREATE person:1 SET name = 'A';").await?;
		// An OPTIONAL block after an INSERT must see the just-created node. The
		// INSERT runs once per matched `person`; the trailing OPTIONAL re-scans
		// `tag` and binds `m` to the new node rather than null-filling it.
		let val = run_gql(
			&ds,
			&ses,
			"MATCH (a:person WHERE a.name = 'A') INSERT (t:tag {name: 'X'}) \
			OPTIONAL MATCH (m:tag) \
			RETURN m.name AS m",
		)
		.await?;
		assert_eq!(val, PublicValue::Array(surrealdb_types::array![object! { m: "X" }]));
		Ok(())
	}

	async fn index_key_base(ds: &Datastore, table: &str, index: &str) -> Result<IndexKeyBase> {
		let txn = ds.transaction(Read).await?;
		let ns = txn.get_ns_by_name("test", None).await?.unwrap();
		let db = txn.get_db_by_name("test", "test", None).await?.unwrap();
		let table = TableName::from(table);
		let ix =
			txn.get_tb_index(ns.namespace_id, db.database_id, &table, index, None).await?.unwrap();
		txn.cancel().await?;
		Ok(IndexKeyBase::new(ns.namespace_id, db.database_id, table, ix.index_id))
	}

	async fn assert_index_compaction_commit_retry(
		site: RetryableConflictSite,
		table: &str,
		index: &str,
		sql: &str,
	) -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(&ds, &session, sql).await?;
		let ikb = index_key_base(&ds, table, index).await?;
		let node_id = ds.id();
		let _guard = inject_retryable_conflict(site, node_id);

		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;

		assert_eq!(retryable_conflict_count(site, node_id), 0);
		Ok(())
	}

	const COUNT_COMPACTION_SQL: &str = "
		DEFINE TABLE user SCHEMALESS;
	DEFINE INDEX count_idx ON user COUNT;
	CREATE user:1 SET name = 'one' RETURN NONE;
	CREATE user:2 SET name = 'two' RETURN NONE;
	";

	const FULLTEXT_COMPACTION_SQL: &str = "
		DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;
	DEFINE TABLE doc SCHEMALESS;
	DEFINE INDEX ft_idx ON doc FIELDS text FULLTEXT ANALYZER simple BM25 HIGHLIGHTS;
	CREATE doc:1 SET text = 'alpha beta' RETURN NONE;
	CREATE doc:2 SET text = 'beta gamma' RETURN NONE;
	";

	const HNSW_COMPACTION_SQL: &str = "
		DEFINE TABLE vec SCHEMALESS;
	DEFINE INDEX hnsw_idx ON vec FIELDS vector HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4;
	CREATE vec:1 SET vector = [1, 2] RETURN NONE;
	CREATE vec:2 SET vector = [2, 3] RETURN NONE;
	";

	#[tokio::test]
	async fn count_index_compaction_retries_commit_conflict() -> Result<()> {
		assert_index_compaction_commit_retry(
			RetryableConflictSite::CountCompaction,
			"user",
			"count_idx",
			COUNT_COMPACTION_SQL,
		)
		.await
	}

	#[tokio::test]
	async fn fulltext_index_compaction_retries_commit_conflict() -> Result<()> {
		assert_index_compaction_commit_retry(
			RetryableConflictSite::FullTextCompaction,
			"doc",
			"ft_idx",
			FULLTEXT_COMPACTION_SQL,
		)
		.await
	}

	#[tokio::test]
	async fn hnsw_index_compaction_retries_commit_conflict() -> Result<()> {
		assert_index_compaction_commit_retry(
			RetryableConflictSite::HnswCompaction,
			"vec",
			"hnsw_idx",
			HNSW_COMPACTION_SQL,
		)
		.await
	}

	/// The process-local HNSW wrapper for one index, resolved the way the query
	/// path resolves it, so a test holds the same instance the compaction and
	/// the executor reach for.
	async fn loaded_hnsw_index(
		ds: &Datastore,
		table: &str,
		index: &str,
	) -> Result<crate::idx::trees::store::hnsw::SharedHnswIndex> {
		let table = TableName::from(table);
		let txn = Arc::new(ds.transaction(Read).await?);
		let ns = txn.get_ns_by_name("test", None).await?.unwrap();
		let db = txn.get_db_by_name("test", "test", None).await?.unwrap();
		let tb = txn.get_tb(ns.namespace_id, db.database_id, &table, None).await?.unwrap();
		let ix =
			txn.get_tb_index(ns.namespace_id, db.database_id, &table, index, None).await?.unwrap();
		let Index::Hnsw(p) = &ix.index else {
			panic!("{index} is not an HNSW index");
		};
		let ikb = IndexKeyBase::new(ns.namespace_id, db.database_id, table, ix.index_id);
		let mut ctx = ds.setup_ctx()?;
		ctx.set_transaction(Arc::clone(&txn));
		let ctx = ctx.freeze();
		let hi =
			ds.index_store().get_index_hnsw(&ctx, tb.table_id, &ikb, p, ix.format_version).await?;
		txn.cancel().await?;
		Ok(hi)
	}

	/// The entries an HNSW compaction still has to apply, across both pending
	/// families.
	async fn hnsw_pending_len(ds: &Datastore, ikb: &IndexKeyBase) -> Result<usize> {
		let txn = ds.transaction(Read).await?;
		let records = txn.getr(ikb.new_hr_range()?, None).await?.len();
		let appends = txn.getr_raw(ikb.new_hp_range()?, None).await?.len();
		txn.cancel().await?;
		Ok(records + appends)
	}

	/// The layer versions the store holds for one HNSW index, layer 0 first.
	async fn hnsw_layer_versions(ds: &Datastore, ikb: &IndexKeyBase) -> Result<Vec<u64>> {
		let txn = ds.transaction(Read).await?;
		let state: surrealdb_datastore::values::hnsw::HnswState =
			txn.get_key(&ikb.new_hs_key(), None).await?.unwrap_or_default();
		txn.cancel().await?;
		let mut versions = Vec::with_capacity(1 + state.layers.len());
		versions.push(state.layer0.version);
		versions.extend(state.layers.iter().map(|l| l.version));
		Ok(versions)
	}

	/// A filtered kNN search must not evaluate its residual condition against a
	/// legacy pending entry that carries no vectors to score.
	#[tokio::test]
	async fn hnsw_legacy_pending_delete_entry_is_not_where_evaluated() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(
			&ds,
			&session,
			"DEFINE TABLE vec SCHEMALESS;
			 DEFINE INDEX hnsw_idx ON vec FIELDS vector HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4;
			 CREATE vec:2 SET vector = [5, 5], bad = 5 RETURN NONE;
			 CREATE vec:1 SET bad = 'x' RETURN NONE;",
		)
		.await?;
		let ikb = index_key_base(&ds, "vec", "hnsw_idx").await?;

		// Put vec:2 in the graph, then inject the shape of a pre-v3.1 legacy
		// delete that an upgraded node can still encounter while draining `!hp`.
		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;
		{
			let txn = ds.transaction(Write).await?;
			let key = surrealdb_datastore::key::schema::HnswPendingLegacyKey::new(
				ikb.ns(),
				ikb.db(),
				Cow::Borrowed(ikb.table()),
				ikb.index(),
				0,
			);
			let pending = surrealdb_datastore::values::hnsw::VectorPendingUpdate {
				id: surrealdb_datastore::values::hnsw::VectorId::RecordKey(Arc::new(
					crate::val::RecordIdKey::Number(1),
				)),
				old_vectors: vec![],
				new_vectors: vec![],
			};
			txn.set_key(&key, &pending).await?;
			txn.commit().await?;
		}

		let mut response = ds
			.execute(
				"SELECT id FROM vec WHERE vector <|5,40|> [0, 0] AND type::int(bad) > 0;",
				&session,
				None,
			)
			.await?;
		let rows = match response.remove(0).result {
			Ok(PublicValue::Array(rows)) => rows,
			Ok(other) => panic!("expected an array result, got {other:?}"),
			Err(error) => panic!(
				"the excluded vec:1 legacy delete must not have its residual condition evaluated: {error}"
			),
		};
		assert_eq!(rows.len(), 1, "only vec:2 satisfies the query: {rows:?}");
		Ok(())
	}

	/// A compaction apply that reached the graph in place and then failed to
	/// commit must not leave that graph reachable.
	///
	/// The apply advances the in-memory version of every layer it writes, and
	/// that version is a plain per-layer counter: a peer applying the same
	/// batch from the same version lands on the same one. This fixture pins the
	/// arithmetic — one staged record advances layer 0 by exactly one — so the
	/// rolled-back copy and a peer's committed copy stand at the same version
	/// with topologies that need not match, and a state check comparing
	/// versions would keep the copy the store never took. The wrapper goes
	/// instead, and the next access rebuilds it from persisted state.
	///
	/// The index engines are configured serial, so the insertion is applied in
	/// place; see the staged counterpart below for the default. The injected
	/// conflict classifies as retryable, so the compaction rolls its write
	/// back, discards the wrapper, and applies again; the call returns once
	/// that attempt commits. That attempt drains the queue, so the records the
	/// index then answers over come from the graph alone.
	#[tokio::test]
	async fn hnsw_index_compaction_commit_failure_evicts_the_loaded_index() -> Result<()> {
		let (ds, session) =
			new_index_compaction_test_ds_with("hnsw_build_parallelism", "serial").await?;
		execute_all(&ds, &session, HNSW_COMPACTION_SQL).await?;
		let ikb = index_key_base(&ds, "vec", "hnsw_idx").await?;
		let site = RetryableConflictSite::HnswCompaction;
		let node_id = ds.id();

		// Hold the wrapper the query path uses, with its graph resident.
		let before = loaded_hnsw_index(&ds, "vec", "hnsw_idx").await?;
		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;
		let versions = hnsw_layer_versions(&ds, &ikb).await?;

		// One more pending, and a commit conflict to roll its apply back.
		execute_all(&ds, &session, "CREATE vec:3 SET vector = [8, 9] RETURN NONE;").await?;
		assert_eq!(hnsw_pending_len(&ds, &ikb).await?, 1, "the record must be staged, not indexed");
		let _guard = inject_retryable_conflict(site, node_id);
		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;
		assert_eq!(retryable_conflict_count(site, node_id), 0, "the conflict must have fired");
		assert_eq!(
			hnsw_pending_len(&ds, &ikb).await?,
			0,
			"the attempt after the rollback must have applied the pending it rolled back"
		);

		// The advance the rolled-back apply staged in memory, and that the
		// attempt after it then committed: one batch of one record, one layer-0
		// version. A peer applying that same batch reproduces it exactly, which
		// is why the version cannot certify the rolled-back topology.
		let applied = hnsw_layer_versions(&ds, &ikb).await?;
		assert_eq!(
			applied[0],
			versions[0] + 1,
			"one staged record must advance layer 0 by exactly one: {versions:?} -> {applied:?}"
		);

		// The wrapper the rollback mutated is gone; the attempt after it ran on
		// one rebuilt from the store.
		let after = loaded_hnsw_index(&ds, "vec", "hnsw_idx").await?;
		assert!(
			!Arc::ptr_eq(&before, &after),
			"a rolled-back compaction write must not leave its graph reachable"
		);

		// With the queue drained, every record answered for comes from the
		// graph, which the rebuilt wrapper took from the store.
		let mut response =
			ds.execute("SELECT id FROM vec WHERE vector <|3,40|> [1, 2];", &session, None).await?;
		let PublicValue::Array(rows) = response.remove(0).result? else {
			panic!("expected an array result");
		};
		assert_eq!(rows.len(), 3, "the recovered index must return every record: {rows:?}");
		Ok(())
	}

	/// A staged compaction whose commit fails leaves the loaded index in place.
	///
	/// A batch that only adds vectors builds its graph changes into its
	/// transaction and publishes them into the resident graph from the commit,
	/// so a commit that fails leaves the resident graph at the committed state:
	/// there is nothing to discard, and the retry runs on the same wrapper. The
	/// retry advances layer 0 by exactly one, as the in-place apply does, and
	/// once it has drained the queue the graph answers for every record.
	#[tokio::test]
	async fn hnsw_staged_compaction_commit_failure_keeps_the_loaded_index() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(&ds, &session, HNSW_COMPACTION_SQL).await?;
		let ikb = index_key_base(&ds, "vec", "hnsw_idx").await?;
		let site = RetryableConflictSite::HnswCompaction;
		let node_id = ds.id();

		let before = loaded_hnsw_index(&ds, "vec", "hnsw_idx").await?;
		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;
		let versions = hnsw_layer_versions(&ds, &ikb).await?;

		execute_all(&ds, &session, "CREATE vec:3 SET vector = [8, 9] RETURN NONE;").await?;
		assert_eq!(hnsw_pending_len(&ds, &ikb).await?, 1, "the record must be staged, not indexed");
		let _guard = inject_retryable_conflict(site, node_id);
		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;
		assert_eq!(retryable_conflict_count(site, node_id), 0, "the conflict must have fired");
		assert_eq!(
			hnsw_pending_len(&ds, &ikb).await?,
			0,
			"the attempt after the rollback must have applied the pending it rolled back"
		);
		let applied = hnsw_layer_versions(&ds, &ikb).await?;
		assert_eq!(
			applied[0],
			versions[0] + 1,
			"one staged batch must advance layer 0 by exactly one: {versions:?} -> {applied:?}"
		);

		let after = loaded_hnsw_index(&ds, "vec", "hnsw_idx").await?;
		assert!(
			Arc::ptr_eq(&before, &after),
			"a staged batch that did not commit must leave the loaded index in place"
		);
		let mut response =
			ds.execute("SELECT id FROM vec WHERE vector <|3,40|> [1, 2];", &session, None).await?;
		let PublicValue::Array(rows) = response.remove(0).result? else {
			panic!("expected an array result");
		};
		assert_eq!(rows.len(), 3, "the index must return every record: {rows:?}");
		Ok(())
	}

	/// An apply error can land after a layer mutates but before `save_nodes`
	/// advances its version, leaving a resident topology the store never took
	/// under the version the store already holds. That path must evict the
	/// wrapper too.
	#[tokio::test]
	async fn hnsw_index_compaction_apply_error_evicts_the_loaded_index() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(&ds, &session, HNSW_COMPACTION_SQL).await?;
		let ikb = index_key_base(&ds, "vec", "hnsw_idx").await?;
		ds.process_index_compaction(&ikb, CancellationToken::new()).await?;

		// Hold the query-path wrapper with the two-node graph resident. Element
		// ids follow the two separately keyed pending records: vec:1 is 0 and
		// vec:2 is 1.
		let before = loaded_hnsw_index(&ds, "vec", "hnsw_idx").await?;
		let (table_id, format_version, entry_point) = {
			let txn = ds.transaction(Read).await?;
			let ns = txn.get_ns_by_name("test", None).await?.unwrap();
			let db = txn.get_db_by_name("test", "test", None).await?.unwrap();
			let table = TableName::from("vec");
			let tb = txn.get_tb(ns.namespace_id, db.database_id, &table, None).await?.unwrap();
			let ix = txn
				.get_tb_index(ns.namespace_id, db.database_id, &table, "hnsw_idx", None)
				.await?
				.unwrap();
			let state: surrealdb_datastore::values::hnsw::HnswState =
				txn.get_key(&ikb.new_hs_key(), None).await?.unwrap();
			txn.cancel().await?;
			(tb.table_id, ix.format_version, state.enter_point.unwrap())
		};
		assert!(entry_point <= 1, "the two-node fixture has an unexpected entry point");

		// Delete the non-entry-point record. Its layer-0 removal mutates the
		// resident graph before resolving the remaining neighbour's vector.
		let removed_element = 1 - entry_point;
		let delete = format!("DELETE vec:{} RETURN NONE;", removed_element + 1);
		execute_all(&ds, &session, &delete).await?;
		assert_eq!(hnsw_pending_len(&ds, &ikb).await?, 1);

		// Force that neighbour lookup to the store, then corrupt its encoded
		// vector. The apply now errors after `remove_node_and_bidirectional_edges`
		// but before `save_nodes` can version the mutated layer.
		ds.index_store().invalidate_hnsw_index_caches(table_id, &ikb, format_version).await;
		let entry_vector_key = surrealdb_datastore::key::schema::HnswVectorKey::new(
			ikb.ns(),
			ikb.db(),
			Cow::Borrowed(ikb.table()),
			ikb.index(),
			entry_point,
		);
		let txn = ds.transaction(Write).await?;
		txn.set(entry_vector_key.encode_key()?, vec![0xff]).await?;
		txn.commit().await?;

		ds.process_index_compaction(&ikb, CancellationToken::new())
			.await
			.expect_err("the malformed neighbour vector must fail the graph apply");
		assert_eq!(
			hnsw_pending_len(&ds, &ikb).await?,
			1,
			"the failed apply must roll back its conditional pending delete"
		);

		let after = loaded_hnsw_index(&ds, "vec", "hnsw_idx").await?;
		assert!(
			!Arc::ptr_eq(&before, &after),
			"an apply error before versioning must evict the mutated wrapper"
		);
		Ok(())
	}

	#[tokio::test]
	async fn index_compaction_retries_queue_cleanup_commit_conflict() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(&ds, &session, COUNT_COMPACTION_SQL).await?;
		let site = RetryableConflictSite::IndexCompactionQueueCleanup;
		let node_id = ds.id();
		let _guard = inject_retryable_conflict(site, node_id);

		let (_, errors) =
			Datastore::index_compaction(ds, Duration::from_secs(1), CancellationToken::new())
				.await?;

		assert_eq!(errors, 0);
		assert_eq!(retryable_conflict_count(site, node_id), 0);
		Ok(())
	}

	/// The compaction-queue drain must never delete more than one batch of
	/// `/!ic` entries per write transaction: the queue grows by one entry per
	/// indexed record write, so an unbounded cleanup transaction would carry
	/// one write per accumulated entry — the per-key reservation profile that
	/// can starve distributed backends.
	#[tokio::test]
	async fn index_compaction_queue_cleanup_is_bounded() -> Result<()> {
		let batch = INDEX_COMPACTION_QUEUE_BATCH_SIZE as usize;
		// A backlog of 2.5 batches forces multiple drain iterations.
		let backlog = batch * 2 + batch / 2;
		let observer = Arc::new(WriteTxSizeObserver::default());
		// Background jobs are off so the only transactions observed are the
		// ones this test drives. The maintenance task runs this very function
		// on the same datastore, and its lease admits a second pass on the same
		// node, so one landing inside this drain both conflicts with the
		// cleanup commit — making it retry and re-observe its keys — and
		// commits batches of its own that the observer cannot distinguish from
		// this drain's.
		let ds = Datastore::builder()
			.without_maintenance_tasks()
			.with_observer(Arc::clone(&observer) as Arc<dyn ExecutionObserver>)
			.build_with_path("memory")
			.await?;
		let session = Session::owner().with_ns("test").with_db("test");
		{
			let txn = ds.transaction(Write).await?;
			txn.ensure_ns_db(None, "test", "test").await?;
			txn.commit().await?;
		}
		// A real index for the queue entries to reference. The table stays
		// empty (no record writes, which would each enqueue an entry of
		// their own), so compacting it performs no index writes and the
		// cycle's only large write transactions are the queue cleanups.
		execute_all(
			&ds,
			&session,
			"DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;
			 DEFINE TABLE doc SCHEMALESS;
			 DEFINE INDEX ft_idx ON doc FIELDS text FULLTEXT ANALYZER simple BM25;",
		)
		.await?;
		let ikb = index_key_base(&ds, "doc", "ft_idx").await?;
		let node_id = ds.id();
		// Enqueue the backlog directly: each key is unique, exactly as the
		// per-record-write enqueue path produces them.
		{
			let txn = ds.transaction(Write).await?;
			for _ in 0..backlog {
				txn.set_key(&ikb.new_ic_key(node_id), &()).await?;
			}
			txn.commit().await?;
		}
		// Only observe the compaction cycle's own transactions.
		observer.clear();

		let (batches, errors) = Datastore::index_compaction(
			Arc::clone(&ds),
			Duration::from_secs(60),
			CancellationToken::new(),
		)
		.await?;
		assert_eq!(errors, 0);
		assert_eq!(batches, 3, "expected the backlog to drain in ceil(2.5) batches");

		// The queue is fully drained.
		let remaining = {
			let txn = ds.transaction(Read).await?;
			let res = txn.keys(IndexCompactionPrefix {}.range()?, u32::MAX, 0, None).await;
			let _ = txn.cancel().await;
			res?
		};
		assert!(remaining.is_empty(), "queue not drained: {} entries left", remaining.len());

		// No write transaction exceeded the batch bound, and the cleanups
		// were exactly [batch, batch, batch/2].
		let sizes = observer.sizes();
		assert!(
			sizes.iter().all(|&n| n <= batch as u64),
			"a write transaction exceeded the {batch}-key bound: {sizes:?}"
		);
		let cleanups = cleanup_sizes(&sizes);
		assert_eq!(
			cleanups,
			vec![batch as u64, batch as u64, (batch / 2) as u64],
			"unexpected cleanup transaction sizes"
		);
		Ok(())
	}

	/// Queue keys sort by index before their time-ordered UUID, so a
	/// start-anchored scan would keep serving an early-sorting index for as
	/// long as it has (or keeps receiving) entries. The drain must instead
	/// rotate: after a batch, the scan resumes past that batch's last index,
	/// reaching later-sorting indexes before returning for the remainder.
	#[tokio::test]
	async fn index_compaction_queue_drain_rotates_across_indexes() -> Result<()> {
		let batch = INDEX_COMPACTION_QUEUE_BATCH_SIZE as usize;
		let observer = Arc::new(WriteTxSizeObserver::default());
		// Background jobs are off, for the same reason as the bounded test
		// above: the maintenance task runs this very function, and a second
		// pass inside this drain would both conflict with the cleanup commits
		// and contribute batches of its own to the observed sequence.
		let ds = Datastore::builder()
			.without_maintenance_tasks()
			.with_observer(Arc::clone(&observer) as Arc<dyn ExecutionObserver>)
			.build_with_path("memory")
			.await?;
		let session = Session::owner().with_ns("test").with_db("test");
		{
			let txn = ds.transaction(Write).await?;
			txn.ensure_ns_db(None, "test", "test").await?;
			txn.commit().await?;
		}
		// Two empty indexed tables whose names order their queue entries:
		// `aaa` sorts before `zzz`.
		execute_all(
			&ds,
			&session,
			"DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;
			 DEFINE TABLE aaa SCHEMALESS;
			 DEFINE TABLE zzz SCHEMALESS;
			 DEFINE INDEX ft_a ON aaa FIELDS text FULLTEXT ANALYZER simple BM25;
			 DEFINE INDEX ft_z ON zzz FIELDS text FULLTEXT ANALYZER simple BM25;",
		)
		.await?;
		let ikb_a = index_key_base(&ds, "aaa", "ft_a").await?;
		let ikb_z = index_key_base(&ds, "zzz", "ft_z").await?;
		let node_id = ds.id();
		// 1.5 batches for the early index, a handful for the late one.
		{
			let txn = ds.transaction(Write).await?;
			for _ in 0..(batch + batch / 2) {
				txn.set_key(&ikb_a.new_ic_key(node_id), &()).await?;
			}
			for _ in 0..10 {
				txn.set_key(&ikb_z.new_ic_key(node_id), &()).await?;
			}
			txn.commit().await?;
		}
		observer.clear();

		let (batches, errors) = Datastore::index_compaction(
			Arc::clone(&ds),
			Duration::from_secs(60),
			CancellationToken::new(),
		)
		.await?;
		assert_eq!(errors, 0);
		assert_eq!(batches, 3);

		// The queue is fully drained. An abandoned cleanup leaves entries
		// behind without moving `errors` or `batches`, so the sequence below
		// cannot stand in for this.
		let remaining = {
			let txn = ds.transaction(Read).await?;
			let res = txn.keys(IndexCompactionPrefix {}.range()?, u32::MAX, 0, None).await;
			let _ = txn.cancel().await;
			res?
		};
		assert!(remaining.is_empty(), "queue not drained: {} entries left", remaining.len());

		// Rotation signature: after the first full batch of the early index,
		// the late index is served before the early index's remainder.
		let sizes = observer.sizes();
		let cleanups = cleanup_sizes(&sizes);
		assert_eq!(
			cleanups,
			vec![batch as u64, 10, (batch / 2) as u64],
			"expected the late-sorting index to be drained between the early index's batches"
		);
		Ok(())
	}

	/// One statement writing many documents must leave exactly one `!iu`
	/// count-delta entry and one `/!ic` compaction request, not one of each per
	/// document.
	///
	/// Reads of a COUNT index sum every un-compacted `!iu` entry, so the
	/// per-document fan-out made `count()` cost scale with write volume and made
	/// the compaction queue grow at the same rate. Aggregating per transaction
	/// keeps the contention-free property the delta log exists for (the entry is
	/// still a blind write under a key no other transaction shares) while
	/// removing that scaling.
	#[tokio::test]
	async fn count_index_writes_one_delta_per_transaction() -> Result<()> {
		const ROWS: usize = 500;
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(
			&ds,
			&session,
			"DEFINE TABLE item SCHEMALESS;
			 DEFINE INDEX idx_total ON item COUNT;",
		)
		.await?;
		let ikb = index_key_base(&ds, "item", "idx_total").await?;

		execute_all(&ds, &session, &format!("CREATE |item:1..={ROWS}| RETURN NONE")).await?;

		let (deltas, queued) = {
			let txn = ds.transaction(Read).await?;
			let iu = IndexCountPrefix {
				ns: ikb.ns(),
				db: ikb.db(),
				tb: Cow::Borrowed(ikb.table()),
				ix: ikb.index(),
			}
			.range()?;
			let deltas = catch!(txn, txn.keys(iu, u32::MAX, 0, None).await);
			let queued =
				catch!(txn, txn.keys(IndexCompactionPrefix {}.range()?, u32::MAX, 0, None).await);
			let _ = txn.cancel().await;
			(deltas, queued)
		};

		assert_eq!(
			deltas.len(),
			1,
			"{ROWS} rows in one statement must leave one count-delta entry, found {}",
			deltas.len()
		);
		assert_eq!(
			queued.len(),
			1,
			"{ROWS} rows in one statement must enqueue one compaction request, found {}",
			queued.len()
		);

		// The single entry carries the net delta, so the count is still right.
		let sum = {
			let mut sum: i64 = 0;
			for key in &deltas {
				let iu = IndexCountKey::decode_key(key)?;
				let delta = i64::try_from(iu.count).expect("count delta out of range");
				sum += if iu.pos {
					delta
				} else {
					-delta
				};
			}
			sum
		};
		assert_eq!(sum, ROWS as i64, "the aggregated entry must carry the net delta");
		Ok(())
	}

	/// A commit that queues compaction work must wake the compactor, rather
	/// than leaving the queue to sit until the next tick.
	///
	/// The compaction interval and the write rate are otherwise unrelated, and
	/// that gap is what lets a count index's delta log — which every read of the
	/// index sums — grow without bound. The notification is what ties the two
	/// together.
	#[tokio::test]
	async fn commit_queuing_compaction_work_wakes_the_compactor() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(
			&ds,
			&session,
			"DEFINE TABLE item SCHEMALESS;
			 DEFINE INDEX idx_total ON item COUNT;",
		)
		.await?;

		// Wait on the trigger the background compactor waits on. Registering
		// before the write is what makes this deterministic rather than a race:
		// `Notify` also stores one permit, so a notification that lands before
		// the await still satisfies it.
		let triggers = Arc::clone(ds.commit_triggers());
		let waiter = tokio::spawn(async move {
			triggers.index_compaction.notified().await;
		});

		execute_all(&ds, &session, "CREATE item:1 RETURN NONE").await?;

		tokio::time::timeout(Duration::from_secs(5), waiter)
			.await
			.expect("a commit that queues compaction work must notify the compactor")
			.expect("the waiter task must not panic");
		Ok(())
	}

	/// A commit that queues no compaction work must not wake the compactor, so
	/// unrelated write traffic does not keep the lease check spinning.
	#[tokio::test]
	async fn commit_without_compaction_work_does_not_wake_the_compactor() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		// No COUNT (or other compaction-eligible) index, so nothing to queue.
		execute_all(&ds, &session, "DEFINE TABLE item SCHEMALESS;").await?;

		let triggers = Arc::clone(ds.commit_triggers());
		let waiter = tokio::spawn(async move {
			triggers.index_compaction.notified().await;
		});

		execute_all(&ds, &session, "CREATE item:1 RETURN NONE").await?;

		let woke = tokio::time::timeout(Duration::from_millis(300), waiter).await;
		assert!(woke.is_err(), "a write with no compaction work must not wake the compactor");
		Ok(())
	}

	/// Queues `count` async events and returns how many the event ran.
	async fn queue_async_events(ds: &Datastore, session: &Session, count: usize) -> Result<()> {
		execute_all(
			ds,
			session,
			"DEFINE TABLE person SCHEMALESS;
			 DEFINE TABLE logged SCHEMALESS;
			 DEFINE EVENT log ON person ASYNC THEN (CREATE logged SET who = $after.id);",
		)
		.await?;
		execute_all(ds, session, &format!("CREATE |person:{count}| RETURN NONE;")).await
	}

	async fn logged_count(ds: &Datastore, session: &Session) -> Result<usize> {
		let mut res = ds.execute("SELECT * FROM logged", session, None).await?;
		match res.remove(0).result? {
			PublicValue::Array(a) => Ok(a.len()),
			other => panic!("expected an array, got {other:?}"),
		}
	}

	/// Defines an async event with the given `RETRY` budget and queues exactly
	/// one of it.
	async fn queue_one_async_event(ds: &Datastore, session: &Session, retry: u16) -> Result<()> {
		execute_all(
			ds,
			session,
			&format!(
				"DEFINE TABLE person SCHEMALESS;
				 DEFINE TABLE logged SCHEMALESS;
				 DEFINE EVENT log ON person ASYNC RETRY {retry} \
				 THEN (CREATE logged SET who = $after.id);"
			),
		)
		.await?;
		execute_all(ds, session, "CREATE person:1 RETURN NONE;").await
	}

	/// Drains the queue the way [`Datastore::event_processing`] does, but with a
	/// bound, so a queue that stops draining fails the test instead of hanging
	/// it — which is the shape the failures under test take.
	async fn drain_event_queue(ds: &Datastore) -> Result<()> {
		for _ in 0..20 {
			if process_next_events_batch(ds, None).await? == 0 {
				return Ok(());
			}
		}
		panic!("the async event queue did not drain");
	}

	/// A retryable conflict on the commit that ends a queued event reports
	/// contention, not a failure of the event: the event still has to run, has
	/// to run exactly once, and must not spend the `RETRY` budget the definition
	/// reserved for a failing event. `RETRY 0` is what makes that last part
	/// observable — one charged attempt would drop the event instead of running
	/// it.
	///
	/// It pins the recovery path as well. `Transaction::commit` leaves the
	/// transaction finished whether or not it succeeds, so cancelling it
	/// afterwards reports `TransactionFinished` in place of the conflict; the
	/// entry is then neither re-run nor removed, and every later batch fetches
	/// and fails it again.
	#[test_log::test(tokio::test)]
	async fn a_queued_event_survives_commit_conflicts_without_spending_its_retries() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_one_async_event(&ds, &session, 0).await?;

		let site = RetryableConflictSite::AsyncEventCommit;
		// Fewer than the in-place bound, so every conflict is absorbed there.
		let _guard = inject_retryable_conflicts(site, ds.id(), 2);

		// Counting passes is what separates the two failures. Both conflicts are
		// absorbed within the pass that picked the entry up, so the first pass
		// finishes the event and the second finds the queue empty. An attempt
		// that ended by reporting `TransactionFinished` would leave the entry
		// for a later pass to fetch and fail again, and the second pass would
		// still find it.
		assert_eq!(
			process_next_events_batch(&ds, None).await?,
			1,
			"the queued event must be the one entry this pass picks up"
		);
		assert_eq!(
			process_next_events_batch(&ds, None).await?,
			0,
			"the entry must be gone: its conflicts belong to the pass that ran it"
		);

		assert_eq!(
			retryable_conflict_count(site, ds.id()),
			0,
			"both injected conflicts must have been raised, or the commit was never re-driven"
		);
		assert_eq!(
			logged_count(&ds, &session).await?,
			1,
			"the event must run exactly once; the conflicting attempts are rolled back"
		);
		Ok(())
	}

	/// Conflicts that outlast the in-place bound fall through to the
	/// definition's own `RETRY` budget, so an event that never wins the race
	/// still reaches a decision and its entry leaves the queue. Without that the
	/// drain loop does not return: it re-scans and re-fails the same entry for
	/// as long as this node holds the lease.
	#[test_log::test(tokio::test)]
	async fn a_queued_event_that_keeps_conflicting_leaves_the_queue() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_one_async_event(&ds, &session, 0).await?;

		let site = RetryableConflictSite::AsyncEventCommit;
		// More than any run can consume, so no attempt ever commits.
		let _guard = inject_retryable_conflicts(site, ds.id(), usize::MAX);

		drain_event_queue(&ds).await?;

		assert_eq!(
			logged_count(&ds, &session).await?,
			0,
			"no attempt committed, so the event left nothing behind"
		);
		Ok(())
	}

	/// Reads the queue the way a batch does, without running anything.
	async fn fetch_event_queue(ds: &Datastore) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
		let tx = ds.transaction(Read).await?;
		let res =
			tx.scan_raw(crate::key::schema::EventQueuePrefix {}.range()?, 1000, 0, None).await;
		tx.cancel().await?;
		res
	}

	/// A batch that fetched an entry another consumer has since run must not
	/// run it again. Batches overlap once the event-processing lease lapses, so
	/// two nodes can hold the same entry; only the first to commit runs it.
	#[test_log::test(tokio::test)]
	async fn an_event_run_by_an_overlapping_batch_is_not_run_again() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_one_async_event(&ds, &session, 1).await?;

		let stale = fetch_event_queue(&ds).await?;
		assert_eq!(stale.len(), 1, "the queued event must be the one entry fetched");
		drain_event_queue(&ds).await?;
		assert_eq!(logged_count(&ds, &session).await?, 1, "the first batch runs the event");

		crate::doc::process_events_batch(&ds, stale, None).await?;

		assert_eq!(
			logged_count(&ds, &session).await?,
			1,
			"the overlapping batch must find the entry gone rather than run it again"
		);
		assert!(
			fetch_event_queue(&ds).await?.is_empty(),
			"the overlapping batch must not requeue an entry that already ran"
		);
		Ok(())
	}

	/// A commit that applied but reported an unknown outcome has run the event
	/// and removed its entry. Requeueing on that report would run the event
	/// twice: `RETRY 1` is what makes that observable, since a charged attempt
	/// would put the entry back for a second pass to run.
	#[test_log::test(tokio::test)]
	async fn an_event_whose_commit_applied_unknown_is_not_run_again() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_one_async_event(&ds, &session, 1).await?;

		let site = NonRetryableErrorSite::AsyncEventCommitAppliedUnknown;
		let _guard = inject_non_retryable_error(site, ds.id());

		assert_eq!(process_next_events_batch(&ds, None).await?, 1);
		assert_eq!(
			process_next_events_batch(&ds, None).await?,
			0,
			"the applied commit removed the entry, so nothing may have put it back"
		);
		assert_eq!(logged_count(&ds, &session).await?, 1, "the event must run exactly once");
		Ok(())
	}

	/// A commit that reported an unknown outcome without applying has neither
	/// run the event nor removed its entry. Deleting the entry on that report
	/// would lose the event: `RETRY 0` is what makes that observable, since a
	/// charged attempt would exhaust the budget and delete it.
	#[test_log::test(tokio::test)]
	async fn an_event_whose_commit_was_discarded_unknown_still_runs() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_one_async_event(&ds, &session, 0).await?;

		let site = NonRetryableErrorSite::AsyncEventCommitDiscardedUnknown;
		let _guard = inject_non_retryable_error(site, ds.id());

		assert_eq!(process_next_events_batch(&ds, None).await?, 1);
		assert_eq!(
			process_next_events_batch(&ds, None).await?,
			0,
			"the unknown outcome belongs to the pass that ran the event"
		);
		assert_eq!(logged_count(&ds, &session).await?, 1, "the event must still run, once");
		Ok(())
	}

	/// An outcome that stays unknown past the in-place bound is never charged
	/// to the `RETRY` budget: the entry is left as the last commit left it, and
	/// a later pass runs it or finds it gone. `RETRY 0` is what makes that
	/// observable, since a charged attempt would delete the entry.
	#[test_log::test(tokio::test)]
	async fn an_event_whose_commit_outcome_stays_unknown_is_left_queued() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_one_async_event(&ds, &session, 0).await?;

		let site = NonRetryableErrorSite::AsyncEventCommitDiscardedUnknown;
		// Every attempt of the first pass: the first run and each in-place re-run.
		let _guard = inject_non_retryable_errors(site, ds.id(), 4);

		assert_eq!(process_next_events_batch(&ds, None).await?, 1);
		assert_eq!(logged_count(&ds, &session).await?, 0, "no attempt of the first pass applied");
		assert_eq!(
			fetch_event_queue(&ds).await?.len(),
			1,
			"an unknown outcome must leave the entry queued rather than delete it"
		);

		drain_event_queue(&ds).await?;
		assert_eq!(logged_count(&ds, &session).await?, 1, "a later pass runs the event");
		Ok(())
	}

	/// A cancelled pass must return at the next batch boundary rather than drain
	/// the queue. Async events run user-defined SurrealQL of unbounded duration,
	/// so a pass that ignored cancellation would hold [`Datastore::shutdown`]
	/// open for as long as the queue kept refilling.
	#[test_log::test(tokio::test)]
	async fn event_processing_returns_immediately_once_cancelled() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_async_events(&ds, &session, 50).await?;

		let canceller = CancellationToken::new();
		canceller.cancel();
		// Cancellation is not an error: the queue is durable, so what is left is
		// picked up by the next pass here or on another node.
		ds.event_processing(Duration::from_secs(1), &canceller).await?;
		assert_eq!(
			logged_count(&ds, &session).await?,
			0,
			"a cancelled pass must not process the queue"
		);
		Ok(())
	}

	/// The control for the test above: with a live token the same queue drains,
	/// so the early return is cancellation and not a broken pass.
	#[test_log::test(tokio::test)]
	async fn event_processing_drains_the_queue_when_not_cancelled() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		queue_async_events(&ds, &session, 50).await?;

		ds.event_processing(Duration::from_secs(1), &CancellationToken::new()).await?;
		assert_eq!(
			logged_count(&ds, &session).await?,
			50,
			"an uncancelled pass must drain the queue"
		);
		Ok(())
	}

	/// Two owners of one datastore may both call `shutdown`, which the sequence
	/// serialises so a second caller cannot close the storage engine while the
	/// first is still waiting on a maintenance pass.
	///
	/// This covers the liveness half of that: both callers complete and neither
	/// blocks on the other's guard. The exclusion itself is a property of holding
	/// the guard across the whole sequence, not something observable from
	/// outside without a test hook in the shutdown path.
	#[test_log::test(tokio::test)]
	async fn concurrent_shutdown_calls_both_complete() -> Result<()> {
		let ds = Datastore::new("memory").await?;
		let (first, second) = tokio::time::timeout(Duration::from_secs(30), async {
			tokio::join!(ds.shutdown(), ds.shutdown())
		})
		.await
		.map_err(|_| anyhow::anyhow!("concurrent shutdown deadlocked"))?;
		first?;
		second?;
		Ok(())
	}

	/// Mutations that cancel out within one transaction write no entry at all,
	/// and a read inside that transaction still sees its own uncommitted work.
	#[tokio::test]
	async fn count_index_nets_out_within_a_transaction() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(
			&ds,
			&session,
			"DEFINE TABLE item SCHEMALESS;
			 DEFINE INDEX idx_total ON item COUNT;",
		)
		.await?;
		let ikb = index_key_base(&ds, "item", "idx_total").await?;

		// A create and a delete of the same rows inside one transaction net to
		// zero, so there is no delta worth recording.
		execute_all(
			&ds,
			&session,
			"BEGIN;
			 CREATE |item:1..=50| RETURN NONE;
			 DELETE item:1..=50 RETURN NONE;
			 COMMIT;",
		)
		.await?;

		let deltas = {
			let txn = ds.transaction(Read).await?;
			let iu = IndexCountPrefix {
				ns: ikb.ns(),
				db: ikb.db(),
				tb: Cow::Borrowed(ikb.table()),
				ix: ikb.index(),
			}
			.range()?;
			let res = catch!(txn, txn.keys(iu, u32::MAX, 0, None).await);
			let _ = txn.cancel().await;
			res
		};
		assert!(
			deltas.is_empty(),
			"a net-zero transaction must write no delta, found {}",
			deltas.len()
		);

		// A read later in the same transaction as its writes must observe them,
		// even though the aggregate is not flushed until commit.
		let res = ds
			.execute(
				"BEGIN;
				 CREATE |item:100..=109| RETURN NONE;
				 SELECT count() FROM item GROUP ALL;
				 COMMIT;",
				&session,
				None,
			)
			.await?;
		// Locate the SELECT's result by content rather than by position, so the
		// assertion does not depend on how many results the surrounding
		// BEGIN/COMMIT contribute.
		let mut counted = None;
		for r in res {
			let rendered = format!("{:?}", r.result?);
			if rendered.contains("count") {
				counted = Some(rendered);
			}
		}
		let counted = counted.expect("the SELECT must produce a result");
		assert!(
			counted.contains("Int(10)"),
			"a read must see its own transaction's buffered deltas, got {counted}"
		);
		Ok(())
	}

	/// An undecodable `/!ic` entry must not wedge the drain: it names no
	/// index to compact, so the cycle skips it with a warning, deletes it
	/// with its batch, and continues serving the decodable entries.
	#[tokio::test]
	async fn index_compaction_quarantines_undecodable_queue_keys() -> Result<()> {
		let (ds, session) = new_index_compaction_test_ds().await?;
		let ds = ds;
		execute_all(
			&ds,
			&session,
			"DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;
			 DEFINE TABLE doc SCHEMALESS;
			 DEFINE INDEX ft_idx ON doc FIELDS text FULLTEXT ANALYZER simple BM25;",
		)
		.await?;
		let ikb = index_key_base(&ds, "doc", "ft_idx").await?;
		let node_id = ds.id();
		{
			let txn = ds.transaction(Write).await?;
			// The corrupt entry's 0xff lead byte sorts it after every valid
			// entry, so it lands last in the batch and exercises the
			// cursor-seek decode fallback as well as the dedupe-loop skip.
			for _ in 0..5 {
				txn.set_key(&ikb.new_ic_key(node_id), &()).await?;
			}
			txn.set(Key::from(b"/!ic\xff-not-a-valid-entry".to_vec()), vec![]).await?;
			txn.commit().await?;
		}

		let (batches, errors) = Datastore::index_compaction(
			Arc::clone(&ds),
			Duration::from_secs(60),
			CancellationToken::new(),
		)
		.await?;
		assert!(batches >= 1);
		assert_eq!(errors, 0, "a corrupt queue entry must not count as a compaction failure");

		// The queue is fully drained, corrupt entry included.
		let remaining = {
			let txn = ds.transaction(Read).await?;
			let res = txn.keys(IndexCompactionPrefix {}.range()?, u32::MAX, 0, None).await;
			let _ = txn.cancel().await;
			res?
		};
		assert!(remaining.is_empty(), "queue not drained: {} entries left", remaining.len());
		Ok(())
	}

	#[tokio::test]
	async fn archive_node_for_shutdown_reports_success() {
		let outcome = archive_node_for_shutdown(Duration::from_secs(60), Ok(()));

		assert_eq!(outcome, ShutdownNodeDeleteOutcome::Archived);
	}

	#[tokio::test]
	async fn archive_node_for_shutdown_reports_failure() {
		let outcome = archive_node_for_shutdown(
			Duration::from_secs(60),
			Err(anyhow::anyhow!("delete failed")),
		);

		assert_eq!(outcome, ShutdownNodeDeleteOutcome::Failed);
	}

	#[tokio::test]
	async fn archive_node_for_shutdown_reports_timeout() {
		let outcome = archive_node_for_shutdown(
			Duration::from_millis(1),
			Err(anyhow::Error::new(EngineError::QueryTimedout(Duration::from_millis(1)))),
		);

		assert_eq!(outcome, ShutdownNodeDeleteOutcome::TimedOut);
	}

	#[tokio::test]
	async fn node_tx_step_cancels_after_timeout() {
		let ds = Datastore::new("memory").await.unwrap();
		let txn = ds.transaction(Write).await.unwrap();
		let timeout_duration = Duration::from_millis(10);

		let err = await_node_tx_step(
			&txn,
			Instant::now() + timeout_duration,
			timeout_duration,
			None,
			pending::<Result<()>>(),
		)
		.await
		.unwrap_err();

		assert!(matches!(crate::err::engine_error(&err), Some(EngineError::QueryTimedout(_))));
		assert!(txn.closed());
	}

	#[tokio::test]
	async fn node_tx_step_cancels_after_cancellation() {
		let ds = Datastore::new("memory").await.unwrap();
		let txn = ds.transaction(Write).await.unwrap();
		let canceller = CancellationToken::new();
		canceller.cancel();

		let err = await_node_tx_step(
			&txn,
			Instant::now() + Duration::from_secs(60),
			Duration::from_secs(60),
			Some(&canceller),
			pending::<Result<()>>(),
		)
		.await
		.unwrap_err();

		assert!(matches!(crate::err::engine_error(&err), Some(EngineError::QueryCancelled)));
		assert!(txn.closed());
	}

	#[tokio::test]
	async fn node_tx_step_cancels_after_error() {
		let ds = Datastore::new("memory").await.unwrap();
		let txn = ds.transaction(Write).await.unwrap();

		let err = await_node_tx_step(
			&txn,
			Instant::now() + Duration::from_secs(60),
			Duration::from_secs(60),
			None,
			async { Err::<(), _>(anyhow::anyhow!("step failed")) },
		)
		.await
		.unwrap_err();

		assert_eq!(err.to_string(), "step failed");
		assert!(txn.closed());
	}

	#[tokio::test]
	async fn node_tx_step_success_leaves_transaction_open() {
		let ds = Datastore::new("memory").await.unwrap();
		let txn = ds.transaction(Write).await.unwrap();

		await_node_tx_step(
			&txn,
			Instant::now() + Duration::from_secs(60),
			Duration::from_secs(60),
			None,
			async { Ok::<_, anyhow::Error>(()) },
		)
		.await
		.unwrap();

		assert!(!txn.closed());
		txn.commit().await.unwrap();
		assert!(txn.closed());
	}

	#[tokio::test]
	async fn node_heartbeat_age_is_small_after_insert() {
		let ds = Datastore::new("memory").await.unwrap();
		// `insert_node` writes the current node's heartbeat at `clock_now()`.
		ds.insert_node().await.unwrap();
		let age = ds.node_heartbeat_age().await.unwrap().expect("the node row was just written");
		assert!(age < Duration::from_secs(5), "heartbeat should be fresh, got {age:?}");
	}

	/// A node with no membership row reports no heartbeat, rather than the read
	/// failure `get_node` raises for the same state. Readiness depends on the
	/// distinction: before `insert_node` runs, and after a peer archives and
	/// reaps this node, the row is legitimately absent.
	#[tokio::test]
	async fn node_heartbeat_age_is_absent_without_a_node_row() {
		let ds = Datastore::new("memory").await.unwrap();
		assert!(
			ds.node_heartbeat_age().await.unwrap().is_none(),
			"an unregistered node reported a heartbeat"
		);
	}

	#[tokio::test]
	async fn node_heartbeat_age_reflects_a_stale_heartbeat() {
		let ds = Datastore::new("memory").await.unwrap();
		// Write this node's registration with a heartbeat 60s in the past.
		let now = ds.clock_now().value;
		let stale = Node::new(
			ds.id(),
			Timestamp {
				value: now.saturating_sub(60_000),
			},
			false,
		);
		let key = NodeKey {
			nd: ds.id(),
		};
		let txn = ds.transaction(Write).await.unwrap();
		txn.set_key(&key, &stale).await.unwrap();
		txn.commit().await.unwrap();
		// The reported age should reflect the stale heartbeat.
		let age = ds.node_heartbeat_age().await.unwrap().expect("the node row was just written");
		assert!(age >= Duration::from_secs(59), "heartbeat should be stale, got {age:?}");
	}

	#[tokio::test]
	async fn test_setup_superuser() {
		let ds = Datastore::new("memory").await.unwrap();
		let username = "root";
		let password = "root";

		// Setup the initial user if there are no root users
		{
			let txn = ds.transaction(Read).await.unwrap();
			assert_eq!(txn.all_root_users(None).await.unwrap().len(), 0);
			txn.cancel().await.unwrap();
		}
		ds.initialise_credentials(username, password).await.unwrap();
		{
			let txn = ds.transaction(Read).await.unwrap();
			assert_eq!(txn.all_root_users(None).await.unwrap().len(), 1);
			txn.cancel().await.unwrap();
		}
		verify_root_creds(&ds, username, password).await.unwrap();

		// Do not setup the initial root user if there are root users:
		// Test the scenario by making sure the custom password doesn't change.
		let sql = "DEFINE USER root ON ROOT PASSWORD 'test' ROLES OWNER";
		let sess = Session::owner();
		ds.execute(sql, &sess, None).await.unwrap();
		let pass_hash = {
			let txn = ds.transaction(Read).await.unwrap();
			let res = txn.expect_root_user(username).await.unwrap().hash.clone();
			txn.cancel().await.unwrap();
			res
		};

		ds.initialise_credentials(username, password).await.unwrap();
		{
			let txn = ds.transaction(Read).await.unwrap();
			assert_eq!(pass_hash, txn.expect_root_user(username).await.unwrap().hash.clone());
			txn.cancel().await.unwrap();
		}
	}

	#[tokio::test]
	pub async fn very_deep_query() -> Result<()> {
		use reblessive::{Stack, Stk};

		use crate::expr::{BinaryOperator, Expr, Literal};
		use crate::kvs::Datastore;
		use crate::val::{Number, Value};

		// build query manually to bypass query limits.
		let mut stack = Stack::new();
		async fn build_query(stk: &mut Stk, depth: usize) -> Expr {
			if depth == 0 {
				Expr::Binary {
					left: Box::new(Expr::Literal(Literal::Integer(1))),
					op: BinaryOperator::Add,
					right: Box::new(Expr::Literal(Literal::Integer(1))),
				}
			} else {
				let q = stk.run(|stk| build_query(stk, depth - 1)).await;
				Expr::Binary {
					left: Box::new(q),
					op: BinaryOperator::Add,
					right: Box::new(Expr::Literal(Literal::Integer(1))),
				}
			}
		}
		let val = stack.enter(|stk| build_query(stk, 1000)).finish();

		let dbs = Datastore::builder()
			.with_capabilities(Capabilities::all())
			.build_with_path("memory")
			.await
			.unwrap();

		let opt = Options::new(&dbs.config().exec)
			.with_ns(Some("test".into()))
			.with_db(Some("test".into()))
			.with_max_computation_depth(u32::MAX);

		// Create a default context
		let mut ctx = dbs.setup_ctx()?;
		// Start a new transaction
		let txn = dbs.transaction(TransactionType::Read).await?.enclose();
		// Store the transaction
		ctx.set_transaction(Arc::clone(&txn));
		// Freeze the context
		let ctx = ctx.freeze();
		// Compute the value
		let mut stack = reblessive::tree::TreeStack::new();
		let res = stack
			.enter(|stk| crate::legacy::expr_compute(&val, stk, &ctx, &opt, None))
			.finish()
			.await
			.catch_return()
			.unwrap();
		assert_eq!(res, Value::Number(Number::Int(1002)));
		txn.cancel().await?;
		Ok(())
	}

	#[tokio::test]
	async fn cross_transaction_caching_uuids_updated() -> Result<()> {
		let (send, _recv) = crate::channel::bounded(surrealdb_cnf::NOTIFICATIONS_CHANNEL_SIZE);
		let ds = Datastore::builder()
			.with_capabilities(Capabilities::all())
			.with_notify(send)
			.build_with_path("memory")
			.await?;
		let ses = Session::owner().with_ns("test").with_db("test").with_rt(true);

		let db = {
			let txn = ds.transaction(TransactionType::Write).await?;
			let db = txn.ensure_ns_db(None, "test", "test").await?;
			txn.commit().await?;
			db
		};

		// Define the table, set the initial uuids
		let initial = {
			let sql = r"DEFINE TABLE test;".to_owned();
			let res = &mut ds.execute(&sql, &ses, None).await?;
			assert_eq!(res.len(), 1);
			res.remove(0).result.unwrap();
			// Obtain the initial uuids
			let txn = ds.transaction(TransactionType::Read).await?;
			let tb = TableName::from("test");
			let initial = txn.get_tb(db.namespace_id, db.database_id, &tb, None).await?.unwrap();
			txn.cancel().await?;
			initial
		};

		// Define some resources to refresh the UUIDs
		let lqid = {
			let sql = r"
				DEFINE FIELD test ON test;
			DEFINE EVENT test ON test WHEN {} THEN {};
			DEFINE TABLE view AS SELECT * FROM test;
			DEFINE INDEX test ON test FIELDS test;
			LIVE SELECT * FROM test;
			"
			.to_owned();
			let res = &mut ds.execute(&sql, &ses, None).await?;
			assert_eq!(res.len(), 5);
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
			let lqid = res.remove(0).result?;
			assert!(matches!(lqid, PublicValue::Uuid(_)));
			lqid
		};

		// Obtain the uuids after definitions
		let after_define = {
			let txn = ds.transaction(TransactionType::Read).await?;
			let tb = TableName::from("test");
			let after_define =
				txn.get_tb(db.namespace_id, db.database_id, &tb, None).await?.unwrap();
			txn.cancel().await?;
			// Compare uuids after definitions
			assert_ne!(initial.cache_indexes_ts, after_define.cache_indexes_ts);
			assert_ne!(initial.cache_tables_ts, after_define.cache_tables_ts);
			assert_ne!(initial.cache_events_ts, after_define.cache_events_ts);
			assert_ne!(initial.cache_fields_ts, after_define.cache_fields_ts);
			// LIVE bumped the committed live-query cache timestamp.
			assert_ne!(initial.cache_lives_ts, after_define.cache_lives_ts);
			after_define
		};

		// Remove the defined resources to refresh the UUIDs
		{
			let sql = r"
				REMOVE FIELD test ON test;
			REMOVE EVENT test ON test;
			REMOVE TABLE view;
			REMOVE INDEX test ON test;
			KILL $lqid;
			"
			.to_owned();
			let vars =
				PublicVariables::from(BTreeMap::from_iter(map! { "lqid".to_string() => lqid }));
			let res = &mut ds.execute(&sql, &ses, Some(vars)).await?;
			assert_eq!(res.len(), 5);
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
			res.remove(0).result.unwrap();
		}
		// Obtain the uuids after definitions
		{
			let txn = ds.transaction(TransactionType::Read).await?;
			let tb = TableName::from("test");
			let after_remove =
				txn.get_tb(db.namespace_id, db.database_id, &tb, None).await?.unwrap();
			txn.cancel().await?;
			// Compare uuids after definitions
			assert_ne!(after_define.cache_fields_ts, after_remove.cache_fields_ts);
			assert_ne!(after_define.cache_events_ts, after_remove.cache_events_ts);
			assert_ne!(after_define.cache_tables_ts, after_remove.cache_tables_ts);
			assert_ne!(after_define.cache_indexes_ts, after_remove.cache_indexes_ts);
			// KILL bumped the committed live-query cache timestamp.
			assert_ne!(after_define.cache_lives_ts, after_remove.cache_lives_ts);
		}
		//
		Ok(())
	}

	/// Exact-count accounting for the durable commits an indexed write incurs
	/// beyond its own statement transaction.
	///
	/// Groups every observed transaction completion by outcome, type and
	/// `keys_written`, so a per-record commit is distinguishable from a
	/// per-record cancel: a cancel costs nothing on a remote backend, a commit
	/// is a full durability round trip.
	#[derive(Default)]
	struct TxOutcomeObserver(std::sync::Mutex<Vec<(&'static str, bool, u64)>>);

	impl ExecutionObserver for TxOutcomeObserver {
		fn on_transaction_complete(&self, event: &crate::observe::TransactionEvent) {
			self.0.lock().unwrap().push((
				event.safe.outcome.as_label(),
				event.safe.write,
				event.safe.metrics.keys_written,
			));
		}
	}

	impl TxOutcomeObserver {
		fn take(&self) -> Vec<(&'static str, bool, u64)> {
			let mut g = self.0.lock().unwrap();
			std::mem::take(&mut *g)
		}
	}

	#[tokio::test]
	async fn doc_id_allocation_commits_per_record() -> Result<()> {
		// Windowed allocation makes the commit count flat in the row count. The
		// doc-ID window is `table_doc_ids_batch_size` wide (1000), so none of
		// these sizes exhausts one, and the builder commits per batch of
		// `INDEXING_BATCH_SIZE`. Persisting per allocation instead put this at
		// one commit per row, which is what the bounds below rule out: they sit
		// far under the smallest row count, so a per-row commit breaches them at
		// every size.
		const ROWS: [usize; 3] = [100, 200, 400];
		const INSERT_MAX: usize = 16;
		const BUILD_MAX: usize = 48;

		let mut observed = Vec::with_capacity(ROWS.len());
		for rows in ROWS {
			let (insert, build) = measure_doc_id_commits(rows).await?;
			assert!(
				insert <= INSERT_MAX,
				"{rows} indexed inserts took {insert} durable write commits, over the {INSERT_MAX} \
				 a windowed allocator needs"
			);
			assert!(
				build <= BUILD_MAX,
				"a DEFINE INDEX over {rows} rows took {build} durable write commits, over the \
				 {BUILD_MAX} a windowed allocator needs"
			);
			observed.push((insert, build));
		}

		// Flat in the row count, not merely bounded: quadrupling the rows must
		// not multiply the commits. A per-row commit shows up here as growth
		// proportional to `ROWS`, even were the caps above ever loosened.
		let (first_insert, first_build) = observed[0];
		let (last_insert, last_build) = observed[ROWS.len() - 1];
		let (first_rows, last_rows) = (ROWS[0], ROWS[ROWS.len() - 1]);
		assert!(
			last_insert <= first_insert * 2,
			"inserting {last_rows} rows took {last_insert} commits against {first_insert} for \
			 {first_rows}: the cost is tracking the row count"
		);
		assert!(
			last_build <= first_build * 2,
			"building over {last_rows} rows took {last_build} commits against {first_build} for \
			 {first_rows}: the cost is tracking the row count"
		);

		Ok(())
	}

	async fn measure_doc_id_commits(rows: usize) -> Result<(usize, usize)> {
		let observer = Arc::new(TxOutcomeObserver::default());
		let ds = Datastore::builder()
			.with_observer(Arc::clone(&observer) as Arc<dyn ExecutionObserver>)
			.without_maintenance_tasks()
			.build_with_path("memory")
			.await?;
		let session = Session::owner().with_ns("test").with_db("test");
		{
			let txn = ds.transaction(Write).await?;
			txn.ensure_ns_db(None, "test", "test").await?;
			txn.commit().await?;
		}

		let report = |label: &str, obs: Vec<(&'static str, bool, u64)>| -> usize {
			let mut h: BTreeMap<(&'static str, bool, u64), usize> = BTreeMap::new();
			for e in &obs {
				*h.entry(*e).or_default() += 1;
			}
			// A rollback reports `Outcome::Cancelled`, so a `success` write
			// completion is exactly a durable commit. Of those, the single-key
			// ones are the sequence state writes this test is about: nothing
			// else on this path commits exactly one key.
			let durable_writes = obs.iter().filter(|(o, w, _)| *o == "success" && *w).count();
			let seq_state = obs.iter().filter(|(o, w, k)| *o == "success" && *w && *k == 1).count();
			let per_row = durable_writes as f64 / rows as f64;
			println!(
				"  {label}: {durable_writes} durable write commits ({per_row:.3}/row), of which {seq_state} single-key sequence-state; {} completions total",
				obs.len()
			);
			for ((outcome, write, keys), n) in h {
				let kind = if write {
					"write"
				} else {
					"read "
				};
				println!("      {n:>4} x [{outcome:>9} {kind} keys_written={keys}]");
			}
			durable_writes
		};

		// Case A: inserts into a table that already carries a b-tree index.
		execute_all(
			&ds,
			&session,
			"DEFINE TABLE item SCHEMALESS;
			 DEFINE INDEX idx_name ON item FIELDS name;",
		)
		.await?;
		let _ = observer.take();
		execute_all(&ds, &session, &format!("CREATE |item:1..={rows}| SET name = 'x' RETURN NONE"))
			.await?;
		let insert_obs = observer.take();

		// Case B: DEFINE INDEX over rows that already exist.
		execute_all(&ds, &session, "DEFINE TABLE other SCHEMALESS;").await?;
		execute_all(
			&ds,
			&session,
			&format!("CREATE |other:1..={rows}| SET name = 'x' RETURN NONE"),
		)
		.await?;
		let _ = observer.take();
		execute_all(&ds, &session, "DEFINE INDEX idx_other ON other FIELDS name;").await?;
		let build_obs = observer.take();

		println!("\n  rows={rows}");
		let insert = report("insert", insert_obs);
		let build = report("build ", build_obs);

		Ok((insert, build))
	}

	/// A doc-ID is issued once. The forward map (record -> id) and the reverse
	/// map (id -> record) therefore hold one entry per record: reissuing an id
	/// overwrites a reverse entry, which leaves the reverse map short while the
	/// forward map stays whole.
	///
	/// The restart lands mid-window — the doc-ID batch is 1000 and far fewer
	/// records are written — which is the case a persisted per-allocation
	/// cursor used to cover and the window's committed end covers now. A
	/// restart keeps the node id, which is what makes the persisted allocator
	/// state reachable at all: it is keyed per node.
	#[tokio::test]
	async fn doc_ids_stay_unique_across_mid_batch_restart() -> Result<()> {
		const BEFORE: usize = 30;
		const AFTER: usize = 30;

		let (ds, session) = new_index_compaction_test_ds().await?;
		execute_all(
			&ds,
			&session,
			"DEFINE TABLE item SCHEMALESS;
			 DEFINE INDEX idx_tag ON item FIELDS tag;",
		)
		.await?;
		execute_all(
			&ds,
			&session,
			&format!("CREATE |item:1..={BEFORE}| SET tag = 'x' RETURN NONE"),
		)
		.await?;

		let ds = Arc::new(Arc::into_inner(ds).expect("sole owner of the datastore").restart());
		let lo = BEFORE + 1;
		let hi = BEFORE + AFTER;
		execute_all(&ds, &session, &format!("CREATE |item:{lo}..={hi}| SET tag = 'x' RETURN NONE"))
			.await?;

		let (forward, reverse) = doc_id_map_sizes(&ds, "item", "idx_tag").await?;

		assert_eq!(forward, BEFORE + AFTER, "one forward doc-ID mapping per record");
		assert_eq!(
			reverse,
			BEFORE + AFTER,
			"a reissued doc-ID overwrites a reverse mapping, leaving this map short"
		);

		Ok(())
	}

	/// The sizes of a table's doc-ID maps: the forward map keyed by record and
	/// the reverse map keyed by id. They hold one entry per record while every
	/// id is distinct; a reissued id overwrites a reverse entry, so the reverse
	/// map is where a collision becomes visible.
	async fn doc_id_map_sizes(ds: &Datastore, tb: &str, ix: &str) -> Result<(usize, usize)> {
		let ikb = index_key_base(ds, tb, ix).await?;
		let txn = ds.transaction(Read).await?;
		let forward = catch!(
			txn,
			txn.keys(
				DocLookupPrefix::new(ikb.ns(), ikb.db(), Cow::Borrowed(ikb.table())).range()?,
				u32::MAX,
				0,
				None
			)
			.await
		);
		let reverse = catch!(
			txn,
			txn.keys(
				DocKeyPrefix::new(ikb.ns(), ikb.db(), Cow::Borrowed(ikb.table())).range()?,
				u32::MAX,
				0,
				None
			)
			.await
		);
		let _ = txn.cancel().await;
		Ok((forward.len(), reverse.len()))
	}

	/// A record nested to [`MAX_VALUE_DEPTH`], the deepest the storage layer
	/// accepts.
	///
	/// It is grown one level per statement so no statement in the source is
	/// itself deeply nested: the depth reaches storage without ever passing
	/// through the query parser, which is what a restore has to read back.
	async fn seed_deepest_storable_record(ds: &Datastore, session: &Session) -> Result<()> {
		execute_all(ds, session, "CREATE deep:1 SET data = 'leaf' RETURN NONE;").await?;
		// The record object is the first level and the leaf the last, so the
		// wrappers between them carry the rest.
		for _ in 0..MAX_VALUE_DEPTH - 2 {
			execute_all(ds, session, "UPDATE deep:1 SET data = { l: data } RETURN NONE;").await?;
		}
		Ok(())
	}

	/// The SurrealQL an export renders a database as.
	async fn export_sql(ds: &Datastore, session: &Session) -> Result<String> {
		let (tx, rx) = crate::channel::bounded::<Vec<u8>>(16);
		let task = ds.export(session, tx).await?;
		let collector = tokio::spawn(async move {
			let mut out = Vec::new();
			while let Ok(chunk) = rx.recv().await {
				out.extend_from_slice(&chunk);
			}
			out
		});
		task.await?;
		Ok(String::from_utf8(collector.await?)?)
	}

	async fn empty_datastore(session: &Session) -> Result<Arc<Datastore>> {
		let ds = Datastore::new("memory").await?;
		let txn = ds.transaction(Write).await?;
		txn.ensure_ns_db(None, session.ns().unwrap().as_ref(), session.db().unwrap().as_ref())
			.await?;
		txn.commit().await?;
		Ok(ds)
	}

	/// A record at the deepest depth the storage layer accepts survives an
	/// export and a restore through both import entry points: what the writer
	/// accepted, an import can read back.
	///
	/// The comparison is between exports rather than query results: a
	/// statement result nests the record one level further than storage does,
	/// which the public-value conversion rejects, so a `SELECT` cannot observe
	/// a record at this depth at all.
	#[tokio::test]
	async fn deepest_storable_record_survives_the_round_trip() -> Result<()> {
		let session = Session::owner().with_ns("test").with_db("test");
		let source = empty_datastore(&session).await?;
		seed_deepest_storable_record(&source, &session).await?;
		let sql = export_sql(&source, &session).await?;

		let text_target = empty_datastore(&session).await?;
		for result in text_target.import(&sql, &session).await? {
			result.result?;
		}
		assert_eq!(export_sql(&text_target, &session).await?, sql, "restored from text");

		let stream_target = empty_datastore(&session).await?;
		let bytes = Bytes::from(sql.clone().into_bytes());
		let stream = futures::stream::once(async move { Ok(bytes) });
		for result in stream_target.import_stream(&session, stream).await? {
			result.result?;
		}
		assert_eq!(export_sql(&stream_target, &session).await?, sql, "restored from a stream");

		Ok(())
	}

	/// Every depth budget an import is read under stays above the deepest
	/// value the storage layer accepts. Raising [`MAX_VALUE_DEPTH`] without
	/// the parser profile, or narrowing the profile, would re-open the gap
	/// where a record can be written but the export of it cannot be restored.
	#[test]
	fn import_profile_clears_the_storable_value_depth() {
		let settings = Datastore::import_parser_settings(&Capabilities::default());
		for (budget, limit) in [
			("object", settings.object_recursion_limit),
			("query", settings.query_recursion_limit),
			("expression", settings.expr_recursion_limit),
		] {
			assert!(
				limit > MAX_VALUE_DEPTH,
				"the {budget} budget ({limit}) must clear the storable value depth \
				 ({MAX_VALUE_DEPTH})"
			);
		}
	}

	/// The deepest literal the import profile accepts is formatted, lowered
	/// and dropped within the call stack a worker thread running statements is
	/// guaranteed.
	///
	/// Parsing recurses on a heap-allocated `reblessive` stack, so depth alone
	/// costs nothing there; the `sql -> expr` lowering that follows, `ToSql`
	/// and the tree's own `Drop` recurse on the call stack, where exhaustion
	/// aborts the process rather than returning an error. A ceiling raised
	/// past what those survive fails here instead.
	///
	/// The budget is a fraction of `SURREAL_RUNTIME_STACK_SIZE`, which the
	/// server sizes well above this in both profiles precisely because these
	/// walks recurse. It cannot be set to the smallest stack an embedded
	/// caller might supply: frames are several times larger without
	/// optimisation, and this test runs unoptimised.
	///
	/// So what this bounds is the server. `SURREAL_RUNTIME_STACK_SIZE` is a
	/// server-only setting, and [`Datastore::import`] is also the embedded
	/// path — `EmbeddedEngine::import`, and `SurrealWasmEngine::import` under
	/// it. A wasm build takes the linker's default shadow stack, which this
	/// repository does not raise, and there a stack overflow is an unrecoverable
	/// trap rather than an abort a supervisor can restart. An embedded caller
	/// that accepts untrusted dumps is not covered by what is asserted here.
	#[test]
	fn import_profile_ceiling_is_stack_safe() {
		std::thread::Builder::new()
			.stack_size(8 * 1024 * 1024)
			.spawn(|| {
				let settings = Datastore::import_parser_settings(&Capabilities::default());
				let parse = |depth: usize| {
					let source = format!("{}'leaf'{}", "{ l: ".repeat(depth), " }".repeat(depth));
					crate::syn::parse_with_settings(
						source.as_bytes(),
						settings.clone(),
						async |parser, stk| parser.parse_expr_field(stk).await,
					)
				};

				// The deepest literal the profile accepts, so the tree the
				// recursive consumers below are handed is its worst case.
				let mut depth = settings.expr_recursion_limit;
				while parse(depth).is_err() {
					depth -= 1;
					assert!(
						depth > MAX_VALUE_DEPTH,
						"the profile accepts a literal at the storable value depth"
					);
				}
				assert!(parse(depth + 1).is_err(), "the search stopped at the ceiling");

				let expr = parse(depth).expect("the deepest accepted literal parses");
				// `ToSql` recurses once per node.
				assert!(surrealdb_types::ToSql::to_sql(&expr).contains("leaf"));
				// The lowering recurses once per node, and dropping what it
				// produces recurses once per node again.
				drop(crate::expr::Expr::from(expr));
			})
			.unwrap()
			.join()
			.unwrap();
	}
}